blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
3945241d765ca9f123408cc6fe6574a1fba9d6e3
aukoyy/sandbox
/python-practice/foundamentals/dictionaries.py
437
4.59375
5
# Initiated with curly braces # Consists of key value pairs student = {'name': 'john', 'age': 25, 'courses': ['Math', 'CompSci']} # These are ways of accessing values by keys print(student['name']) print(student.get('name')) # [] method of access will produce a keyerror if none is found. The {} method returns none # Looping keys for key in student: print(key) # Looping items for key, value in student.items(): print(key, value)
e1b4ed2be7b156677d3254ae159b5a25fd13bc29
crjerry/gitworksm
/python_study/trim.py
188
3.890625
4
def trim(s): if s[0] == " " and s[-1] == " ": return s[1:-1] elif s[0] == " ": return s[1:] elif s[-1] == " ": return s[:-1] else: return s
6c958e04e88cce477eb71a3db4096b3ce1a5629b
josenaldo/python-learning
/exercicios/extras/tartaruga.py
225
3.984375
4
def main(): for numero in [5, 4, 3, 2, 1, 0]: print("Eu tenho", numero, "biscoitos. Vou comer um.") #----------------------------------------------- # a linha a seguir inicia a execução do programa main()
425efcc6df64b16d27e1bc614807f2c287d26b9c
moontasirabtahee/Problem-Solving
/CodeForce/443A. Anton and Letters.py
315
3.890625
4
def anton_and_letters(): inp = input() letters = [l for l in inp[1:len(inp)-1].split(', ') if l] letter_set = set() for letter in letters: if letter not in letter_set: letter_set.add(letter) return len(letter_set) if __name__ == '__main__': print(anton_and_letters())
be2775e0392059585b92de9c7a5f5165481360d2
Piper-Rains/Sandbox
/password_check.py
427
4.15625
4
MIN_LENGTH = 4 print("Please enter a valid password, with a length no less than {}".format(MIN_LENGTH)) password = input("> ") while len(password) < MIN_LENGTH: print("Invalid password length") print("Please enter a valid password, with a length no less than {}".format(MIN_LENGTH)) password = input("> ") print("Your password has been approved:") for i in range(len(password)): print("*", end=' ') print()
ff94cd313169a951514c41d3df8ad36bd7b16300
Risoko/Algorithm
/hash_table_open_addressing.py
1,901
3.859375
4
class HashTable: """Hash table using open addressing""" def __init__(self, size): assert type(size) == int, "Must be type int" self.table = [None for _ in range(size)] self.size = size def _hash_function(self, key): """Helpty hash function.""" return key % self.size def _main_hash_function(self, key): """Main hash function.""" for idx in range(self.size): yield (self._hash_function(key) + idx) % self.size def _slot_is_empty(self, idx): """Check slot is empty""" return self.table[idx] is None or self.table[idx] == "DELETE" def insert(self, key, data): """Insert key wit data to hash table.""" for idx in self._main_hash_function(key): if self._slot_is_empty(idx): self.table[idx] = (key, data) return True raise Exception('Hash table is full.') def search(self, key): """Search key in hashtable, return Data.""" for idx in self._main_hash_function(key): if self.table[idx][0] == key: return self.table[idx][1] elif self.table[idx] == None: break return False def delete(self, key): """Delete key and data with hash table.""" for idx in self._main_hash_function(key): if self.table[idx][0] == key: self.table[idx] = 'DELETE' return True elif self._slot_is_empty(idx): break return False def __repr__(self): return f'{self.table}' if __name__ =="__main__": a = HashTable(11) for idx in range(11): a.insert(idx, idx**2) print(a) print(a.search(10)) print(a.delete(0)) print(a) print(a.insert(10, 'ok')) print(a)
54c269ef09a17b57f3c25c169677a0dd50d32acd
matatablack/clyphx-pro_user-actiolns
/template/utils/log_utils.py
1,434
3.5625
4
def _make_member_desc(member_name, member): return '{} <{}>'.format(member_name, type(member).__name__) def dumpobj(obj, show_callables=False): '''A debugging function that prints out the names and values of all the members of the given object. Very useful for inspecting objects in interactive sessions''' txt = 'TYPE: %s\n' % type(obj).__name__ members = {} for name in dir(obj): try: members[name] = getattr(obj, name) except Exception as e: members[name] = 'EXCEPTION getting value: %s - %s' % (type(e), str(e)) members = {name: member for name, member in members.items() if name not in ('__builtins__', '__doc__')} members = {name: member for name, member in members.items() if not name.startswith('__') and not name.endswith('__')} if not show_callables: members = {name: member for name, member in members.items() if not callable(member)} if len(members) == 0: txt += ' <EMPTY>\n' return txt max_desc_len = max([len(_make_member_desc(k, v)) for k, v in members.items()]) items = list(members.items()) items.sort() for name, member in items: member_desc = _make_member_desc(name, member) txt += ' {} = {}\n'.format(member_desc.ljust(max_desc_len), member) return txt def str2bool(v): return v.lower() in ("yes", "true", "t", "1")
02f40516e510fa87f184572e0ba9ced1a30b24ed
TerryLun/Code-Playground
/HackerRank Problems/halloween_sale.py
271
3.640625
4
""" https://www.hackerrank.com/challenges/halloween-sale/problem """ def howManyGames(p, d, m, s): r = 0 while s > 0: s -= p p = max(p - d, m) r += 1 print(s) return r if s == 0 else r - 1 print(howManyGames(20, 3, 6, 80))
343b6f81c4ef10ac84a8efc4c2dc0213b231558c
cdimattina/MPI_Python
/FIBNUM/fibo.py
1,187
3.875
4
""" fibo.py Description: This computes the fibonacci sequence for multiple inputs using a serial process (one core only) Basic fibonacci sequence calculation base case: f(1) = 1 f(2) = 1 recursion: f(n) = f(n-1) + f(n-2) , n > 2 Usage: python3 fibo.py <n1> <n2> ... <nK> """ import sys import time import fibomod as fb num_args = len(sys.argv) args = sys.argv def check_valid(inlist): is_valid = 1 for i in range(1,len(inlist)): if(int(inlist[i])<1): is_valid = 0 return is_valid if(num_args > 1): # Make sure all arguments are valid is_valid = check_valid(args) # For all the inputs, sequentially compute the requested Fibonacci number if(is_valid): t0 = time.time() for i in range(1,num_args): answer = fb.calc_fibo(int(args[i])) outStr = "The " + str(args[i]) + "-th Fibonacci number is: " + str(answer) print(outStr) t1 = time.time() wt = t1-t0 timeStr = "Wall time = " + str("{:.4}".format(wt)) + " seconds" print(timeStr) else: print("Usage: fibo <n1> <n2> ... <nK>, all inputs integers > 0") else: print("Usage: fibo <n1> <n2> ... <nK>, all inputs integers > 0")
3fa3ba230b8ee6e97e39e861246e0ae7a9030804
shanwan/python3-course
/firstProgram/attack_basic.py
831
3.75
4
import random class Enemy: hp = 200 def __init__(self, attacklow, attackhigh): self.attacklow = attacklow self.attackhigh = attackhigh def getAttack(self): print("Attack is ",self.attacklow) def getHp(self): print("Hp is", self.hp) enemy1 = Enemy(40, 49) enemy1.getAttack() enemy1.getHp() enemy2 = Enemy(50, 59) enemy2.getAttack() enemy2.getHp() ''' playerhp = 260 enemyattacklow = 60 enemyattackhigh = 80 while playerhp > 0: damage = random.randrange(enemyattacklow, enemyattackhigh) playerhp = playerhp - damage if playerhp <= 30: playerhp = 30 print("Enemy strikes ",damage ,"damage points.You have ",playerhp ," hp left.") if playerhp == 30: print("You have low health. You have been teleported to a hospital.") break '''
2b087280c1da108ad7ce29330362571a61ccdd31
Hamng/hamnguyen-sources
/python/sort_by_column.py
1,766
4.1875
4
# -*- coding: utf-8 -*- """ Created on Mon Feb 25 09:25:10 2019 @author: Ham HackerRanch Challenge: Athele Sort Task You are given a spreadsheet that contains a list of N athletes and their details (such as age, height, weight and so on). You are required to sort the data based on the K-th attribute and print the final resulting table. Follow the example given below for better understanding. image Note that K is indexed from 0 to M - 1, where M is the number of attributes. Note: If two attributes are the same for different rows, for example, if two atheletes are of the same age, print the row that appeared first in the input. Input Format The first line contains N and M separated by a space. The next N lines each contain M elements. The last line contains K. Constraints Each element Output Format Print the lines of the sorted table. Each line should contain the space separated elements. Check the sample below for clarity. Sample Input 0 (see stdin_sim below) Sample Output 0 7 1 0 10 2 5 6 5 9 9 9 9 1 23 12 """ from operator import itemgetter stdin_sim = """ 5 3 10 2 5 7 1 0 9 9 9 1 23 12 6 5 9 1 """ stdin_sim = stdin_sim.strip().splitlines() if __name__ == '__main__': #n, m = map(int, input().split()) n, m = map(int, stdin_sim.pop(0).split()) #arr = [map(int, input().rstrip().split()) for _ in range(n)] arr = [list(map(int, stdin_sim.pop(0).rstrip().split())) for _ in range(n)] #k = int(input()) k = int(stdin_sim.pop(0)) #[print(" ".join([str(e) for e in l])) for l in sorted(arr, key=itemgetter(k))] print(*((" ".join([str(e) for e in l])) for l in sorted(arr, key=itemgetter(k))), sep="\n")
f0f9ffe06f8c07f1657b93e61a490ff3d8e66e0d
cognosphere/intro-to-python
/Class 6 - Comparison & Boolean Operators/comparison_operators.py
1,803
4.65625
5
#Comparison Operators: ==,!=, >, <, >=, <= print("== Operator") print(2==2) #This will return True print(1==2) #This will return False print("----------") print("!= Operator") print(2!=2) #This will return False print(1!=2) #This will return True print("----------") print("> Operator") print(3>2) #This will return True print(1>2) #This will return False print("----------") print("< Operator") print(3<2) #This will return False print(1<2) #This will return True print("----------") print(">= Operator") print(3>=2) #This will return True print(2>=2) #This will return True print(1>=2) #This will return False print("----------") print("<= Operator") print(3<=2) #This will return False print(2<=2) #This will return True print(1<=2) #This will return True print("----------") #Chained Comparison Operators print(1<2<3) #will return True print(1<2>3) #will return False #different method- "and" keyword checks if both conditions are true print(1<2 and 2<3) #will return True print(1<2 and 2>3) #will return False print(2==2 and 3==3) #will return True #use different comparison operators at once print(2==2 and 3!=2) #will return True #or keyword checks if one of the conditions are true print(2==2 or 1<2) #will return True print(1<2 or 2<3 or 5<100 or 5<=100 or 2!=2 or 5==5) #will return True ''' PRACTICE Define a variable as an integer (you can choose any number) ex. number = 5 Take user input to get another number Print the boolean (True or False) of the number you defined and the number the user gave with the == comparison operator. ''' my_num = 5 user_num = int(input("Please enter a number: ")) print(my_num==user_num) ''' Note: If you don't put int(input()) instead of input, then it will always return False because one type is an integer and one type is a string '''
0dcb4d8336183ee6bcb9f0b16990c27c745fbe6d
NizanHulq/Kuliah-Python
/struktur_data/Stack_/InfixPostfix.py
2,405
3.75
4
# ini membuat class stack class Stack: def __init__(self,max): self.top = -1 self.stackSize = max self.datum = [] def isEmpty(self): if self.top == -1: return True else: return False def isFull(self): if self.top == self.stackSize-1 : return True else: return False def push(self, datum): if self.top == self.stackSize-1 : self.top = self.top else: self.top = self.top + 1 self.datum.insert(self.top,datum) def pop(self): if self.top == -1: self.top = self.top else: self.top = self.top - 1 return self.datum.pop(self.top+1) def peek(self): if self.top == -1: self.top = self.top else: return self.datum[self.top] # ini mulai masuk ke algoritma cara mengkonversi dari infix ke postfix # operator yang digunakan hanya +,-,*,/ def prioritas(komponen): if komponen == '*' or komponen == '/' : return 3 elif komponen == '+' or komponen == '-' : return 2 elif komponen == '(' or komponen == ')' : return 1 else: return 1 # input harus pake spasi infix = input('masukkan operasi infix(batasan operator "+ , - , * , /" ) : ').split() postfix = [] operator = Stack(50) # untuk memasukkan setiap anggota list infix ke dalam list opstfix atau stack operator for i in infix : if i in "1234567890" : # 1 postfix.append(i) else: if operator.isEmpty() == True: # 2 operator.push(i) else: if i == '(' : # 3 operator.push(i) elif i == ')' : # 4 while operator.peek() != '(': postfix.append(operator.pop()) operator.pop() elif i in ['+','-','*','/'] : # 5 if operator.isEmpty() != True: if prioritas(i) <= prioritas(operator.peek()): # 6 postfix.append(operator.pop()) operator.push(i) else: operator.push(i) else: # 7 operator.push(i) while operator.isEmpty() != True: postfix.append(operator.pop()) print('operasi postfix : ',' '.join(postfix))
c533718b58d64be5339e60529d11fbcfb1f2c77b
tailaiwang/Competitive-Programming
/wcipeg/sorting.py
236
3.578125
4
#sorting list1=[] out=[] n=int(input()) for i in range(n): c=int(input()) list1.append(c) for i in range(len(list1)): out1=min(list1) list1.remove(out1) out.append(out1) for i in out: print(i)
b71a067f8b38475a8c493fb13306a2fbcbe37ee9
osnaldy/Python-StartingOut
/chapter2/SalesPrediction.py
167
3.5
4
sales = float(raw_input("Enter the annual sales: ")) print "The Annual sale is ", sales expected_profit = sales * 0.23 print "Expected annual profit ", expected_profit
57c4c89319467a04ef6b11282772f94b5819f318
ieuan-jones/Doodle
/snake.py
4,294
3.90625
4
from doodle import * # A function to add a berry to the screen def add_berry(berries, snake): # First try and place the berry randomly new_berry = [rand(0,31), rand(0,23)] # If it's hitting the snake, or another berry, move it while new_berry in berries or new_berry in snake: new_berry = [rand(0,31), rand(0,23)] # When it's a good place, add it to the list of berries! berries.append(new_berry) # Directions RIGHT = (1, 0) LEFT = (-1, 0) UP = (0, -1) DOWN = (0, 1) # Load the images berry_image = load("berry.png") snake_image = load("snake.png") head_image = load("head.png") rotated_head_image = head_image # Create our snake and berries snake = [[3,5],[4,5],[5,5],[6,5]] berries = [[rand(0,31), rand(0,23)]] add_berry(berries, snake) # Keep track of the score score = 0 # The direction the snake is travelling in direction = (1, 0) last_direction = direction # These help us keep control of time time_since_update = 0 game_speed = 0.3 # Finally make the window make_window(640,480) while True: # If fps is 0, we will be dividing by 0 # This is bad, so make sure the fps is over 0 if get_fps() > 0: # This tells us how many seconds have passed since the last loop time_since_update += 1.0 / get_fps() # Check for input from the player # We check the last direction so going the opposite direction # doesn't kill you! if keydown("left") and last_direction != RIGHT: direction = LEFT rotated_head_image = rotate_picture(head_image, 180) elif keydown("right") and last_direction != LEFT: direction = RIGHT rotated_head_image = rotate_picture(head_image, 0) elif keydown("up") and last_direction != DOWN: direction = UP rotated_head_image = rotate_picture(head_image, 90) elif keydown("down") and last_direction != UP: direction = DOWN rotated_head_image = rotate_picture(head_image, 270) # Draw the world, and write the score fill("green") write("Score: "+str(score), (20, 20), "black") # Draw each snake segment in turn # We miss the last segment as this is the head, which we want to draw separately for segment in snake[:-1]: segment_x = segment[0] * 20 segment_y = segment[1] * 20 draw_picture(snake_image, (segment_x, segment_y)) # Draw the head segment_x = snake[-1][0] * 20 segment_y = snake[-1][1] * 20 draw_picture(rotated_head_image, (segment_x, segment_y)) # And the same for the berries for berry in berries: berry_x = berry[0] * 20 berry_y = berry[1] * 20 draw_picture(berry_image, (berry_x, berry_y)) # Move the snake, but only when enough time has passed if time_since_update > game_speed: # Find the position in front of the snake new_segment = [snake[-1][0] + direction[0], snake[-1][1] + direction[1]] # Check the snake didn't hit itself! if new_segment not in snake[1:]: # Check the snake hasn't gone off the side of the screen if new_segment[0] >= 0 and new_segment[0] <= 31: # And make sure it hasn't gone off the top or bottom if new_segment[1] >= 0 and new_segment[1] <= 23: snake.append(new_segment) # Check if we hit a berry if new_segment not in berries: # If we didn't, don't grow! snake.pop(0) else: # If we did, add a new berry and remove the old one add_berry(berries, snake) berries.remove(new_segment) score += 1 # We want to make the game faster if they hit a snake game_speed = 1.5 / len(snake) else: stop() else: stop() else: stop() # We updated now, so set the time to 0 time_since_update = 0 last_direction = direction next_frame()
507e337ed5c1b39d1da53fd1cc8da1f741e491e5
Daehyun-Bigbread/Bigbread-Python
/python_for_everyone/10A-count.py
257
3.8125
4
# while 명령으로 반복해서 숫자를 출력하는 프로그램 print("[1-10]") x = 1 while x <= 10: # x가 10 이하인 동안 반복(1에서 10까지 실행) print(x) x = x + 1 # x에 1을 더해서 저장합니다.
1f8c2b26fa7fdf13dd2ad875557c3b96f99fe79c
kjh03160/Algorithm_Basic
/Kakao_Intern_2021/1.py
465
3.625
4
def solution(s): answer = '' mapping = {'zero': 0, 'one': 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9} temp = '' for string in s: if string.isdigit(): answer += string else: temp += string if temp in mapping: answer += str(mapping[temp]) temp ='' answer = int(answer) return answer s = "one4seveneight" print(solution(s))
330a013b6d875cb41d27c95594574fe732b7491f
suhassrivats/Data-Structures-And-Algorithms-Implementation
/Problems/Leetcode/49_GroupAnagrams.py
447
3.640625
4
class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: """ Time Complexity: O(n.slog(s)) // n is len of input, s is len of string Space Complexity (auxiliary): O(n.s) // total information content stored in dict """ dict = {} for word in strs: key = tuple(sorted(word)) dict[key] = dict.get(key, []) + [word] return dict.values()
1cb336b334bfb92e007ec099a10b9a42a1bf7f63
smzztx/pythonlearn
/4advancedcharacter/split.py
173
3.734375
4
#!/usr/bin/env python L=['michael','sarah','tracy','bob','jack'] print L print L[0:3] print L[:3] print L[1:3] print L[:-2] T=(1,2,3,4,5,6,7,8,9,10) print T print T[:3]
da875fe759f55aaeb229db1d7c07f0402ac6b4d5
walterbeddoe/Batch17python
/operadoresMatematicos.py
599
3.71875
4
#x = 10 #y = 4 #suma = x + y #print(suma) # #resta = x - y #print(resta) # #multiplicacion = x * y #print(multiplicacion) # #division = x / y #print(division) # #division_redondeado = x // y #print(division_redondeado) # #residuo = x % y #print(residuo) # #exponencial = x **2 #print(exponencial) x = 4 y = 9 z = 10 print( +x+y+z ) #1 print( ( x+y ) / z) #2 print( (x * y ) +z) #3 print( z % x ) #4 print( y**2 ) #5 print( (x**2)/( y+z )) #6 print( (z/x)/10 ) #7 exp = x**y print(exp) cel = 1 result = (cel * 1.8)+32 print(result)
8b313d62f1a464040aada513feba2157202b1af4
HUGGY1174/MyPython
/Ch05/Lab01.py
408
3.828125
4
frind_list = [] a = input("친구의 이름을입력하시오.") frind_list.append(a) a = input("친구의 이름을입력하시오.") frind_list.append(a) a = input("친구의 이름을입력하시오.") frind_list.append(a) a = input("친구의 이름을입력하시오.") frind_list.append(a) a = input("친구의 이름을입력하시오.") frind_list.append(a) print(frind_list)
9bc0af8efdcdee32c9853fe36fe8bda62ca36e8d
marjan-sz/CodeSignal_Solutions
/removeDuplicateStrings.py
1,179
4.0625
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Feb 28 22:01:27 2020 @author: marjan Question: Remove all duplicates from an already sorted (in lexicographical order) array of strings. Redefine the question: a) an array of strings is given as input/array is sorted b) remove all duplicates from the array c) return an array of unique strings Consider all possible cases: a) if the input is not an array, return TypeError b) if the input array has integers or floats, remove them Steps to solve the problem: a) Define a set to store unique elements of the input array b) For each element in the array, check if it does not exist in the set, add it c) Return the set """ def removeDuplicateStrings(inputArray): if not isinstance(inputArray, list): return TypeError my_set = set() for x in inputArray: if (x not in my_set) and (isinstance(x, str)): my_set.add(x) tmp = list(my_set) tmp.sort() tmp.sort(key = len) return tmp inputArray = ['a', 'a', 'ab', 'acd', 'ab', 'ab', 'abc', 'abc', 'acdesg', 2, 3.4] print(removeDuplicateStrings(inputArray))
4d3425816630376568f313d146d573b6563d49b7
panpan7/panpan7.github.io
/example/Python/string.py
716
4.09375
4
s = 'string' print(len(s)) print(s[0]) # 输出序列的第一个元素 print(s[-1]) # 输出字符串的最后一个元素 print(s[1:3]) # 输出字符串的第2-3个字符,不包含第4个字符 t = '这是个中文字符串' print(len(t)) # 使用+运算符合并字符串 print(s + t) # 使用*运算符复制字符传 print(s * 3) # 使用字符串对象的内置方法 print(s.find('in')) print(s.replace('g', 'gs')) # 虽然显示字符串已被替换,但实际上是一个新的字符串。 # 字符串类型是不可变性类型 print(s) # 得到字符串对象所有的属性和方法 print(dir(s)) # 内置的帮助函数 print(help(s.upper)) # s[0] = 'another s' # print(s)
7a495dbbd0c56c7398808eb2d1eb79b3f7c3f93d
dictator-x/practise_as
/algorithm/leetCode/0148_sort_list.py
1,146
3.984375
4
""" 148. Sort List """ class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def sortList(self, head: ListNode) -> ListNode: if not head or not head.next: return head def middle(head): slow, fast = head, head while fast and fast.next and fast.next.next: print(fast.val) slow = slow.next fast = fast.next.next return slow def merge(list1, list2): ret = ListNode() temp = ret while list1 and list2: if list1.val < list2.val: temp.next = list1 list1 = list1.next else: temp.next = list2 list2 = list2.next temp = temp.next temp.next = list1 or list2 return ret.next middle_node = middle(head) right = middle_node.next #Important: break inner connection. middle_node.next = None return merge(self.sortList(head), self.sortList(right))
3948de62dbd37ba62778521c634812470d3bb29b
Jonathan-aguilar/DAS_Sistemas
/Ago-Dic-2019/Jorge Alberto Hernandez Sanchez/Practicas/Practica1/5.2_More_Conditional_Tests.py
718
3.9375
4
car = "Mercedez" print("Is car == 'Mercedez'? I predict True") print(car == "Mercedez") print("\nIs car == 'Seat'? Ipredict False") print(car == "Seat") print("############################################") car = "Ford" print(car.lower() == "ford") car = "Seat" print(car.lower() == "Seat") print("############################################") number = 2 print("Is number == 2? I predict True") print(number == 2) print("\nIs number == 3? I predict False") print(number == 3) print("############################################") palabra = ["Uno", "Dos", "Tres"] print("Is palabra == 'Dos'? I predict True") print("Dos" in palabra) print("\nIs palabra == 'Cuatro'? I predict False") print("Cuatro" in palabra)
dcd7bafbb8ab0ac07083d8fac8a6d9aab4087a48
souravskr/MS-Project
/Experiments/venv/lib/python3.7/site-packages/cnfgen/families/pigeonhole.py
8,948
3.71875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- """Implementation of the pigeonhole principle formulas """ from cnfgen.cnf import CNF from cnfgen.graphs import bipartite_sets from itertools import combinations, product def PigeonholePrinciple(pigeons, holes, functional=False, onto=False): """Pigeonhole Principle CNF formula The pigeonhole principle claims that no M pigeons can sit in N pigeonholes without collision if M>N. The counterpositive CNF formulation requires such mapping to be satisfied. There are different variants of this formula, depending on the values of `functional` and `onto` argument. - PHP: pigeon can sit in multiple holes - FPHP: each pigeon sits in exactly one hole - onto-PHP: pigeon can sit in multiple holes, every hole must be covered. - Matching: one-to-one bijection between pigeons and holes. Arguments: - `pigeon`: number of pigeons - `hole`: number of holes - `functional`: add clauses to enforce at most one hole per pigeon - `onto`: add clauses to enforce that any hole must have a pigeon >>> print(PigeonholePrinciple(4,3).dimacs(export_header=False)) p cnf 12 22 1 2 3 0 4 5 6 0 7 8 9 0 10 11 12 0 -1 -4 0 -1 -7 0 -1 -10 0 -4 -7 0 -4 -10 0 -7 -10 0 -2 -5 0 -2 -8 0 -2 -11 0 -5 -8 0 -5 -11 0 -8 -11 0 -3 -6 0 -3 -9 0 -3 -12 0 -6 -9 0 -6 -12 0 -9 -12 0 """ def var_name(p, h): return 'p_{{{0},{1}}}'.format(p, h) if functional: if onto: formula_name = "Matching" else: formula_name = "Functional pigeonhole principle" else: if onto: formula_name = "Onto pigeonhole principle" else: formula_name = "Pigeonhole principle" description = "{0} formula for {1} pigeons and {2} holes".format( formula_name, pigeons, holes) php = CNF(description=description) if pigeons < 0 or holes < 0: raise ValueError( "Number of pigeons and holes must both be non negative") mapping = php.unary_mapping(range(1, pigeons + 1), range(1, holes + 1), var_name=var_name, injective=True, functional=functional, surjective=onto) for v in mapping.variables(): php.add_variable(v) for c in mapping.clauses(): php.add_clause_unsafe(c) return php def GraphPigeonholePrinciple(graph, functional=False, onto=False): """Graph Pigeonhole Principle CNF formula The graph pigeonhole principle CNF formula, defined on a bipartite graph G=(L,R,E), claims that there is a subset E' of the edges such that every vertex on the left size L has at least one incident edge in E' and every edge on the right side R has at most one incident edge in E'. This is possible only if the graph has a matching of size |L|. There are different variants of this formula, depending on the values of `functional` and `onto` argument. - PHP(G): each left vertex can be incident to multiple edges in E' - FPHP(G): each left vertex must be incident to exaclty one edge in E' - onto-PHP: all right vertices must be incident to some vertex - matching: E' must be a perfect matching between L and R Arguments: - `graph` : bipartite graph - `functional`: add clauses to enforce at most one edge per left vertex - `onto`: add clauses to enforce that any right vertex has one incident edge Remark: the graph vertices must have the 'bipartite' attribute set. Left vertices must have it set to 0 and the right ones to 1. A KeyException is raised otherwise. """ def var_name(p, h): return 'p_{{{0},{1}}}'.format(p, h) if functional: if onto: formula_name = "Graph matching" else: formula_name = "Graph functional pigeonhole principle" else: if onto: formula_name = "Graph onto pigeonhole principle" else: formula_name = "Graph pigeonhole principle" description = "{0} formula on {1}".format(formula_name, graph.name) gphp = CNF(description=description) Left, Right = bipartite_sets(graph) mapping = gphp.unary_mapping(Left, Right, sparsity_pattern=graph, var_name=var_name, injective=True, functional=functional, surjective=onto) for v in mapping.variables(): gphp.add_variable(v) for c in mapping.clauses(): gphp.add_clause_unsafe(c) return gphp def BinaryPigeonholePrinciple(pigeons, holes): """Binary Pigeonhole Principle CNF formula The pigeonhole principle claims that no M pigeons can sit in N pigeonholes without collision if M>N. This formula encodes the principle using binary strings to identify the holes. Parameters ---------- pigeon : int number of pigeons holes : int number of holes """ description = "Binary Pigeonhole Principle for {0} pigeons and {1} holes".format( pigeons, holes) bphp = CNF(description=description) if pigeons < 0 or holes < 0: raise ValueError( "Number of pigeons and holes must both be non negative") bphpgen = bphp.binary_mapping(range(1, pigeons + 1), range(1, holes + 1), injective=True) for v in bphpgen.variables(): bphp.add_variable(v) for c in bphpgen.clauses(): bphp.add_clause_unsafe(c) return bphp def RelativizedPigeonholePrinciple(pigeons, resting_places, holes): """Relativized Pigeonhole Principle CNF formula The formula claims that pigeons can fly into holes with no conflicts, with the additional caveat that before landing in a hole, each pigeon stops in some resting place. No two pigeons can rest in the same place. A description can be found in [1]_ Parameters ---------- pigeons: int number of pigeons resting_places: int number of resting places holes: int number of holes References ---------- .. [1] A. Atserias, M. Lauria and J. Nordström Narrow Proofs May Be Maximally Long IEEE Conference on Computational Complexity 2014 """ rphp = CNF() rphp.header[ 'description'] = "Relativized pigeonhole principle formula for {0} pigeons, {1} resting places and {2} holes".format( pigeons, resting_places, holes) if pigeons < 0: raise ValueError('The number of pigeons must be non-negative') if resting_places < 0: raise ValueError('The number of resting places must be non-negative') if holes < 0: raise ValueError('The number of holes must be non-negative') def p(u, v): return 'p_{{{0},{1}}}'.format(u, v) def q(v, w): return 'q_{{{0},{1}}}'.format(v, w) def r(v): return 'r_{{{0}}}'.format(v) U = range(1, 1 + pigeons) V = range(1, 1 + resting_places) W = range(1, 1 + holes) for u, v in product(U, V): rphp.add_variable(p(u, v)) for v, w in product(V, W): rphp.add_variable(q(v, w)) for v in V: rphp.add_variable(r(v)) # NOTE: the order of ranges in the products are chosen such that related clauses appear after each other # (3.1a) p[u,1] v p[u,2] v ... v p[u,n] for all u \in [k] # Each pigeon goes into a resting place for u in U: rphp.add_clause([(True, p(u, v)) for v in V], strict=True) # (3.1b) ~p[u,v] v ~p[u',v] for all u, u' \in [k], u != u', v \in [n] # no conflict on any resting place for (v, (u, u_)) in product(V, combinations(U, 2)): rphp.add_clause([(False, p(u, v)), (False, p(u_, v))], strict=True) # (3.1c) ~p[u,v] v r[v] for all u \in [k], v \in [n] # resting place activation for (v, u) in product(V, U): rphp.add_clause([(False, p(u, v)), (True, r(v))], strict=True) # (3.1d) ~r[v] v q[v,1] v ... v q[v,k-1] for all v \in [n] # pigeons leave the resting place for v in V: rphp.add_clause([(False, r(v))] + [(True, q(v, w)) for w in W], strict=True) # (3.1e) ~r[v] v ~r[v'] v ~q[v,w] v ~q[v',w] for all v, v' \in [n], v != v', w \in [k-1] # no conflict on any hole, for two pigeons coming from two resting places for (w, (v, v_)) in product(W, combinations(V, 2)): rphp.add_clause([(False, r(v)), (False, r(v_)), (False, q(v, w)), (False, q(v_, w))], strict=True) return rphp
f7d7910fbe6829e78b8e8ea76b6d7cc4bc84e6cb
tuinfor/Data-Structure-And-Algorithmns
/Codepath/Linked list/Asignments - Hackerrank/Plus One Linked List.py
1,725
3.65625
4
''' Given a non-negative integer representatted as a non-empty singly linked liswt of digits, add one to the integer. You may assume the integer do not contain any leading zero, except the number 0 itself The digits are stored such as that the most significant dif is at the head of the list Input: 1->2->3 Output: 1-> 2-> 4 ''' # Two pointers solution. class Solution(object): def plusOne(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return None dummy = ListNode(0) dummy.next = head left, right = dummy, head while right.next: if right.val != 9: left = right right = right.next if right.val != 9: right.val += 1 else: left.val += 1 right = left.next while right: right.val = 0 right = right.next return dummy if dummy.val else dummy.next # Time: O(n) # Space: O(1) class Solution2(object): def plusOne(self, head): """ :type head: ListNode :rtype: ListNode """ def reverseList(head): dummy = ListNode(0) curr = head while curr: dummy.next, curr.next, curr = curr, dummy.next, curr.next return dummy.next rev_head = reverseList(head) curr, carry = rev_head, 1 while curr and carry: curr.val += carry carry = curr.val / 10 curr.val %= 10 if carry and curr.next is None: curr.next = ListNode(0) curr = curr.next return reverseList(rev_head)
5061ab5533c712226e72a5f66acab16ea2236f1e
ShannonCanTech/Python-Crash-Course
/ChapterOne/stripping_whitespace.py
451
4.15625
4
email = input("Enter your email: ") #Adds whitespace to the right of the output, then strips it away print("'" + email + '\t' + "'") print("'" + email.rstrip() + "'") # Adds whitespce to the left of the output, then strips it away print("'" + '\t' + email + "'") print("'" + email.lstrip() + "'") # Adds whitespace to both the left and right of the output, then strips it away print("'" + '\t'+ email + '\t' + "'") print("'" + email.strip() + "'")
112748b77d8d9cd6792f9386f94b390e36a23241
gavinbarrett/ScriptObscurer
/obscure.py
500
3.625
4
def hexpad(character): ''' Return a padded hex encoding of an ascii character ''' character = hex(ord(character))[2:] if len(character) == 1: return '0' + character return character def html_entity_encode(string): ''' Encode an ascii string as HTML entities ''' return ''.join([f'&#x{hexpad(c)};' for c in string]) if __name__ == "__main__": str1 = "alert('1337')"; str2 = "for (let i in [1,2,3]) alert(i);"; encoded = html_entity_encode(str2) print(f"<svg onload={''.join(encoded)}>")
21d3fcbc8e788472f18c65cb49f447ee51b30583
bormanjo/py-snake
/snake.py
2,496
3.796875
4
import config class FIFOQueue(object): '''A First-in First-out priority Queue of fixed capacity''' def __init__(self, *args, capacity: int): self._data = list(args) self.set_capacity(capacity) def __repr__(self): return self._data.__repr__() def __str__(self): return self._data.__str__() def __iter__(self): return self._data.__iter__() def __len__(self): return self._data.__len__() def __getitem__(self, i): return self._data[i] def trim(self, n: int): '''Return the list trimmed to capacity n''' if n <= 0: raise ValueError(f'Expected n to be >= 1, got: {n}') res = self._data[n:] self._data = self._data[:n] return res def set_capacity(self, n: int): '''Set the capacity of the list to n''' if not isinstance(n, int): raise ValueError(f'Expected n to be an integer, got: {type(n)}') if n <= 0: raise ValueError(f'Expected n to be >= 1, got: {n}') self._capacity = n return self.trim(n) def get_capacity(self): return self._capacity def add_cappacity(self, i: int): self.set_capacity(self._capacity + abs(i)) def at_capacity(self): return self._capacity == len(self._data) def add(self, item): ''' Add the item to the list Pops and returns the oldest item if at capacity (before adding item). Otherwise returns None ''' res = self._data.pop() if self.at_capacity() else None self._data = [item] + self._data return res def pop(self): return self._data.pop() def first(self): return self._data[0] def last(self): return self._data[len(self._data)] class Snake(object): def __init__(self, pos): self.pos = FIFOQueue(*pos, capacity=len(pos)) self.head_color = config.snake_head_color self.color = config.snake_color def __repr__(self): return self.pos.__repr__() def __str__(self): return self.pos.__str__() def __iter__(self): return self.pos.__iter__() def __getitem__(self, i): return self.__getitem__(i) def add(self, new_pos): return self.pos.add(new_pos) def grow(self, i: int): self.pos.add_cappacity(i) def head(self): return self.pos.first() def last(self): return self.pos.last()
57b8850414670d4ff065e260aa6b0a089d345d74
Anshum4512501/dsa
/graphs/graph_transpose.py
1,004
3.78125
4
# Graph Transpose # O(V+E) times # O(V2) in if using adjacency matrix from collections import defaultdict class GraphAbstract: def __init__(self,nodes): self.nodes = nodes self.adj_list = defaultdict(list) def addedge(self,u,v): self.adj_list[u].append(v) def printgraph(self): for node in self.nodes: print(node,"->",self.adj_list[node]) class GraphTranspose(GraphAbstract): pass class Graph(GraphAbstract): def transpose(self): graphtranspose = GraphTranspose(self.nodes) for node in self.nodes: for item in self.adj_list[node]: graphtranspose.addedge(item,node) return graphtranspose graph = Graph(["A","B","C","D","E"]) graph.addedge("A","B") graph.addedge("A","C") graph.addedge("B","D") graph.addedge("D","C") graph.addedge("D","E") graph.addedge("E","C") graph.printgraph() graphtranspose = graph.transpose() print("\n") graphtranspose.printgraph()
46528dbc058be6bc3d6ed8460e3b623131524718
DokiStar/my-lpthw-lib
/ex7.py
724
4.28125
4
# 输出一个字符串 print("Mary had a little lamb") # 输出一个字符串,将字符串“snow”嵌入前面的字符串 print("Its fleece was white as {}.".format('snow')) # 输出一个字符串 print("And everywhere that Mary went.") # 输出10个句点,使用*运算符重载实现 print("." * 10) # 定义12个(字符型/字符串型)变量 end1 = "c" end2 = "h" end3 = "e" end4 = "e" end5 = "s" end6 = "e" end7 = "b" end8 = "ue" end9 = "r" end10 = "g" end11 = "e" end12 = "r" # 输出由前六个变量拼接形成的字符串,以空格结尾 print(end1 + end2 + end3 + end4 + end5 + end6, end=' ') # 输出由后六个变量拼接形成的字符串 print(end7 + end8 + end9 + end10 + end11 + end12)
8c9501603728eb82ed2fe923e6d1ed7213289c35
eruns/GUI
/Rules_orig.py
6,399
3.671875
4
from Hand import * from Deck import * from Enums.Rank import * class Rules(object): """Defines the rules of go fish game.""" def __init__(self, deck=None, points=None, books=None): """Creates deck object. Args: deck (deck): all cards. """ self.deck = None self._points = 0 self._books = None self.deck = deck @property def points(self): """ Getter: Tracks the p1_points points. Returns (int): p1_points """ return self._points @property def books(self): """ Getter: Tracks the number of books. Returns (int): books """ return self._books def card_request(self): """Gets the requested card rank from the player. Returns: request (string): requested card rank. """ request = int(input("Enter a card rank you like to collect (1-13).")) return Rank(request) def player_answer(self, request, p2): """Gets the answer from the other player. Args: request (string): requested card rank. Returns: answer (string): answer from the other player. """ if p2.count_rank(request): answer = "YES" elif not p2.count_rank(request): answer = "GOFISH" return answer def book_check(self, request, p1): """Checks if the player have a book. Args: request (string): requested card rank. p1 (array) : p1 cards. Returns: book (arry): Four suit of one rank. """ book = p1.count_rank(request) return book def count_request(self, p2, request): """Counts the number of the requested rank in p2. Args: p2 (array): array of cards for the other player. Returns: p1 (array): array of cards for the player. p2 (array): array of cards for the other player. """ req_num = p2.count_rank(request) # print("p2 has" + " " + str(req_num) + " " + "of" + " " + str(request)) return req_num def check_deck(self): """Count's the number of cards in the deck. Args: deck (array): array of cards in the deck. Returns: p1 (array): array of cards for the player. Deck (array): array of cards in the deck. """ deck_count = self.deck.count return deck_count def play_game(self, p1, p2): """Plays the Go Fish game. Args: p1 (array): first player cards. p2 (array): the other player cards. Returns: True : player take another turn. False: player turn ended. """ request = self.card_request() answer = self.player_answer(request, p2) """If p2 has the requested rank (answer = YES).""" if answer.upper() == "YES": for card in p2.cards: if card.rank == request: move_card = p2.play_card(card) p1.add_card(move_card) """Checks if p1 has a book of requested rank.""" book = self.book_check(request, p1) """If p1 has book(four suit of one rank).""" if book == 4: p1.find_and_remove(request) self._points += 1 self._books += 1 """If p1 is empty from cards.""" if p1.card_count == 0: deck_count = self.check_deck() """If deck has less than 5 cards.""" if deck_count < 5: for i in range(deck_count): p1.add_card(self.deck.deal()) print("Player turn ended.") return False """If deck has more than 5 cards.""" else: for i in range(0, 4): p1.add_card(self.deck.deal()) return False print("Player turn ended.") return False print("Player take another turn,") return True """Answer is GOFISH (p2 does not have the requested card).""" else: for card in p2.cards: if card.rank == request: print("Player is cheating.") return True deck_count = self.check_deck() if deck_count != 0: card = self.deck.deal() p1.add_card(card) book = self.book_check(card, p1) """Player has a book or got requested card from the deck.""" if book == 4 and request == card: print("Show the card.") p1.find_and_remove(request) self._points += 1 self._books += 1 print("player gets" + " " + str(self.points) + " " + "points") print("player take another turn.") return True """Player got the requested card from the deck.""" elif book != 4 and request == card: print("Show the card.") print("p1 take another turn.") return True """Player has a book.""" elif book == 4 and request != card: p1.find_and_remove(request) self._points += 1 self._books += 1 print("p1 gets" + " " + str(self.points) + " " + "points") return False """No book, No requested card.""" else: print("p1 turn is ended") return False """ Deck is empty.""" else: print("Deck is empty, players keep playing.") return False def main(): play_game(self, p1, p2) if __name__ == '__main__': main()
1a9f6664c38047941be5acb46f37f67703b684c4
ximuwang/Python_Crash_Course
/Chap8_Functions/Practice/8-8 User Albums.py
1,060
4.03125
4
# 8-8 User albums def make_album(artist, title, tracks = 0): '''Build a dictionary containing the info about an album''' music_album = {'artist': artist.title(), 'title': title.title(), } if tracks: music_album['tracks'] = tracks return music_album album = make_album('Beattles', 'Abbey Road', tracks = 8) print(album) album = make_album('metallica', 'ride the lighting') print(album) album = make_album('beethoven', 'ninth symphony') print(album) album = make_album('willie nelson', 'red-head stranger') print(album) # prepare the prompts artist_prompt = 'Who is the artist: ' title_prompt = '\nWhat albums are you thinking of: ' # Let user know how to quit: print('(Enter "q" anytime to quit)') while True: title = input(title_prompt).title() if title == "q" or 'Q': break artist = input(artist_prompt).title() if artist == "q" or 'Q': break album = make_album(artist, title) print(album) print('\nThanks for your response')
0becc906f497decb23e19e73c7f35eba911f5edf
haochi/raspberry-pi-tasks
/time-announcer
167
3.734375
4
#!/usr/bin/python3 from datetime import datetime now = datetime.now() print("It is {} {} {} right now".format(now.hour % 12, now.strftime('%M'), now.strftime('%p')))
3097696dc8fad57e80325bbcbf8f6d58a402b6b7
Vanshika-RJIT/python-programs
/positional arguments or keyword arguments.py
219
3.671875
4
#positional arguments def add(n1,n2): print(n1) print(n2) s=n1+n2 print(s) add(2,3) #keyword arguments def add(n1,n2): print(n1) print(n2) s=n1+n2 print(s) add(n2=2,n1=3)
e1a799cf996ec3b32f171f41fce7db3f9bf9e611
GriffH/school-files
/project_1/hausken_griff_todays_date.py
151
3.984375
4
from datetime import date #importing date module todaydate = date.today() #gets the date print("Today's date is: ", todaydate) #displays date
de6a9b38fee45959803e942bd83ce889563fb518
Telos4/ICFP-Contest-2015
/Texts/freq.py
481
3.5625
4
#!/usr/bin/python from collections import defaultdict from collections import OrderedDict import pickle # words = "apple banana apple strawberry banana lemon" datf = open("others_combined.txt", 'r') words = datf.read() datf.close() # meh # words.decode('utf-8').lower() d = defaultdict(int) for word in words.split(): for letter in word: d[letter] += 1 od = OrderedDict(sorted(d.items())) print od f = open("words.pickle", 'w') pickle.dump(od, f) f.close()
ccf8b0a1fed04f30463a1102226393041283313b
ZhouNan1212/LeetCode
/DataStructure/Queue.py
908
4.25
4
# -*- coding: utf-8 -*- class Queue(object): # 无限长队列,这里可以设置队列长度 # 初始化队列为空列表 def __init__(self): self.items = [] # 判断队列是否为空,返回布尔值 def is_empty(self): return self.items == [] # 返回队列的大小 def size(self): return len(self.items) # 返回队首的元素 def queue_first(self): return self.items[0] # 返回队尾的元素 def queue_last(self): return self.items[len(self.items) - 1] # 将一个元素插入队列 def enqueue(self, element): return self.items.append(element) # 队首元素出队列 def dequeue(self): first = self.items[0] del self.items[0] return first if __name__ == "__main__": s = Queue() s.enqueue(1) s.enqueue(2) s.enqueue(3) s.dequeue()
435f9f5fe78e3a985efc9d152c630e4924c1cc98
klw11j/Financial-and-Election-Analysis-Python
/PyBank/Analysis/main.py
1,958
3.78125
4
import os import csv csvpath = os.path.join('..', 'Resources', 'budget_data.csv') total_months = [] total_profit = [] profit_change = [] with open(csvpath) as csvfile: csvreader = csv.reader(csvfile, delimiter=',') csv_header = next(csvreader) for row in csvreader: total_months.append(row[0]) total_profit.append(int(row[1])) #find monthly change in profit by iterating through the profits for i in range(len(total_profit)-1): profit_change.append(total_profit[i+1]-(total_profit[i])) #find greatest increase and decrease in profits greatest_increase_profits = max(profit_change) greatest_decrease_profits = min(profit_change) #greatest increase month k = profit_change.index(greatest_increase_profits) greatest_increase_month = total_months[k+1] #greatest decrease month j = profit_change.index(greatest_decrease_profits) greatest_decrease_month = total_months[j+1] #print statements print("Financial Analysis") print("-----------------------------------") print(f"Total Months: {len(total_months)}") print(f"Total: ${sum(total_profit)}") print(f"Average Change: {round(sum(profit_change)/len(profit_change),2)}") print(f"Greatest Increase in Profits:{greatest_increase_month} (${greatest_increase_profits})") print(f"Greatest Decrease in Profits:{greatest_decrease_month} (${greatest_decrease_profits})") with open('financial_analysis.txt', 'w') as text: text.write("Financial Analysis") text.write("-----------------------------------") text.write(f"Total Months: {len(total_months)}") text.write(f"Total: ${sum(total_profit)}") text.write(f"Average Change: {round(sum(profit_change)/len(profit_change),2)}") text.write(f"Greatest Increase in Profits:{greatest_increase_month} (${greatest_increase_profits})") text.write(f"Greatest Decrease in Profits:{greatest_decrease_month} (${greatest_decrease_profits})")
ec9836d172488b69f03e7be545c62f8c69930335
LuisC18/ws_simple_pickup
/my_grasping/src/process_path.py
2,397
3.625
4
#!/usr/bin/env python def prepare_path_transforms_list(path_source, scaling_factor=0.100): import csv import numpy as np # Load solution path from CSV into numpy Array with open(path_source) as csvfile: dataList = list(csv.reader(csvfile, delimiter=',')) path = np.array(dataList[0:], dtype=np.float) path = np.append(path, np.zeros((path.shape[0],1)),1) if False: print(path) print(path.shape) # Assuming Each pixel to be a 1x1 METER square. We will scale down to a reasonable size. #scaling_factor = 0.100 # 10 cm path_scaled = path*scaling_factor return path_scaled def prepare_path_tf_ready(path_list): """ Convenience Function to Convert Path from a List of xyz points to Transformation Matrices :param path_list: Input must be list type with cell formatting of XYZ :return: List of Transformation Matrices """ import numpy as np from transformations import transformations tf = transformations() rot_default = np.identity(3) new_list = [] for vector in path_list: item = np.matrix(vector) new_list.append( tf.generateTransMatrix(rot_default, item) ) return new_list def main(): """ DEMONSTRATION CODE - Shows how to use the path processing tools included in this file. """ print("-------DEMONSTRATION CODE---------") # Visualize Demo w/ Visualizations Module from visualizations import plot_path_vectors, plot_path_transforms #Process Path into Flat Vector Plane path_as_xyz = prepare_path_transforms_list('tiny_path_soln.csv') print(" Visual: Path as XYZ in Flat Vector Plane") plot_path_vectors(path_as_xyz) # Convert Cartesian Points to Transformation List path_as_tf_matrices = prepare_path_tf_ready(path_as_xyz) print(" Visual: Path as Homogeneous Transformation Matrices (list thereof)") plot_path_transforms(path_as_tf_matrices) # Generate Example Transformation Matrix import numpy as np from transformations import transformations tf = transformations() #body_rot = np.identity(3) body_rot = np.matrix('0 -1 0; 1 0 0; 0 0 1') # rot(z,90deg) body_transl = np.matrix('0; 0; 0') body_frame = tf.generateTransMatrix(body_rot, body_transl) new_path = tf.convertPath2FixedFrame(path_as_tf_matrices, body_frame) print(" Visual: Rigid Body Transformation Applied") plot_path_transforms(new_path) if __name__ == '__main__': main()
01c2937df5ed2f12f113aec4133531b608125b12
NiravModiRepo/Coding
/OOD/DesignPatterns/factory.py
449
3.859375
4
# -*- coding: utf-8 -*- """ Created on Fri Nov 2 15:28:41 2018 @author: Nirav Modi https://www.youtube.com/watch?v=flOXIdWUpmU Factory Method """ #A design patter which lets a function which class to create BaseClass = type("BaseClass", (object,),{}) C1 = type("C1", (BaseClass,), {"x":1}) C2 = type("C2", (BaseClass,), {"x":30}) def MyFactory(myBool): return C1() if myBool else C2() m = MyFactory(True) v = MyFactory(False) print(m.x, v.x)
4fd9657d6c53a053601a04472a1789ae8607a382
bakunobu/exercise
/1400_basic_tasks/chap_8/ex_8_15.py
736
3.765625
4
def seq_qunc(x:int) -> float: num = x ** 2 + 100 den = x + 200 return(num / den) def calc_less_nums(my_func, min_value:float, max_value:float) -> None: while True: try: m = float(input('Введите число: ')) if min_value <= m <= max_value: break else: print(f'Число должно быть в интервале {min_value}:{max_value}.') except ValueError: print('Используйте целые числа и десятичные дроби!') i = 1 while my_func(i) < m: print(my_func(i)) i += 1 calc_less_nums(seq_qunc, 0.52, 33.7)
e2b36c88abaca12f6ebcf5503b9e10bb1ff3d6a6
MTGTsunami/LeetPython
/src/leetcode/math/202. Happy Number.py
917
3.78125
4
""" Write an algorithm to determine if a number is "happy". A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers. Example: Input: 19 Output: true Explanation: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1 """ class MySolution(object): def isHappy(self, n): """ :type n: int :rtype: bool """ visited = set() num = n while num not in visited and num != 1: visited.add(num) count = 0 for d in str(num): count += int(d) ** 2 num = count return True if num == 1 else False
59432f2c8382816a320066934d7e3f32cfe86f60
Mapoet/py_ggcm
/ggcm_re.py
4,001
4.0625
4
from re import * SCI = "[+-]?\d+\.\d+[eE][-+]?\d+" DEC = "[+-]?\d+\.\d+" INT = "[+-]?\d+" num_patt_dict = {'dec':DEC, 'DEC':DEC, 'sci':SCI, 'SCI':SCI, 'int':INT, 'INT':INT} any_num_patt = ".*?(%(sci)s|%(dec)s|%(int)s)" % num_patt_dict def find(pattern, string, flags = 0): result = search(pattern, string, flags) if result != None: return True else: return False def findNum(string, numtype = None): ''' Method to determine if there are of the standard number formats are present in a string. If numtype is specified, only numbers of that type will cause the function to return True. ''' if numtype != None: patt = num_patt_dict[numtype] else: patt = any_num_patt return find(patt, string) def retrieve(pattern, string, flags = 0): re_out = compile(pattern, flags).findall(string) if not len(re_out): raise error("No matches for %s in:\n%s" % (pattern, string)) return re_out def retrieveNums(string, multi = True, numtype = None): ''' Method to retrieve a number of set of numbers from a string. The values of those numbers will be returned in the order found. ''' # If the user specified a particular type of number (int, sci, or dec) if numtype != None: patt = num_patt_dict[numtype] else: patt = any_num_patt # Get the numbers re_n_list = retrieve(patt % num_patt_dict, string) n_list = [] for n in re_n_list: if numtype == 'sci' or numtype == 'SCI' or find(SCI, n): n_list.append(float(n)) elif numtype == 'dec' or numtype == 'DEC' or find(DEC, n): n_list.append(float(n)) else: n_list.append(int(n)) return n_list def replace(patt, string, new_str = "", new_fmt = "", reorder = None, flags = 0): ''' A regular expression based method to replace a piece of `string`. There are two main options: - (Simple) If `new_str` is specified, the match for `patt` will be replaced by `new_str`. - (Not Simple) If `new_fmt` is specified, and for every %s in `new_fmt` there is exactly one parenthetical capture in `patt`, then the items captured from string will be placed in `new_fmt`, reordered according to `reorder`, which may be either a list or a dict, where the index/key applies to the order in `patt` and the values apply to the order in `new_fmt`. The result will replace piece matched by `patt.` If neither `new_str` nor `new_fmt` are specified, `patt` will be replace with an empty string (i.e. removed). `flags` may be specified as for any other regular expression. ''' # If there a format was given, get the data for the format if new_fmt != '': old = search(patt.replace(")", "").replace("(", ""), string, flags) if not old: return string old = old.group(0) finds = search(patt, string, flags).groups() # If the results are reordered in the format if reorder != None: if isinstance(reorder, dict): iters = reorder.iteritems() elif isinstance(reorder, list) or isinstance(reorder, tuple): iters = enumerate(reorder) else: raise TypeError("Reorder must be an iterable (list, tuple, or dict), not %s" % type(reorder)) d_in = {} for i0, i1 in iters: d_in[i1] = finds[i0] # The dict will automatically sort by key inputs = tuple(d_in.values()) else: inputs = tuple(finds) new = new_fmt % inputs else: # Get the entire section of string to be replaced old = search(patt, string, flags) if not old: return string old = old.group(0) new = new_str return string.replace(old, new)
019e5614141e62e6c32481227794dc323b74d809
ykambham/mydev1
/stringexamples/sum_of_all_sub_strings.py
1,048
4.09375
4
# Sum of all sub strings # Complexity o(n2) def sub_strings(str1): sub_strings_list = [] for i in range(len(str1)): for j in range(i, len(str1) + 1): sub_strings_list.append(str1[i:j]) return sub_strings_list def sum_of_sub_strings(str1): return sum(int(a) for a in sub_strings(str1) if a) # Same problem with complexity O(n)) ''' For above example, sumofdigit[3] = 4 + 34 + 234 + 1234 = 4 + 30 + 4 + 230 + 4 + 1230 + 4 = 4*4 + 10*(3 + 23 +123) = 4*4 + 10*(sumofdigit[2]) In general, sumofdigit[i] = (i+1)*num[i] + 10*sumofdigit[i-1] ''' def sum_of_sub_strings1(str1): sum_of_digit = {} sum_of_digit[0] = int(str1[0]) sum = sum_of_digit[0] for i in range(1, len(str1)): sum_of_digit[i] = (i+1) * int(str1[i]) + 10 * sum_of_digit[i-1] sum += sum_of_digit[i] return sum import time t1 = time.time() print sum_of_sub_strings("12345") print time.time() - t1 t2 = time.time() print sum_of_sub_strings1("12345") print time.time() - t2
85b17bd3d3eb3a738573b2537c7201130821dd8b
ajay-jayanth/Python-NLP
/nlp_script.py
1,993
3.5
4
''' Author: Ajay Jayanth Date: 9/22/20 Description: Naive Bayes Algroithm predicts the Content Category feature of text using a tf-idf vectorized set of text data ''' # C:\Users\msctb\AppData\Local\Programs\Python\Python38-32\Scripts import pandas as pd import sklearn from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn import metrics MainDf = pd.read_csv('Label-Sample200.csv') #print(MainDf) ''' Check for NaNs [FIXED] is_NaN = MainDf.isnull() row_has_NaN = is_NaN.any(axis = 1) rows_with_NaN = MainDf[row_has_NaN] print(rows_with_NaN) ''' #Split data to training and testing data X_train, X_test, Y_train, Y_test = train_test_split(MainDf['text'], MainDf['Content_category'], test_size = 0.3, random_state = 10) #Vectorize training feature train_Vect = CountVectorizer() V_X_train = train_Vect.fit_transform(X_train) ''' The Vectorizer takes the dataset if text values (i.e. training X values) and turns it into a matrix of token counts of the whole vocabulary or a limited vocabulary that can be set ''' #Vectorize the testing feature test_Vect = CountVectorizer(vocabulary=train_Vect.vocabulary_) V_X_test = test_Vect.fit_transform(X_test) ''' The model will be MultinomialNB, which is a scikit model that predicts from values tf-idf vectors using a Naive-Bayes Classifier ''' model = MultinomialNB() model = model.fit(V_X_train, Y_train) #Predict the Y-Values from the model Y_Predicted = model.predict(V_X_test) #Output the classification report and confusion matrix print("Training Size: %d" % X_train.shape[0]) print("Test Size: %d" % X_test.shape[0]) print(metrics.classification_report(Y_test, Y_Predicted, zero_division = 0)) #Because of small sample size of questions, the precision and f-score could be dividing by 0 print("Confusion matrix: ") print(metrics.confusion_matrix(Y_test, Y_Predicted))
d2db0b2f4da1841ca46af2b99cc16b1da20668f8
MartinMa28/LeetCode-Solutions
/top_interview_questions/easy/merge_sort.py
668
4.125
4
def merge_sort(arr): mid = int(len(arr) / 2) if mid == 0: # the array only has zero or one element, so it's already sorted return arr else: return merge(merge_sort(arr[0:mid]), merge_sort(arr[mid:])) def merge(arr1, arr2): if len(arr1) == 0: return arr2 if len(arr2) == 0: return arr1 if arr1[0] < arr2[0]: return [arr1[0]] + merge(arr1[1:], arr2) else: return [arr2[0]] + merge(arr1, arr2[1:]) if __name__ == "__main__": n1 = [1, 3, 6, 7] n2 = [1, 2, 4, 4, 5, 9] print(merge(n1, n2)) test = [-9, -88, 33, 232, 887, 11, 23, 64, -99] print(merge_sort(test))
d492d61741cf0a9bcf0a7716e291ea40b028fc59
chrisglencross/advent-of-code
/aoc2015/day21/day21.py
2,504
3.578125
4
#!/usr/bin/python3 # Advent of code 2015 day 21 # See https://adventofcode.com/2015/day/21 from dataclasses import dataclass @dataclass class Character: name: str hp: int damage: int armor: int def attack(self, other): other.hp -= max(1, self.damage - other.armor) @dataclass class Item: name: str cost: int = 0 damage: int = 0 armor: int = 0 weapons = [ Item(name="Dagger", cost=8, damage=4), Item(name="Shortsword", cost=10, damage=5), Item(name="Warhammer", cost=25, damage=6), Item(name="Longsword", cost=40, damage=7), Item(name="Greataxe", cost=74, damage=7) ] armor_items = [ Item(name="No armor", cost=0, armor=0), Item(name="Leather", cost=14, armor=1), Item(name="Chainmail", cost=31, armor=2), Item(name="Splintmail", cost=53, armor=3), Item(name="Bandedmail", cost=75, armor=4), Item(name="Platemail", cost=102, armor=5), ] rings = [ Item(name="No Ring 1", cost=0), Item(name="No Ring 2", cost=0), Item(name="Damage +1", cost=25, damage=1), Item(name="Damage +2", cost=50, damage=2), Item(name="Damage +3", cost=100, damage=3), Item(name="Defense +1", cost=20, armor=1), Item(name="Defense +2", cost=40, armor=2), Item(name="Defense +3", cost=80, armor=3), ] def fight(player, boss): while True: player.attack(boss) if boss.hp <= 0: return True boss.attack(player) if player.hp <= 0: return False max_cost = -1 min_cost = 100000 for weapon in weapons: for armor in armor_items: for ring1 in rings: for ring2 in rings: if ring1 == ring2: continue items = [weapon, armor, ring1, ring2] cost = sum([item.cost for item in items]) if min_cost < cost < max_cost: # Not interesting - cannot affect min cost or max cost continue player_damage = sum([item.damage for item in items]) player_armor = sum([item.armor for item in items]) boss = Character(name="boss", hp=109, damage=8, armor=2) player = Character(name="player", hp=100, damage=player_damage, armor=player_armor) if fight(player, boss): min_cost = min(min_cost, cost) else: max_cost = max(max_cost, cost) print("Part 1:", min_cost) print("Part 2:", max_cost)
bc88f4700e7a12507e10ec1dee57514f431cc9c2
FelixTheC/hackerrank_exercises
/hackerrank/CamelCase.py
251
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @created: 03.05.20 @author: felix """ def camelcase(s: str): return 1 + sum([1 for char in s if char.isupper()]) if __name__ == '__main__': print(camelcase('saveChangesInTheEditor') == 5)
97239cac6cde82a245360593d8ce4784fcc07198
jhansi-yallay/DjangoApplication
/newone.py
1,013
3.796875
4
# class Parent: # def __init__(self,msg): # self.msg = msg # def sample(self): # return self.msg # class Child(Parent): # def child_sample(self): # return "sample child class" # print("Call parent class") # obj = Parent("calling parent method") # print(obj.sample()) # print("call child class method") # obj1=Child("Calling child method") # print(obj1.child_sample()) # print(obj1.sample()) class College: def __init__(self, name,age,gender,role): self.name = name self.age = age self.gender = gender self.role = role class Staff(College): def attendance_sheet(self, present,reason=None): if present == 'no': print('{} is Absent and the reason is {} '.format(self.name,reason)) else: print('this{}is present'.format(self.name)) obj = College('jhansi','24','Female','Student') # print(str(obj.name)) obj1 = Staff('jhansi','24','Female','Student') obj1.attendance_sheet('no', 'not feeling well')
e46f7e310772c381787df33db8ff564c8df86175
dyoung418/Google-Drive-Python-Utilities
/retry.py
5,785
3.796875
4
""" Download all files from a specified Google Drive (identified by its "folder" id) on my Google Account "[email protected]" to D:/Google Drive/Google Drive Download. From D:/Google Drive/Google Drive Download the folder is then synced (using Google Drive functionality) with my Google Drive on [email protected] This program should be run in a directory where the file client_secrets.json contains the credential for my Google Drive on [email protected] In order for the program to run, it may be required to first install pydrive, using the command "pip install PyDrive" in the Windows Terminal windows (i.e., from where this program is started). """ from pydrive.auth import GoogleAuth gauth = GoogleAuth() # gauth.LocalWebserverAuth() # Creates local webserver and auto handles authentication. from pydrive.drive import GoogleDrive drive = GoogleDrive(gauth) import shutil, os import datetime import time from retrying import retry def Start_download(folder_id): List_folder(folder_id) # print(filelist) for l in reversed(filelist): # print(l['title'].ljust(60), l['MimeType'].ljust(35), l['id'].ljust(20)) if l['MimeType']=='application/vnd.google-apps.folder': # if folder print("\n**** " +'{:%Y-%m-%d %H-%M-%S} .txt'.format(datetime.datetime.now()) + " starting download of folder " + str(l['title']) + "\n" ) log.write("\n**** " + '{:%Y-%m-%d %H-%M-%S} .txt'.format(datetime.datetime.now()) + " starting download of folder " + str(l['title']) + "\n") if not l['MimeType'][:15]=='application/vnd': failure = False try: download = drive.CreateFile({'id': l['id']}) download.GetContentFile(l['title'], l['MimeType']) # Download file except: print(l['title'].ljust(50) + " download failed (1. attempt) " + l['id'] + "\n") log.write('{:%Y-%m-%d %H-%M-%S} .txt'.format(datetime.datetime.now()) + " " + l['title'].ljust(50) + " download failed (1. attempt) " + l['id'] + "\n") time.sleep(2) try: download = drive.CreateFile({'id': l['id']}) download.GetContentFile(l['title'], l['MimeType']) # Download file except: print(l['title'].ljust(50) + " download failed (2. attempt) " + l['id'] + "\n") log.write('{:%Y-%m-%d %H-%M-%S} .txt'.format(datetime.datetime.now()) + " " + l['title'].ljust(50) + " download failed (2. attempt) " + l['id'] + "\n") failure = True if failure == False: try: Move_file(l['id'], l['title']) print(l['title'] + " downloaded and moved. Mime Type = ", l['MimeType']) except: try: print(l['title'] + " download and move failed (1. attempt). Mime Type = ", l['MimeType']) log.write('{:%Y-%m-%d %H-%M-%S} .txt'.format(datetime.datetime.now()) + " " + l['title'] + " move failed (1. attempt)\n") time.sleep(2) Move_file(l['id'], l['title']) print(l['title'] + " downloaded and moved (2. attempt). Mime Type = ", l['MimeType']) except: log.write('{:%Y-%m-%d %H-%M-%S} .txt'.format(datetime.datetime.now()) + " " + l['title'] + " move failed (2. attempt)\n") print(l['title'] + " download and moved failed (2. attempt). Mime Type = ", l['MimeType']) pass pass def List_folder(parent): # print({'q': "'%s' in parents and trashed=false" % parent}) file_list = drive.ListFile({'q': "'%s' in parents and trashed=false" % parent}).GetList() for f in file_list: if f['mimeType']=='application/vnd.google-apps.folder': # if folder filelist.append({"id":f['id'],"title":f['title'],"MimeType":f['mimeType'],"list":List_folder(f['id'])}) else: filelist.append({"id":f['id'],"title":f['title'],"MimeType":f['mimeType']}) return filelist def Make_directory_if_not_exists(path): if not os.path.isdir(path): os.makedirs(path) def Move_file(file_id, file_name): parents = [] isroot = False file_ID = file_id while isroot == False: file = drive.CreateFile({'id': file_id}) p1 = file['parents'] p2 = p1[0] p = p2['parentLink'] parent_id = p[p.rfind('/')+1:] file1 = drive.CreateFile({'id': parent_id}) parent = file1['title'] # print(file['title'].ljust(60), file['mimeType'].ljust(40), parent) file_id = parent_id parents.append(parent) isroot = p2['isRoot'] parents[-1:] = ["Google Drive Download"] path = "D:\\Google Drive\\" for s in parents[::-1]: path = path + (s + '\\') #path = '"' + path[:-1] + '"' path = path[:-1] # print(path) Make_directory_if_not_exists(path) try: shutil.copy(file_name, path) except IOError: print("Unable to copy file") print(file_name.ljust(40) + " " + path.ljust(80) + " " + file_ID) os.remove(file_name) pass # folder = "root" # folder = "0BxhD2G0gO43yVktTZVdvZHFMOUU" # folder = "0BxhD2G0gO43yT1c2Uk1XcHBhTGc" # Foto # folder = "0BxhD2G0gO43ybzBiN09GVTc0UXc" # Folder Fotos 2 folder = "0BxhD2G0gO43yVEwwN2pFU0tqNHM" # Fotos aus der Vergangenheit # folder = "0BxhD2G0gO43yaEV2a0dPalZSS00" # Download # folder = "0BxhD2G0gO43yQmtBRkE4clZkb0U" # Test Folder # folder = "0BxhD2G0gO43yQXpqemhDV1ZpeEk" # Versicherungen filelist=[] logfilename = 'Logfile {:%Y-%m-%d %H-%M-%S} .txt'.format(datetime.datetime.now()) log = open(logfilename, "w") Start_download(folder)
570ae17649ef9a83a3da67827dbf00cf8db2ec28
feizhihui/Coursera-Python-Repo
/lecture_1/find_monisen.py
353
3.75
4
# encoding=utf-8 from math import sqrt, log2 def isPrime(n): assert type(n) == int for i in range(2, int(sqrt(n)) + 1): if n % i == 0: return False return True for i in range(2, 1000000): if not isPrime(i): continue p = log2(i + 1) if not p == int(p): continue if isPrime(int(p)): print(i)
ffd0f13b91008acafd781ae22fbd082c85a31555
jenningchen/logsAnalysis
/newsdata.py
2,229
3.53125
4
#!/usr/bin/env python3 # Reporting tool that generates reports based on data provided import psycopg2 import datetime import calendar def main(): """Print most popular 3 articles of all time.""" get_articles() """Print most popular authors of all time.""" get_authors() """Days where more than 1% of requests led to errors.""" get_errors() def execute_query(query): """Executes query and returns tuple list""" try: db = psycopg2.connect(database="news") c = db.cursor() c.execute(query) results = c.fetchall() db.close() return results except (Exception, psycopg2.DatabaseError) as error: print(error) def get_articles(): """Print ranking of most popular 3 articles of all time""" print("Ranking of most popular 3 articles of all time:") query1 = """select title, count(*) as views from articles_simplified group by title order by views desc limit 3;""" rows = execute_query(query1) """Print result""" for title, views in rows: print('\"{}\" — {} views'.format(title, views)) print ("\n") def get_authors(): """"Print ranking of most popular authors of all time""" print("Ranking of most popular authors of all time:") query2 = """select name, count(*) as views from articles_simplified group by name order by views desc;""" rows = execute_query(query2) '''Print result''' for name, views in rows: print('\"{}\" — {} views'.format(name, views)) print("\n") def get_errors(): """"Print days where more than 1% of requests led to errors""" print("Day(s) where more than 1% of requests led to errors:") query3 = """select day1, num_errors, num_accessed from day_error join day_requests on day1=day2 where ((num_errors::float/num_accessed) > 0.01);""" rows = execute_query(query3) """Print result""" for day1, errors, accessed in rows: index = day1.month print('{} {}, {} — {:.2f}% errors'.format(calendar.month_name[index], day1.day, day1.year, (100*errors/accessed))) print("\n") if __name__ == '__main__': main()
b569dff50bad1110df44e318464f013a9e86f458
anne75/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/2-uniq_add.py
182
4.03125
4
#!/usr/bin/python3 def uniq_add(my_list=[]): """ add all the unique elements in a list my_list: a list of ints Return: sum """ return (sum(set(my_list)))
d5a8797a1f66768c5b13e8dd4d8628e469d23797
juanvergaramunoz/SE-Main_Functions
/HashTable_Class.py
3,765
4.09375
4
# coding: utf-8 # In[1]: ######################################### ####### General HASH TABLE CLASS ######## ######################################### # Includes a contact class: X.name, X.number, X.address --> The number is the one that provides the main identifier ####### FUNCTIONS FOR THIS CLASS ####### # # - __init__: Generates the hash string with the desired length || An specific hash function can be included as well # # - hashFunc: Generates the hash number (adjusted to the string length) based on the identifier given by the function selected above # # - insertElem: Allows to insert the element desired (identifier string must be given as well) # # - getElem: Given the string identifier returns all the contact data for the correspondent element # # - deleteElem: Deletes the element with the ID provided # #WE USE THE LINKED LIST CLASS TO MANAGE COLLISIONS from LinkedList_Class import linkedList ##---------------------------------## ## Aux HASH NUM Generator Function ## ##---------------------------------## # # We define a default basic function for generating a hash identifier # # INPUT: Number given as a STRING # OUTPUT: HASH NUM (all digits added together) def phoneFunction(number): identifier = 0 for digit in number: identifier += int(digit) return identifier ####################################### ######## Main HASHTABLE CLASS ######### ####################################### class hashTable: #INPUT: 1) Number of elements for the Hash Array (which will define the max value of the HASH Num) # 2) Desired Hash Function to generate the Hash Num from the Unique Identifier (such as a telephone number) # - If not given, a default function adds the digits from the Unique Identifiers (that must be passed as a STRING) def __init__(self, num_options, function = phoneFunction): self.opt = num_options self.array = [None]*self.opt self.func = function #INPUT: Numerical Identifier ('Unique' number) #OUTPUT: Hash number (for the sel.array) def hashFunc(self, value): val = self.func(value) hash_num = val%self.opt return hash_num #INPUTS: 1) Element (a class) # 2) Unique numerical identifier #OUTPUT: Bool --> TRUE __ if insertion correct | FALSE __ if there is a problem during insertion def insertElem(self, element, id_val): hash_num = self.hashFunc(id_val) if self.array[hash_num] == None: self.array[hash_num] = linkedList(id_val,element) return True else: aux_linkedlist = self.array[hash_num] aux_linkedlist.insertNewElem(id_val,element) return True #INPUT: Unique numerical identifier (from element desired) #OUTPUT: Element desired def getElem(self, id_val): hash_num = self.hashFunc(id_val) if self.array[hash_num] == None: return False else: aux_linkedlist = self.array[hash_num] aux_data = aux_linkedlist.retrieveElem(id_val) return aux_data #INPUT: Unique numerical identifier (from element desired) #OUTPUT: Bool --> TRUE __ if deletion correct | FALSE __ if there is a problem during deletion def deleteElem(self, id_val): hash_num = self.hashFunc(id_val) if self.array[hash_num] == None: return False else: aux_linkedlist = self.array[hash_num] new_list = aux_linkedlist.deleteElem(id_val) if new_list != False: self.array[hash_num] = new_list return True else: return False
8e906cbfe667eb73cbd2d362fb20c1b85987748a
adrielj/CS104-01
/richter2.0.py
789
4.28125
4
testing = True while testing is True: richter = float(input("What was the recorded Richter scale magnitude? Type -99 to end")) if 8 <= richter <= 10: print ("Most of the structures have fallen.") continue elif 7 <= richter < 8: print ("Many buildings have been destroyed") continue elif 6 <= richter < 7: print ("Many of the buildings have been considerably damages, some will collapse.") continue elif 4.5 <= richter < 6: print ("There is damage on poorly constructed buildings.") continue elif richter == -99: print ("Goodbye.") testing is False break else: print ("The number must be between 0 and 10. Try again.") continue
79f423d207758bda3df1dddc9521c446f602a60c
babs20795/DataSciene_ML
/Python/Odd_Even.py
182
4.125
4
# -*- coding: utf-8 -*- """ Created on Sun Apr 5 10:20:31 2020 @author: Babs """ num=input("Enter a number:") a=int(num) if a%2 ==0: print("Even") else: print("Odd")
fee9b6d61b1913db920f2a98feee43ad50aa5e30
zhangzi2/Quick-Python-Projects
/polynomial_roots.py
2,213
4
4
import math #1 A = float(1) B = float(0) C = float(-4) print( "\nThe coefficients of the equation:\n" ) print( " Coefficient A = ", A ) print( " Coefficient B = ", B ) print( " Coefficient C = ", C ) root1 = (-B + math.sqrt(B**2 - 4*A*C)) / (2 * A) # replace 0.0 with the quadratic formula root2 = (-B - math.sqrt(B**2 - 4*A*C)) / (2 * A) print( "\nThe roots of the equation:\n" ) print( " Root #1 = ", root1 ) print( " Root #2 = ", root2 ) #2 A = float(1) B = float(5) C = float(-36) print( "\nThe coefficients of the equation:\n" ) print( " Coefficient A = ", A ) print( " Coefficient B = ", B ) print( " Coefficient C = ", C ) root1 = (-B + math.sqrt(B**2 - 4*A*C)) / (2 * A) # replace 0.0 with the quadratic formula root2 = (-B - math.sqrt(B**2 - 4*A*C)) / (2 * A) print( "\nThe roots of the equation:\n" ) print( " Root #1 = ", root1 ) print( " Root #2 = ", root2 ) #3 A = float(-2) B = float(7.5) C = float(6) print( "\nThe coefficients of the equation:\n" ) print( " Coefficient A = ", A ) print( " Coefficient B = ", B ) print( " Coefficient C = ", C ) root1 = (-B + math.sqrt(B**2 - 4*A*C)) / (2 * A) # replace 0.0 with the quadratic formula root2 = (-B - math.sqrt(B**2 - 4*A*C)) / (2 * A) print( "\nThe roots of the equation:\n" ) print( " Root #1 = ", root1 ) print( " Root #2 = ", root2 ) #4 A = float(1) B = float(3.5) C = float(8) print( "\nThe coefficients of the equation:\n" ) print( " Coefficient A = ", A ) print( " Coefficient B = ", B ) print( " Coefficient C = ", C ) root1 = (-B + math.sqrt(B**2 - 4*A*C)) / (2 * A) # replace 0.0 with the quadratic formula root2 = (-B - math.sqrt(B**2 - 4*A*C)) / (2 * A) print( "\nThe roots of the equation:\n" ) print( " Root #1 = ", root1 ) print( " Root #2 = ", root2 ) #5 A = float(5) B = float(0) C = float(-6.5) print( "\nThe coefficients of the equation:\n" ) print( " Coefficient A = ", A ) print( " Coefficient B = ", B ) print( " Coefficient C = ", C ) root1 = (-B + math.sqrt(B**2 - 4*A*C)) / (2 * A) # replace 0.0 with the quadratic formula root2 = (-B - math.sqrt(B**2 - 4*A*C)) / (2 * A) print( "\nThe roots of the equation:\n" ) print( " Root #1 = ", root1 ) print( " Root #2 = ", root2 )
22e2462fe5d7d3ab5114b85eb54dea6bed9b40ee
vishalkumar9dec/demopython
/ExampleFunctionParameters.py
926
4
4
'''def addition(num1, num2): answer = num1 + num2 return answer x = addition(5,6) print(x) #No limit on the number of parameters being passed def website(font,background_color,font_size,font_color): print('font: ',font) print('BG:',background_color) print('Font_Size:',font_size) print('Font Color:',font_color) website('TNR','white','11','Black') #Giving wrong order of paramters #website('TNR','white','Black','11') # another way of doing''' #default parameters def website(font='TNR', font_size='11', font_color='White', background_color='Black'): print('font: ',font) print('BG:',background_color) print('Font_Size:',font_size) print('Font Color:',font_color) #website() #calling function without giving paramters #website(background_color='Grey') website('TNR','Grey') # if only passing some parameters give the parameters in the correct order
0bf4b2a8074c8c3333a6a0905b9efd1fc5f6651a
mvphjx/Test_framework
/learn_and_try/python_book_automate/04-list/commaList.py
283
3.703125
4
def commaList(items): ret = '' for item in items[:-1]: ret += item + ', ' return ret + 'and ' + items[-1] spam = ['apples', 'bananas', 'tofu', 'cats'] spam.sort(reverse=True) print(spam) print(commaList(spam)) a=["b","a","c"] b = sorted(a,reverse=True) print(b)
ab47be46c47d0709982d617269085880f23cd32d
Harrison-Hughes/project_euler
/problem51.py
4,968
3.875
4
# By replacing the 1st digit of the 2-digit number *3, it turns out that six of the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime. # By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit number is the first example having seven primes among the ten generated numbers, yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993. Consequently 56003, being the first member of this family, is the smallest prime with this property. # Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an eight prime value family. # HARD CODED AND TOO SLOW import time def n_member_prime_family(n): [numbers, num_length] = [[2], 2] cont = True while cont: def range_starter(): if num_length == 2: return 1 else: return 2 for i in range(numbers[-1]+range_starter(), 10**num_length, 2): numbers.append(i) counter = 1 while counter < len(numbers): numbers = [x for x in numbers if x <= numbers[counter] or x % numbers[counter] != 0] counter += 1 prime_value_fam = contains_prime_value_family(numbers, num_length, n) # print('prime_value_fam', prime_value_fam) if len(prime_value_fam) > 0: cont = False num_length += 1 sol = 0 for i in range(len(prime_value_fam[0])): sol += prime_value_fam[0][i] * 10 ** (len(prime_value_fam[0])-i - 1) return sol def contains_prime_value_family(full_arr, digits, family_size): correct_length_primes = [x for x in full_arr if len(str(x)) == digits] split_primes = [] for i in correct_length_primes: [prime, prime_arr] = [i, []] while prime > 0: prime_arr.insert(0, prime % 10) prime = int(prime/10) split_primes.append(prime_arr) for digit in range(11 - family_size): unfiltered_primes = split_primes for prime in split_primes: # if digit in prime: if how_many_item_in_list(prime[0:-1], digit) == 3: indices_of_not_digit = get_anti_indices(prime, digit) filtered_primes = [ x for x in unfiltered_primes if not_star_match(prime, x, indices_of_not_digit) and star_space_is_repeated_digit(x, indices_of_not_digit)] # print('filtered_primes', filtered_primes) if len(filtered_primes) == family_size: return filtered_primes return [] def how_many_item_in_list(list, item): count = 0 for i in range(len(list)): if list[i] == item: count += 1 return count def not_star_match(base_num, compare_num, anti_indices): [base, comparison] = [[], []] for i in anti_indices: base.append(base_num[i]) comparison.append(compare_num[i]) if base == comparison: return True else: return False def star_space_is_repeated_digit(compare_num, anti_indices): star_digit = [] for i in range(len(compare_num)): if i not in anti_indices: if star_digit == []: star_digit = compare_num[i] else: if not star_digit == compare_num[i]: return False return True def get_anti_indices(list_, val): ret = [] for i in range(len(list_)): if not list_[i] == val: ret.append(i) return ret if __name__ == "__main__": start_time = time.time() print(n_member_prime_family(8)) print("--- took %s seconds ---" % (time.time() - start_time)) # def contains_prime_value_family(full_arr, digits, family_size): # correct_length_primes = [x for x in full_arr if len(str(x)) == digits] # split_primes = [] # for i in correct_length_primes: # [prime, prime_arr] = [i, []] # while prime > 0: # prime_arr.insert(0, prime % 10) # prime = int(prime/10) # split_primes.append(prime_arr) # for x in range(1, 10): # for i in range(1, digits): # potential_primes = [ # n for n in split_primes if n.count(x) == i] # filtered_primes = filter_potential_primes( # potential_primes, family_size, x) # if filtered_primes != []: # return filtered_primes # return 0 # def filter_potential_primes(prime_array, family_size, digit): # [primes, filtered_primes] = [prime_array, []] # while len(primes) > 0: # indices = get_indices(primes[0], digit) # filtered_primes = [ # x for x in prime_array if get_indices(x, digit) == indices] # if len(filtered_primes) >= family_size: # return filtered_primes # else: # primes = [x for x in primes if not x in filtered_primes] # return []
d1541ed52487a0c2a0504cd25fabc37cb2c95990
vmarcella/d2dl
/maths/auto_grad.py
3,941
3.890625
4
from mxnet import autograd, np, npx npx.set_np() # Create the initial ndarrary x = np.arange(4) # Allocate memory for the gradient buffer that is of the same shape # as the input vector. x.attach_grad() # Display the gradient buffer, which is initialized at 0. It is initialized # at 0 for the event that the gradient is accidentally applied to the # differentiated function before the gradients are computed. print(x.grad) # Build the graph and record computations across it with autograd.record(): y = 2 * np.dot(x, x) # Print the reuslt of y print(y) # Compute the gradient of y with respect to each component of x y.backward() # Teh gradient of y = 2 * dot(x, x) is 4x, which means that # the gradients of x should be 0, 4, 8, and 12 respectively print(x.grad) def detach_computation(): """ Lets say we have a function y that relies on a function x. We could write that as: y = x * x now lets also say that we have a function z, that depends on both y and x. If we wanted to compute the gradient of z with respect to x and treat y as a constant, how could we possibly do it? The answer, we can compute y and then detach it from the graph, allowing it to be used as a constant in another computation """ x = np.arange(4) x.attach_grad() with autograd.record(): # The computation for y is computed, with the derivative of y # being 2x. y = x * x # Here we convert y to a constant by creating a variable u that # is detached from the graph, allowing us to record future computations # that store the result of y but not how the results came about. u = y.detach() # Now we can compute the gradient of z with respect to x while treating # u as a constant. (The derivative becomes u*x instead of 3x^2, which # would've been computed had we used y instead of u). z = u * x print("z") # We are now obtaining the gradients of function z with respect to x. Because # we used the detached variable u, the gradient becomes the result of u * x. z.backward() print(x.grad) print("The gradients for the partial derivate of z with respect to x", x.grad) print(x.grad == u) # Because the operations for y were recorded when computing underneath # the autograd, we're able to compute the gradient for y with respect # to x. y.backward() print("The derivative of y is 2x, resulting in gradients: ", x.grad) print(x.grad == 2 * x) def compute_gradient_with_control_flow(): """ How can we handle computing the gradient of a functino that introduces control flow to our program? """ def f(a): """ A piecewise mathematical function that is used for computing some arbritrary values. """ b = 2 * a # Multiply each element by 2 until # the l2 norm of b is greater than 1000 while np.linalg.norm(b) < 1000: b = 2 * b # If the sum of b is greater than 0, c = b, else # c = 100 * b. if b.sum() > 0: c = b else: c = 100 * b return c # Create a random normal distribution and initialize it's gradient array. a = np.random.normal() a.attach_grad() # Record all gradients when computing the result of f(a) with autograd.record(): d = f(a) # Backward propagte d in order to obtain the gradients for variables a. d.backward() # In f(a), we're simply multiplying a by some scalar number that is # determined by the initial random normal distribution. We can # mathematically formula f(a) = k * a, where k is the scalar multiplied # by a. To verify our gradient, we can simply check if f(a) / k = a. print("f(a) / k = a: ", a.grad == d / a) if __name__ == "__main__": detach_computation() compute_gradient_with_control_flow()
16ae54462e50f09fbb1bc3794c52e83a50003646
5thCorner/Coffee_Machine
/Problems/I have friends/main.py
481
3.640625
4
class Song: def __init__(self, artist, name, year): self.artist = artist self.name = name self.year = year def __repr__(self): rep = "Artist: {}. Name: {}. Year: {}".format(self.artist, self.name, self.year) return rep def __str__(self): return "{} — {} ({})".format(self.artist, self.name, self.year) dsmn = Song("Queen", "Don't stop me now", 1979) print(dsmn)
084179ea4f9b155da661f1f2b7c5f74f3bde4f26
mi-ran/Algorithm
/CodeForce/Kefa_and_Park.py
869
3.515625
4
def visite(dic, vs, current, cnt, con): if vs[current] is 1: cnt = cnt - 1 else: cnt = con res = 0 if current in arr: for p in arr[current]: res = res + visite(dic, vs, p, cnt, con) else: if cnt >= 0: return res + 1 return res if __name__ == '__main__': number_of_v, con = list(map(int, input().split())) vs = list(map(int, input().split())) arr = {} leaf = [True for i in range(0, number_of_v)] for i in range(0, number_of_v - 1): f, t = list(map(int, input().split())) if t - 1 in arr: arr[t-1].append(f-1) else: arr[t-1] = [f -1] leaf[f-1] = False res = 0 for i in range(0, number_of_v): if leaf[i] == True: res = res + visite(arr, vs, i, con, con) print(res)
7c599d75d459a069dae8e8261b74ebeb2d623526
Elwing-Chou/mtkpython
/1_oo_1020.py
1,005
4.09375
4
# https://docs.python.org/3/reference/datamodel.html#object.__init__ class Person: def __init__(self, name, height, weight): self.name = name self.height = height self.weight = weight def bmi(self): return self.weight / (self.height / 100) ** 2 def __str__(self): return "{}:{:.2f}".format(self.name, self.bmi()) def __repr__(self): return "{}...".format(self) def __eq__(self, other): return self.height == other.height class SuperPerson(Person): def __init__(self, name, height, weight, city): Person.__init__(self, name, height, weight) self.city = city def __str__(self): return "{}[{}]".format(Person.__str__(self), self.city) p1 = SuperPerson("Elwing", 175, 75, "Taipei") print(p1.bmi(), Person.bmi(p1)) # print -> str(p1) -> p1.__str__() print(p1) p2 = Person("Bob", 175, 80) # p1.__repr__() print([p1, p2]) # p1 == p2 -> p1.__eq__(p2) print(p1 == p2)
b162adbf6fdd54a90122c9ee2c56f133430693b2
calwoo/graph-notes
/word-ladder.py
801
3.578125
4
import sys sys.path.insert(0, "./implementations/") from adjacency_list import Graph def construct_graph(words): d = {} g = Graph() # form buckets of words that differ by one letter for word in words: for i in range(len(word)): bucket = word[:i] + "_" + word[i+1:] if bucket in d: d[bucket].append(word) else: d[bucket] = [word] # after creating buckets, store into a graph for bucket in d.keys(): for word1 in d[bucket]: for word2 in d[bucket]: if word1 != word2: g.add_edge(word1, word2) return g # to find the shortest path in this graph from one word to another, we use BFS from collections import queue
0b4304baf1755d976ea42a630b01730422a69022
sconetto/ppc
/listas/contest_2/a_cash.py
251
3.640625
4
n = int(input()) times = [] for i in range(n): h, m = input().split(' ') times.append(h + ':' + m) biggest = 0 repeated = list(set(times)) for i in repeated: if (times.count(i) > biggest): biggest = times.count(i) print(biggest)
da18b7ed765563efd8c417760c83ef1d82322d6b
balajisomasale/Chatbot-using-Python
/02 Advanced Python Functions/bond_jamesbond.py
619
4.0625
4
'''Write a function named introduction() that has two parameters named first_name and last_name. The function should return the last_name, followed by a comma, a space, first_name another space, and finally last_name.''' # Write your introduction function here: # Uncomment these function calls to test your introduction function: def introduction(first_name,last_name): #list=[last_name,',',' ',first_name+' ',last_name] return f"{last_name}, {first_name} {last_name}" print(introduction("James", "Bond")) # should print Bond, James Bond print(introduction("Maya", "Angelou")) # should print Angelou, Maya Angelou
a68e1e1d96f90338d0f139a696ab2fea333bec03
avivrm/beginpython
/Include/assignment2/assign3.py
209
3.84375
4
# Use map and a lambda function to find the maximum x coordinate (the 0-th coordinate) in a list of points. # You will need to apply max to the result of the map arr = [45, 23, 87, 11, 23, 89] print(max(arr))
91b86aa5e9c9d5f6caf26264b886c1fc3adf37f9
Andreivilla/PythonCV
/078.py
293
3.90625
4
vet = [] for i in range(0, 5, +1): vet.append(float(input('N[{}]: '.format(i+1)))) maior = menor = vet[0] for i in range(0, 5, +1): if menor < vet[i]: menor = vet[i] if maior > vet[i]: maior = vet[i] print('Maior: {}'.format(maior)) print('Menor: {}'.format(menor))
14b1608f8e169a486eb481e7e42e943ba02d1549
hado66/python_project
/s14/day02/shopping_demo.py
928
3.984375
4
salary=int(input("please input you salary:")) list=[ ["IPhone",5800], ["Mac pro",12000], ["Starbuck",31], ["Alex python",81], ["Bile",88], ["a",200], ["b",300], ["c",400] ] account=salary current_list=[] while account>0: for index,i in enumerate(list) : # print(list.index(i)+1,i) print(index+1,i) print("Your current account :",str(account)) elect=input("please you elect want buy:") if elect>='1' and elect<=str(len(list)): elect=int(elect) per_price=list[elect-1][1] if account-per_price>0: current_list.extend(list[elect-1]) print("------------------------------------------") print("you had possession :"+str(current_list)) account=account-per_price elif elect=="q": print("you had possession :" + str(current_list)) break else: print("您的输入有误")
11d29b02d3133aa828248e66f6b7cc9e36ddf91c
will8211/my_euler_solutions
/euler_19.py
1,058
3.921875
4
#!/usr/bin/env python3 ''' You are given the following information, but you may prefer to do some research for yourself. • 1 Jan 1900 was a Monday. • Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. • A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? ''' lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] day_counter = 2 # Jan. 1, 1901 --> Tuesday hit_counter = 0 year = 1901 while year <= 2000: if year % 4 == 0: lengths[1] = 29 # For other centuries: #if (year % 100 == 0) and (year % 400 != 0): #lengths[1] = 28 else: lengths[1] = 28 for i in lengths: if day_counter % 7 == 0: hit_counter += 1 day_counter += i year += 1 print(hit_counter)
b817f76165f147b4d92b0852477fa17f51c2cdb2
pepitogrilho/learning_python
/xUdemy_tkinter/Sect2_Python_Refresher/12_if_01.py
268
4.09375
4
# -*- coding: utf-8 -*- """ """ day_of_week = input("What day of the week is it today?").lower() if day_of_week == "monday": print("Have a great start to your week!") elif day_of_week == "tuesday": print("Tuesday!") else: print("Full speed ahead!")
cb9653b6482fba64133ccbbb4cad3f051b391bf2
Sidhus234/Python-Dev-Course
/Codes/Session 3/Session 3 - Python Basics - Escape Sequences.py
213
3.625
4
# Escape Sequence weather = 'It's sunny' weather = 'It\'s sunny' weather = "It\'s \"kind of\" sunny" weather # \n new line # \t tab print("\t It\'s \"kind of\" sunnt\n hope you have a good day !")
047c1c5c0040b7b7b7c2c330622e0752a5381316
hobg0blin/ganterbury-tales
/scripts/clean.py
1,571
3.59375
4
import argparse import re parser = argparse.ArgumentParser() parser.add_argument('filename') args = parser.parse_args() with open(args.filename, "r") as file: # this script contains a bunch of individual regexes for common footnote/non-corpus patterns and deletes lines that contain them clean_name = ("_clean.").join(args.filename.split(".")) print("clean name: ", clean_name) output = open(clean_name, "w") # starting with number followed by period or colon or comma startsWithNumber = re.compile('\d+[\.|\:|\,]') onlyNumbers = re.compile('^[0-9 ()]+$') startsWithBracket = re.compile('^\[') startsWithLetterAndPeriod = re.compile('^\w+\.') # alphanumeric regex = re.compile('(^[^\s\w]|_)+') # this worked! but realized a ton of the lil poems and stuff start nonAlphanumeric #startsNonAlphaNumeric = re.compile('^[^\s\w\'\"]') f = file.read() newF = '' for line in f.splitlines(): print('line') if not startsWithNumber.match(line) and not startsWithBracket.match(line) and not startsWithLetterAndPeriod.match(line) and not onlyNumbers.match(line): output.write(line + '\n') else: # print('match starts with number: ', startsWithNumber.match(line)) # print('match starts with bracket: ', # startsWithBracket.match(line)) print('match starts with letter and period: ', startsWithLetterAndPeriod.match(line)) print(line) output.close() file.close()
ace8832ee9a0bcdb52f5718238c55ba2bc9399ee
BaseCampCoding/python-fundamentals
/7-methods/pytest-exercises/methods.py
3,127
3.765625
4
def greeting(name): ''' str -> str Returns a greeting telling the provided name hello. ''' raise NotImplementedError("Delete this line and put your code here") def city_banner(city_name, banner_width): ''' (str, int) -> str Returns a welcome banner for the provided city. The message should be centered in banner_width characters. ''' raise NotImplementedError("Delete this line and put your code here") def how_long_is_my_name(name): ''' str -> str Returns a message telling the user how long their name is. ''' raise NotImplementedError("Delete this line and put your code here") def student_email(first_name, last_name): ''' (str, str) -> str Returns the email for a base camp student with the provided first and last name. ''' raise NotImplementedError("Delete this line and put your code here") def old_enough_to_vote(age): ''' number -> bool Returns True if the user old enough to vote (is at least 18 years old) ''' raise NotImplementedError("Delete this line and put your code here") def has_two_os(string): '''str -> bool Returns True if string at least two o's (upper or lower case) ''' raise NotImplementedError("Delete this line and put your code here") def has_more_e_than_a(string): '''str -> bool Returns True if string has more e's than a's (upper or lower case) ''' raise NotImplementedError("Delete this line and put your code here") def walk_or_drive(miles, is_nice_weather): '''(int, bool) -> str Returns 'walk' if the user should walk and 'drive' if the user should drive to their destination. The user should walk if it is nice weather and the distance is less than a quarter mile. ''' raise NotImplementedError("Delete this line and put your code here") def gold_stars(points): '''int -> str Return the appropriate number of stars for the users score. 1 stars for scores less than 1000 points 2 stars for scores less than 5000 points 3 stars for scores less than 8000 points 4 stars for scores less than 10000 points 5 stars for anything 10000+ ''' raise NotImplementedError("Delete this line and put your code here") def damage_dealt(attack_strength, defense_strength, is_blocking): '''(int, int, bool) -> number Returns the damage dealt to the defender. Normally, the damage dealt is the difference between the attack_strength and the defense strength (without healing the defender). If the defender is blocking, the final damage dealt is reduced by 75%. ''' raise NotImplementedError("Delete this line and put your code here") def how_many_points(scoring_action): '''(str) -> int Returns the number of points for the corresponding scoring action in American football. An extra point kick is worth 1 point. An extra point conversion is worth 2 points. A safety is worth 2 points. A field goal is worth 3 points. A touchdown is worth 6 points. ''' raise NotImplementedError("Delete this line and put your code here")
c3ff78e520dca62b48e19d48cd50b09d2e178dac
blaoke/leetcode_answer
/序号题/445.py
1,485
3.625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: stack1 = [] stack2 = [] while l1 or l2: if l1: stack1.append(l1.val) l1 = l1.next if l2: stack2.append(l2.val) l2 = l2.next ans=None res=0 while stack1 or stack2 or res!=0: #如果两个栈有一个非空,res用于记录大于十的进位 a=0 if not stack1 else stack1.pop() b=0 if not stack2 else stack2.pop() cur=a+b+res res=0 if cur>9: res=cur//10 cur=cur%10 ret=ListNode(cur) #这里使用的头插法也是一个重点 ret.next=ans ans=ret return ans #下面 直接求和的方法 就失去了本题考查的意义 sums = sum(stack2 + stack1) while sums!=0: #7807通过求余输出的顺序为 从个位向上 7 0 8 7 a=sums%10 sums//=10 ret.append(a) ret.reverse() res=ListNode() back=res for i in ret: res.next=ListNode(i) res=res.next if not back.next: return back return back.next
c72cbaa302b31a34461aa631a30114e7bb77516f
wsgan001/InterestingnessSurvey
/FirstAssociationRules/PatternLabelling.py
1,703
3.65625
4
import sys def readAnnotationFile(file_name): association_rules = {} with open(file_name, "r") as text_file: for line in text_file: subStrings = line.split(":") rule_key = subStrings[0].strip() label = subStrings[1].strip() association_rules[rule_key] = label return association_rules def writeAnnotation(file_name, association_rules): with open(file_name, "w") as text_file: for rule_key, value in association_rules.items(): text_file.write(rule_key) text_file.write(':') text_file.write(value) text_file.write('\n') def main(argv): if len(argv) < 2: print ('Argument is not correct!') else: file_name = argv[1] association_rules = readAnnotationFile(file_name) rule_keys = association_rules.keys() n = len(rule_keys) m = sum(x == 'u' for x in association_rules.values()) print ('There are ' + str(m) + '/' + str(n) + ' patterns need to be labelled. Press s if you want to stop!') for rule_key in rule_keys: answer = association_rules[rule_key] if(answer != 'u'): continue print(rule_key) while (True): answer = input('Pattern is interesting? (y/n)') if (answer == 'y' or answer == 'n' or answer == 's'): break; if answer == 's': break association_rules[rule_key] = answer writeAnnotation(file_name, association_rules) print('New labels are recoreded!!!') if __name__ == '__main__': main(sys.argv)
f3b54a61fbb1d6d3862548044e8b3915a7bd5e62
zlbruce/nrciz
/projecteuler/032/032-nacre.py
443
3.5
4
#!/usr/bin/env python from itertools import permutations def is_pandigital_product(s): if int(s[:2]) * int(s[2:5]) == int(s[5:]): return 1 if int(s[0]) * int(s[1:5]) == int(s[5:]): return 1 return 0 lp = [] for s in permutations('123456789'): s = reduce(lambda x, y: x + y, s) if is_pandigital_product(s): product = int(s[5:]) if not(product in lp): lp.append(product) print sum(lp)
90f03a75aa39442183faa8b75f9b8d35815ef6c1
AdamZhouSE/pythonHomework
/Code/CodeRecords/2909/60889/280000.py
521
3.671875
4
def letterType(letters,limit): letters = set(letters) if len(letters)<=limit: return True else: return False String = input() limitType = int(input()) minSize = int(input()) maxSize = int(input()) count = {} maxCount = 0 for i in range(len(String)-minSize+1): str1 = String[i:i+minSize] if letterType(str1,limitType): nowCount = count.get(str1,0) count[str1] = nowCount + 1 if count[str1] > maxCount: maxCount = count[str1] print(maxCount)
508142279900214b6994e85c367d9392dc43d813
TripleFlex/DojoAssignments
/Python/structure/fundamentals/cointoss.py
612
3.734375
4
from random import randint print "Starting the program..." def coinToss(): heads = 0 tails = 0 for count in range(1,5001): flip = randint(0,1) if flip == 0: heads+=1 print "Attempt #" + str(count) + " Throwing a coin... its a Head! ... Got" + str(heads) + " head(s) so far and" + str(tails) + " tail(s) so far" else: tails+=1 print "Attempt #" + str(count) + " Throwing a coin... its a Tail!... Got" + str(heads) + " head(s) so far and" + str(tails) + " tail(s) so far" print "Ending the program, thank you" coinToss()
866350497e289578c1e501e8c178498652dde4eb
migueltorrescosta/DSA-Together-HacktoberFest
/algorithms/greedy/JumpGame.py
625
3.578125
4
#Link https://leetcode.com/problems/jump-game/ """ Greedy Algorithm You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, or false otherwise. """ class Solution: def canJump(self, nums: List[int]) -> bool: leftind = n = len(nums) - 1 for i in range(n,-1,-1): if (i + nums[i]) >= leftind: leftind = i return leftind == 0 obj = Solution() nums = list(map(int,input().split())) print(obj.canJump(nums))
03f9aca2d2708ac738ee12b7bf7c9359b749617e
wanguiwaweru/micropilot-entry-challenge
/wanguiwaweru/count_zeros.py
390
3.953125
4
# Write a function CountZeros(A) that takes in an array of integers A, and returns the number of 0's in that array. # For example, given [1, 0, 5, 6, 0, 2], the function/method should return 2. # Naive solution """ def CountZeros(A): count = 0 for i in A: if i == 0: count += 1 return count """ # pythonic solution def CountZeros(A): return A.count(0)
d861c05b2651ff5bd978596ddcd886e27f3541a7
zcgu/leetcode
/codes/308. Range Sum Query 2D - Mutable.py
2,924
3.9375
4
# Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). # Range Sum Query 2D # The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8. # Example: # Given matrix = [ # [3, 0, 1, 4, 2], # [5, 6, 3, 2, 1], # [1, 2, 0, 1, 5], # [4, 1, 0, 1, 7], # [1, 0, 3, 0, 5] # ] # sumRegion(2, 1, 4, 3) -> 8 # update(3, 2, 2) # sumRegion(2, 1, 4, 3) -> 10 # Note: # The matrix is only modifiable by the update function. # You may assume the number of calls to update and sumRegion function is distributed evenly. # You may assume that row1 ≤ row2 and col1 ≤ col2. # Show Company Tags # Show Tags # Show Similar Problems class NumMatrix(object): def __init__(self, matrix): """ initialize your data structure here. :type matrix: List[List[int]] """ if not matrix: self.matrix = None return m = len(matrix) n = len(matrix[0]) self.matrix = [[0 for _ in range(n)] for _ in range(m)] self.tree = [[0 for _ in range(n + 1)] for _ in range(m + 1)] for x in range(m): for y in range(n): self.update(x, y, matrix[x][y]) def update(self, row, col, val): """ update the element at matrix[row,col] to val. :type row: int :type col: int :type val: int :rtype: void """ if not self.matrix: return m = len(self.matrix) n = len(self.matrix[0]) i = row + 1 while i < m + 1: j = col + 1 while j < n + 1: self.tree[i][j] += val - self.matrix[row][col] j += j & -j i += i & -i self.matrix[row][col] = val def sumRegion(self, row1, col1, row2, col2): """ sum of elements matrix[(row1,col1)..(row2,col2)], inclusive. :type row1: int :type col1: int :type row2: int :type col2: int :rtype: int """ if not self.matrix: return 0 return self.sumCorner(row2, col2)\ - self.sumCorner(row1 - 1, col2)\ - self.sumCorner(row2, col1 - 1)\ + self.sumCorner(row1 - 1, col1 - 1) def sumCorner(self, row, col): res = 0 i = row + 1 while i > 0: j = col + 1 while j > 0: res += self.tree[i][j] j -= j & -j i -= i & -i return res # Your NumMatrix object will be instantiated and called as such: # numMatrix = NumMatrix(matrix) # numMatrix.sumRegion(0, 1, 2, 3) # numMatrix.update(1, 1, 10) # numMatrix.sumRegion(1, 2, 3, 4)
b635c4bbce464bedc7a752c832b8d7e5fc7b75b6
tanuj208/CipherForces
/flask_app/2/helper.py
1,057
4.21875
4
#TODO: Better conversion methods def convert_to_num(text): """Converts a text message to a list of numbers (their ascii codes).""" nums = [] for character in text: nums.append(ord(character)) return nums def convert_to_text(nums): """Converts a list of numbers to characters using numbers as their ascii code.""" text = [] for num in nums: text.append(chr(num)) return ''.join(text) def convert_text_to_binary(plaintext): """Converts each character of plaintext to its ascii number, then converts ascii number to its 8-bit representation & concatenates for all characters.""" nums = convert_to_num(plaintext) nums = [format(num, '08b') for num in nums] binary_string = ''.join(nums) return binary_string def convert_binary_to_text(binary_string): """Reverse of the above function.""" ascii_text = [] for i in range(0, len(binary_string), 8): temp_data = binary_string[i : i + 8] decimal_data = int(temp_data, 2) # converts 8-bit string to decimal ascii_text.append(decimal_data) return convert_to_text(ascii_text)
919fd01d12e48882bf9e80fd2fa1c0fc447c81a5
AMARTYA2020/nppy
/Project EULER/Problem_22.py
998
3.890625
4
''' Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file? ''' import string total_sum = 0 alphabets = {} capwords = string.ascii_uppercase for index, value in enumerate(capwords): alphabets.update({capwords[index]: index + 1}) with open('names.txt', 'r') as names: lines = [name.strip('"') for name in names.read().strip('\n').split(',')] lines.sort() for line in lines: total_sum += sum([alphabets[li] for li in line]) * (lines.index(line) + 1) print(total_sum)
91b485949feb1003b2e5e14872e26b2b96e7cc4f
shandaiwang/leetcode
/remove_duplicates_from_sorted_list.py
1,146
3.734375
4
__author__ = 'pld' import linkutils """ Given a sorted linked list, delete all duplicates such that each element appear only once. For example, Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3. """ class Solution(object): def deleteDuplicates1(self, head): """ :type head: ListNode :rtype: ListNode """ sentinel = head node = head while node: if node.val != sentinel.val: sentinel.next = node sentinel = node node = node.next if sentinel: sentinel.next = None return head def deleteDuplicates2(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return head node = head while node.next: if node.val == node.next.val: node.next = node.next.next else: node = node.next return head solution = Solution() head = linkutils.parse_array_2_list([1, 2, 3, 3, 3]) solution.deleteDuplicates2(head) linkutils.iterate_linked_list(head)
f9f1e15b0eae2d0bc831040bc0111d04f84f3103
realRichard/-offer
/chapterTwo/algorithmsAndDataManipulation/minNumber/1.2.py
1,112
3.765625
4
def my_min(arr): if not isinstance(arr, list): print('invalid input') return None for i in arr: if not isinstance(i, int): print('invalid input') return None if len(arr) == 0: return None start = 0 end = len(arr) - 1 middle = start # if the first < the last, means arr already sorted, return the first directly while arr[start] >= arr[end]: if end - start == 1: middle = end break middle = (start + end) // 2 # if the first the midlle, the last are equal # we can not determine the middle # but to sequential search if arr[start] == arr[end] and arr[middle] == arr[start]: return min(arr) if arr[middle] >= arr[start]: start = middle else: end = middle return arr[middle] def test(): l = [3, 4, 5, 6, 1] print(my_min(l)) a = [8, 9, 100, 2, 3, 4, 5] print(my_min(a)) # spercial test case b = [1, 1, 1, 0, 1] print(my_min(b)) if __name__ == '__main__': test()
1e80d4cf53291e6f5fdb3dfdcf844b3842a4fc68
Bouteloua/bioinformatics_p1
/GCcontent.py
810
3.640625
4
#By: Brian Franzone #Email: [email protected] #For: Bioinformatics E-100. assignment 1 problem 1 #Summary: This script determines the total amount of GC content ratio in a given sequence. Ignores codon structures. import random def main(): #N is the length of the randomly generated sequence N = 30000 print 'GC content of sequence is: %s out of %i bases' % (ratioGC(N), N) #This function first generates a random sequence, based off #N, and then calculates the percentage of GC in the sequence def ratioGC(N): bases = "ACTG" seq = "" for i in xrange(N): seq += bases[random.randint(0,3)] #Pseudocode for the equation. GC content = 100 * (number of "C"s + number of "G"s) / (length of sequence) return "%.02f" % (100.0 * (seq.count('G') + seq.count('C')) / float(len(seq))) if __name__ == '__main__': main()
144572ebb910e8855da87401d14835f02a99f897
sanster9292/Daily-Algorithm
/kangaroo.py
441
3.84375
4
''' PROBLEM URL: https://www.hackerrank.com/challenges/kangaroo/problem Description: For two kangaroos jumping in a positive direction on the x axis, tell if they will ever cross. '''' vals = input().strip().split(' ') x1, v1, x2,v2 = [int(i) for i in vals] first = x1-x2 second = v2-v1 if (x1<x2) and (v1<v2): print('NO') elif first%second ==0: print('YES') elif (x1<x2) and v1<v2: print('NO') elif v1==v2: print('NO')
c2c39d754f8feaf0342aa068507a596b16e35943
ralitsapetrina/Programing_basics
/exam_practice/9-10march2019/tennis_ranklist.py
560
3.5625
4
from math import floor number_plays = int(input()) start_points = int(input()) won_play = 0 tour_points = 0 for play in range(number_plays): play_outcome = input() if play_outcome == "W": tour_points += 2000 won_play += 1 elif play_outcome == "F": tour_points += 1200 elif play_outcome == "SF": tour_points += 720 avarage_points = 100 / number_plays * won_play print(f'Final points: {start_points + tour_points}') print(f'Average points: {floor(tour_points / number_plays)}') print(f'{avarage_points:.2f}%')
86da43ce94041f758810c0af5d4c26614048f210
Ramshiv7/Python-Codes
/Makes_twenty.py
328
4.21875
4
#### MAKES TWENTY: Given two integers, return True if the sum of the integers is 20 *or* if one of the integers is 20. If not, return False def makes_twenty(n1, n2): if n1 + n2 == 20 or (n1 == 20 or n2 == 20): print(True) else: print(False) makes_twenty(20, 10) makes_twenty(12, 8) makes_twenty(2, 3)
8f9058f339b5765054adcd840f8be899ea316dcf
viharati/fc_python
/04/4th-1.py
161
3.53125
4
# -*- coding:utf-8 -*- datafile = open('text2.txt', 'r') data = datafile.read() print(data+'\n\n') string=data.decode('utf-8').encode('euc-kr') print(string)
8a1d587a3a727a61ce8f33494485ab1a7e578b2f
IShahnawazShaikh/Python-Programming
/MapFilter.py
95
3.625
4
number=[1,2,3,4,2,6,2,2,9,10] def even_num(n): return n!=2 print(list(filter(even_num,number))
4e9cba77af2b9ce6913c0c8589e5dabcb3acfc23
t4rxzvf/IFT383
/mod-5/types.py
227
4.0625
4
#!/usr/bin/python myString="HELLO!" myNumber=123456 myFloat=3.14159 myList=[1, 2, 3, 4] print type(myString) print type(myNumber) print type(myList) print type(myFloat) if (type(myString) is str): print "We have a string!"
3cce9a30cb276ae3f367fd9310f3859c15654887
HuberTRoy/pythonTricks
/tricks/define_a_class_manually_by_namedtuple.py
380
3.96875
4
from collections import namedtuple # use string. Car = namedtuple('Car', 'name color') # use other iterable class. Car = namedtuple('Car', ['name', 'color']) my_car = Car('rabbit', 'light gray') # light gray. print(my_car.color) # Car(name='rabbit' , color='light gray') print(my_car) # Namedtuples are immutable. # AttributeError: can't set attribute. my_car.color = 'blue'
896c06b8248692d9750ab1a43d8697a05270107e
Edwin-Pau/FAM-Application
/driver.py
9,746
3.65625
4
#!/usr/bin/env python3 """ This module contains the Driver class and serves as the entry point for the Family Appointed Moderator application. """ from menu import Menu from transaction import Transaction from budget import BudgetManager, Budget from user import User from rich import print class Driver: """ An object of type Driver is responsible for running the F.A.M. application. It presents a list of menu options to the user that will let the user interact with the various features of the F.A.M. application for moderating their budgets and spendings. Acts as the middleman for all the various modules. Responsible for the application's flow of control and passing the flow of control to the right class based on user input. """ user_test_data = { "name": "Edwin Pau", "age": "31", "user_type": "3", "bank_account_number": "A01074676", "bank_name": "TD Bank", "bank_balance": "5000", "budget_games_and_entertainment": "200", "budget_clothing_and_accessories": "200", "budget_eating_out": "500", "budget_miscellaneous": "100" } """ Modifiable variable which is used for registering a test user for the load_test_data method in the Driver class. """ def __init__(self): """ Initialize a Driver object. The user object that belongs to the driver is created when the start method is called. """ self.user = None @staticmethod def load_test_user() -> User: """ Initializes and returns an object representing a test user with pre-set hardcoded settings and budgets. This is a helper function designed to speed up development. Uses the global variable dictionary USER_TEST_DATA for generating a new user. :return: User, an object of type User """ new_user = User.generate_new_user(Driver.user_test_data) return new_user def start(self) -> None: """ Entry method to start up the F.A.M. application. This method starts up the startup menu for registering a user, then proceeds to direct the flow of control to the main menu prompts. """ self.execute_startup_menu() self.execute_main_menu() def execute_startup_menu(self) -> None: """ Prompts the user to choose between creating a new user or loading the test user account. Creates a new user based on user input. This function sets this Driver's user account to the new User that is created. """ new_user = None user_choice = Menu.prompt_startup_menu() if user_choice == 1: user_data = User.prompt_user_registration() new_user = User.generate_new_user(user_data) elif user_choice == 2: new_user = Driver.load_test_user() elif user_choice == 3: print("Exiting F.A.M. application...") exit(1) self.user = new_user def execute_main_menu(self) -> None: """ Prompts the user with the main menu choices. Based on the user input, the function will direct the flow of control to the appropriate driver method to handle the logic for that function. """ user_choice = None while user_choice != 5: user_choice = Menu.prompt_main_menu() if user_choice == 1: self.view_budgets() elif user_choice == 2: self.record_transaction() elif user_choice == 3: self.view_transactions() elif user_choice == 4: self.view_bank_account_details() elif user_choice == 5: print("Exiting F.A.M. application...") exit(1) def view_budgets(self) -> None: """ Prompts the user with a budget they want to view. The budget details for each budget category in the budget manager is then printed out to the user. """ Menu.prompt_view_budgets() for budget in self.user.budget_manager: print(f"{budget}\n") def record_transaction(self) -> None: """ Prompts the user with the required input for recording a new transaction record. The new transaction is created if it is validated by the system checks. Notifies the user if the transaction failed or succeeded. The system refreshes the state of all the Budget objects in the BudgetManager and the Transaction objects in the TransactionManager. Finally it issues any notifications or warnings to the user. """ Menu.prompt_record_transaction() tx_data = Transaction.prompt_record_tx() new_tx = Transaction.generate_new_tx(tx_data) # Convert the user budget category int input to the enum budget_category_int = new_tx.budget_category budget_category = BudgetManager.category_mapping[budget_category_int] # Retrieve the budget object using the enum as the key budget = self.user.budget_manager.budget_dict[budget_category] # Validate the transaction before proceeding validated_tx, error_msg = self.validate_transaction_record(new_tx, budget) if not validated_tx: print("\n[red]Warning:[/red] Unable to record transaction!") print(error_msg) print(f"{self.user.account}\n") print(budget) return # User has successfully recorded a transaction budget.add_amount_spent(new_tx.tx_amount) self.user.account.add_amount_spent(new_tx.tx_amount) self.user.tx_manager.add_transaction(new_tx) self.user.update_lock_status() print("\nSuccessfully recorded the following transaction:") print(new_tx) print("\nTransaction has been recorded under the following budget " "category:") print(budget) self.user.check_and_issue_user_warnings(budget) def view_transactions(self) -> None: """ Prompts the user with the option to view transactions for an individual budget category. Once a budget category is selected, it prints out all the transactions that belong in that budget category. """ user_choice = Menu.prompt_view_transactions() if user_choice == 5: print("Returning to main menu...") return budget_category = BudgetManager.category_mapping[user_choice] print(f"\nTransactions in the {budget_category.value} " f"category: ") for tx in self.user.tx_manager: if tx.budget_category == user_choice: print(f"\n{tx}") def view_bank_account_details(self) -> None: """ Prints out the user's bank account details, including all the transactions conducted, as well as a spending summary. """ Menu.prompt_view_bank_account_details() print("Bank Account Details:") print(self.user.account) for tx_num, tx_details in \ self.user.tx_manager.transaction_records.items(): print(f"\nTransaction #{tx_num}:\n" f"{tx_details}") print(f"\nSpending Summary:") print(f" Starting Bank Balance: " f"{'{:.2f}'.format(self.user.account.starting_balance)}") print(f" Total Transactions Amount: " f"{'{:.2f}'.format(self.user.tx_manager.calc_total_spent())}") print(f" Closing Bank Account Balance: " f"{'{:.2f}'.format(self.user.account.current_balance)}") def validate_transaction_record(self, new_tx: Transaction, budget: Budget) -> (bool, str): """ This method is used to validate if a transaction can be successfully recorded for the user, based on his budget and account restrictions. :param new_tx: a Transaction object. :param budget: a Budget object. :return: a tuple of (a bool for validation, a str for error msg). """ budget_threshold = self.user.tx_manager.lock_threshold validated_tx = True error_msg = "" # Perform the various checks # TODO Can refactor in the future using chain of responsibility if self.user.account.locked_status: error_msg = error_msg + " The account has been locked out " \ "completely for exceeding the budgets " \ "in two categories!\n" validated_tx = False if budget.locked_status: error_msg = error_msg + " The budget category for the " \ "transaction entered is locked!\n" validated_tx = False if budget_threshold and \ new_tx.tx_amount > budget.amount_total * budget_threshold: error_msg = error_msg + " Exceeded allowable budget available " \ "for the category selected!\n" validated_tx = False if new_tx.tx_amount > self.user.account.current_balance: error_msg = error_msg + " Insufficient bank balance available " \ "to complete the transaction!\n" validated_tx = False return validated_tx, error_msg def main(): """ Entry point to the F.A.M. application. """ driver = Driver() driver.start() if __name__ == '__main__': main()
e415e6d2e9654088096891c556930469904e8244
Michaeloye/python-journey
/simp-py-code/time.py
96
3.6875
4
import time print(time.time()) for letter in range(ord("a"),ord("y")+1): print(chr(letter))