blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
922638b27f743c13fbed9bf09b4b498a2b72f487
dataOtter/CodeFights-Python3
/challenge3_secret_lock.py
6,336
3.984375
4
""" SUBMITTED IN JAVASCRIPT. THIS PYTHON SOLUTION NOT FINISHED. CFBot stores all of her important information in the Secret Archives. CodeMaster is trying to pick the lock! The lock, a metal rectangle composed of movable cells, is unique and hard to pick. Some of the lock’s cells are occupied, and some are empty. The lock is unlocked when its occupied cells form a specific configuration. The lock is represented as a matrix. The lock’s occupied cells are represented by an uppercase English letter A-Z and its empty cells are represented by .. When CodeMaster puts a magnet on one of the lock’s sides, all the occupied cells shift toward that end of the lock. The sequence of actions is a string that can contain the uppercase English letters L (left), R (right), D (down), and U (up), which represent the side of the lock that CodeMaster places the magnet on. Given the initial state of the lock and a sequence of actions, your function should return the final state of the lock to the Secret Archives.""" def secret_archives_lock(lock, actions): """Input: array.string lock, string actions. The lock’s occupied cells are represented by an uppercase English letter A-Z and its empty cells are represented by .. Guaranteed constraints: 1 ≤ lock.length ≤ 300, 1 ≤ lock[i].length ≤ 300. Each element in this string is L, R, D, or U (left, right, down, or up), and indicates the side of the lock on which CodeMaster has placed the magnet. Guaranteed constraints: 1 ≤ actions.length ≤ 50. Output: array.string. The final state of the lock to the Secret Archives.""" lck = [] positions = [] rows = len(lock) columns = len(lock[0]) for i in range(rows): lck.append(list(lock[i])) # turn the list of strings lock into a list of lists lck for j in range(columns): if lck[i][j] != '.': positions.append([i, j]) # put all letter positions in a list of lists, in order of appearance for char in actions: if char == 'L': move_left(lck, positions) print(lck) elif char == 'R': move_right(lck, positions, columns) print(lck) elif char == 'D': move_down(lck, positions, rows) print(lck) elif char == 'U': move_up(lck, positions) print(lck) for i in range(rows): lck[i] = ''.join(lck[i]) return lck def move_left(lk, pos): """Input: lock array l, list of letter position tuples pos Output: Moves all letters as far left as possible""" for i in range(len(pos)): x, y = pos[i][0], pos[i][1] # set x and y to equal the coordinates/position of a letter in the array lock if y != 0: # if the letter is not already located on the left edge of the array lock try: new_y = lk[x].index('.') # find first empty position in row x except ValueError: break if new_y < y: # if it is to left of current letter pos[i] = move_letter(lk, x, x, y, new_y) sort_positions(pos) def move_right(lk, pos, c): """Input: lock array l, list of letter position tuples pos Output: Moves all letters as far right as possible""" i = len(pos) - 1 while i >= 0: # go through the list of positions backwards in order to get the rightmost letters first for each row x, y = pos[i][0], pos[i][1] # set x and y to equal the coordinates/position of each letter in array lock if y != c - 1: # if the letter is not already located on the right edge of the array lock try: new_y = lk[x][::-1].index('.') # find last empty position in row x except ValueError: break if new_y > y: # if it is to right of current letter pos[i] = move_letter(lk, x, x, y, new_y) i -= 1 sort_positions(pos) def move_down(lk, pos, r): """Input: lock array l, list of letter position tuples pos Output: Moves all letters as far down as possible""" i = len(pos) - 1 no_dot = True while i >= 0: # go through the list of positions backwards in order to get the bottom letters first for each column x, y = pos[i][0], pos[i][1] # set x and y to equal the coordinates/position of a letter in the array lock dot = x if x != r - 1: # if the letter is not already located on the bottom edge of the array lock if no_dot: new_x = r - 1 while new_x > x: # look only below current letter if lk[new_x][y] == '.': # find first empty position in column y, if any pos[i] = move_letter(lk, x, new_x, y, y) dot = new_x no_dot = False break new_x -= 1 no_dot = False else: dot -= 1 pos[i] = move_letter(lk, x, dot, y, y) i -= 1 sort_positions(pos) def move_up(lk, pos): """Input: lock array l, list of letter position tuples pos Output: Moves all letters as far up as possible""" for i in range(len(pos)): x, y = pos[i][0], pos[i][1] # set x and y to equal the coordinates/position of a letter in the array lock if x != 0: # if the letter is not already located on the top edge of the array lock for new_x in range(x): # look only above current letter if lk[new_x][y] == '.': # find first empty position in column y, if any pos[i] = move_letter(lk, x, new_x, y, y) break sort_positions(pos) def move_letter(lck, x, new_x, y, new_y): letter = lck[x][y] lck[new_x][new_y] = letter # move the letter to that empty position lck[x][y] = "." return [new_x, new_y] # update the list of positions def sort_positions(p): p.sort(key=lambda x: (x[0], x[1])) l = ["...PD.O..P", ".MF.......", "Q.....I...", "....JNJ...", ".Y..O.O.J.", "V..U......", "..J..H....", "....T.J...", "W.....A.B.", ".P....O.K."] l2 = ["..A.", ".BC.", "....", "...D"] l3 = ["AB", "CD"] actions = "RURLD" print(secret_archives_lock(l2, actions))
49d0219eee28806167bced5b573d97aab67d17ba
Skumbatee/andela-labs
/stringlength.py
373
4.1875
4
# declare a function that takes a list argument def check_string(items): # declare an empty list where you will append the length for strings empty = [] # loop through the list argument for item in items: # append the length of strings in the list in empty list empty.append(len(item)) return empty print check_string(["Beth","Lynn","Monica","Kathure","Martha"])
10c48cf87f9d8686b42213a5af4ae9dd6198cd02
Jassii/HackerRank-Solution-Python-language-
/Compress_the_String.py
235
3.859375
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import itertools s = input() #input of the string.. for k,a in itertools.groupby(s): #passing the string print("({}, {})".format(len(list(a)),k),end=" ")
b1c3e027e30e36a99afb65ccba9d7e21e4394974
ampasancho/GithubTraining
/src/ejer.py
230
3.71875
4
def showNumbers: number = input("Introduce numero: ") for i in range(0, number+1) print(i + "\n") def par_impar(numero): resto = numero % 2 if resto == 1: return 1 else: return 0
66110c655443f265965a3caa2ab4972d676f08df
RAmruthaVignesh/PythonHacks
/DataStructures/linkedlist.py
4,771
4.1875
4
class node(object): data = None ptr = None class LL(object): head = None def __init__(self): pass def insert(self , position,value): # Insertion when the linked list is empty if self.head == None: mynode = node() mynode.data = value mynode.ptr = None self.head = mynode else: sizell=self.size() #Insertion in the beginning if position == 0: mynode = node() mynode.data=value mynode.ptr = self.head self.head = mynode #insertion when the position is provided elif position <= sizell: mynode = node() prevnode = node() mynode.data = value temp=self.traverseposition(position) mynode.ptr=temp[0] #print "mynode pointer is" , mynode.ptr.data #print "position is" , position temp = self.traverseposition(position-1) prevnode = temp[0] #print "prevnode data is" , prevnode.data prevnode.ptr = mynode else: print "Enter the correct postion" #This function inserts the value at the end of the linkedlist def insertend(self,value): mynode = node() mynode.data= value mynode.ptr = None temp= self.traverseposition("full") lastnode = temp[0] lastnode.ptr = mynode #This fuction deletes the value at the end of the linkedlist def delend(self): llsize=self.size() temp = self.traverseposition(llsize-2) lastnode=temp[0] lastnode.ptr = None #This function deletes the node at the given position def delete(self,position): sizell = self.size() if (sizell>0 and position<=sizell and position>=0): #Checks boundary conditions temp = self.traverseposition(position) currentnode = temp[0] if position == 0: #Deleting the first node temp = self.traverseposition(position+1) nextnode = temp[0] self.head = nextnode elif position >0 :# Function to delete the nodes from 2nd to last temp = self.traverseposition(position-1) prevnode = temp[0] if position <sizell: #Deleting nodes in the middle temp = self.traverseposition(position+1) nextnode = temp[0] prevnode.ptr = nextnode else: # Deletes last node prevnode.ptr = None else: print "Invalid position" #This function returns the size of the linkedlist def size(self): sizecount = 0 temp = self.traverseposition("full") size = temp[1]+1 return size # Function to traverse through the linked list . It takes in position of the node and gives the size and node at the given position def traverseposition(self,location): #print "location is" , location loccount = 0 tempnode = self.head while (loccount <location and tempnode.ptr !=None): # When the size till the given position is requested tempnode = tempnode.ptr loccount = loccount+1 while (loccount == "full" and tempnode.ptr !=None): # When the size of the LL is requested tempnode = tempnode.ptr loccount = loccount+1 return [tempnode,loccount] #This function prints the linked list def printll(self): tempnode = self.head x=[] def traversenode(tnode): if tnode.ptr != None: x.append(tnode.data) tnode = tnode.ptr traversenode(tnode) else: x.append(tnode.data) traversenode(tempnode) print "The Linked list is ",x newlist = LL() newlist.insert(0,2) newlist.insert(0,1) newlist.insert(1,1.5) newlist.insertend(3) newlist.insert(3,2.5) newlist.printll() print "The size of the linked list is" , newlist.size() newlist.delend() print "The LL after deleting the last node is" newlist.printll() print "The size of the linked list after deleting the last node is" , newlist.size() newlist.delete(2) print "The LL after deleting node in 2nd position" newlist.printll() print "The size of the linked list after deleting node in 2nd position ", newlist.size() newlist.delete(0) print "The LL after deleting first node" newlist.printll() print "The size of the linked list after deleting 1st node" , newlist.size() newlist.delete(100) # print "--------" # newlist.insert(1,300) # newlist.printll()
3eb1ee4b2c391cc3da0ed50a0e6c4d7465bf7d1d
AZ-OO/Python_Tutorial_3rd_Edition
/4章 制御構造ツール/4.7.4.py
611
3.671875
4
""" 4.7.4 引数リストのアンパック """ # 引数にしたいものがすでにリストやタプルになっていて、 # 位置してい型行き数を要求する関数のためにアンパックしなければならないという時 print(list(range(3,6))) args = [6,10] print(list(range(*args))) def parrot(voltage, state = 'a stiff', action = 'voom'): print("This parrot wouldn't", action, end= ' ') print("if you put", voltage, 'volts through it.', end = ' ') print("E's", state, '!') d = {"voltage":'four million', "state":"bleedin' demised", 'action':'VOOM'} print(parrot(**d))
92a14f8b5c43a427db7540d9c056016d36a9b635
DeanHe/Practice
/LeetCodePython/MaximumTwinSumOfaLinkedList.py
2,151
4.15625
4
""" In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1. For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only nodes with twins for n = 4. The twin sum is defined as the sum of a node and its twin. Given the head of a linked list with even length, return the maximum twin sum of the linked list. Example 1: Input: head = [5,4,2,1] Output: 6 Explanation: Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6. There are no other nodes with twins in the linked list. Thus, the maximum twin sum of the linked list is 6. Example 2: Input: head = [4,2,2,3] Output: 7 Explanation: The nodes with twins present in this linked list are: - Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7. - Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4. Thus, the maximum twin sum of the linked list is max(7, 4) = 7. Example 3: Input: head = [1,100000] Output: 100001 Explanation: There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001. Constraints: The number of nodes in the list is an even integer in the range [2, 105]. 1 <= Node.val <= 10^5 """ from typing import Optional class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class MaximumTwinSumOfaLinkedList: def pairSum(self, head: Optional[ListNode]) -> int: res = 0 def find_mid(dummy): slow = fast = dummy while fast and fast.next: fast = fast.next.next slow = slow.next return slow def reverse(cur): dummy = ListNode(0) while cur: post = cur.next cur.next = dummy.next dummy.next = cur cur = post return dummy.next a = head b = reverse(find_mid(head)) while a and b: res = max(res, a.val + b.val) a = a.next b = b.next return res
a41a81204ca32860b4f37dff534be53488e7e108
mdk7554/Python-Exercises
/MaxKenworthy_A2P1.py
2,024
4
4
""" Exercise: Given a flat text file containing names of boys and girls, create a function that records the number of times each name ends in a certain letter of the alphabet. Executing the function produces a 26x2 dataframe where each letter of the alphabet has a row and a column for each boy and girl names. """ import pandas as pd def print_last_char(): #open and read in text file to lists gfile = open(".../namesGirls.txt",'r') bfile = open(".../namesBoys.txt",'r') girls = gfile.read().split('\r\n') boys = bfile.read().split('\r\n') gfile.close() bfile.close() #create 2 new empty lists for last characters of names g_char,b_char = [],[] #iterate through each list collecting last characters of all names for i in girls: for j in i: g_char.append(i[-1]) break for k in boys: for l in k: b_char.append(k[-1]) break #convert to Pandas Series and use value_counts to sum all unique values last_chars_b = pd.Series(b_char).value_counts(sort=False) last_chars_g = pd.Series(g_char).value_counts(sort=False) #make internal alphabet list alpbt = pd.Series(['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']) #check last character lists if missing any letters of alphabet, if so impute 0 for k in alpbt: if k not in last_chars_b.index: last_chars_b=last_chars_b.append(pd.Series([0],[k])) for t in alpbt: if t not in last_chars_g.index: last_chars_g=last_chars_g.append(pd.Series([0],[t])) #sort Series by index alphabetically chars_sortb = pd.Series.sort_index(last_chars_b) chars_sortg = pd.Series.sort_index(last_chars_g) #concatenate boy & girl and apply column header df = pd.concat([chars_sortg,chars_sortb],axis=1) df.columns=['Girls','Boys'] return df
d17c130017712e620cdb75caf7f3d8624c956ed8
lalaboom/algorithm-practice
/剑指offer/从上往下打印二叉树.py
747
3.90625
4
#从上往下打印二叉树 # 题目: #从上往下打印出二叉树的每个节点,同层节点从左至右打印。 # 思路: #遍历二叉树的两种方式: # 1.递归 # 2.非递归,入栈:根节点入栈,如果节点不为空,处理这个节点,同时左右子节点入栈 class Solution: # 返回从上到下每个节点值列表,例:[1,2,3] def PrintFromTopToBottom(self, root): if not root: return [] temp = [root] result = [] while len(temp): cur = temp.pop(0) result.append(cur.val) if cur.left: temp.append(cur.left) if cur.right: temp.append(cur.right) return result
b295d06ce695d5d627ff0cd380046f5848149ac9
rkujawa/py-exercises-osec
/ex09/order_csv.py
265
3.59375
4
#!/usr/bin/env python3 from order import * import csv class OrderCSV(Order): def save(self, filename): with open(filename, 'w') as csvfh: writer = csv.writer(csvfh) for i in self: writer.writerow(i.to_list())
2f3d7936617707d05ad8bec61c08fd1451f2e1b7
VivekVRaga/Coding-Projects
/Fantasy Game.py
614
3.515625
4
stuff = {'rope': 1, 'torch': 6, 'gold': 42, 'dagger': 1, 'arrow': 12} loot = ['gold', 'dagger', 'gold', 'gold', 'ruby'] def dispinventory(inven): print('inventory:\n') for k, v in inven.items(): print(k+'\t', v) def addinventory(inven, ainven): for i in range(0, 5, 1): print(ainven[i], ' ', 'Added') if ainven[i] not in inven.items(): inven.setdefault(ainven[i], 0) if ainven[i] in inven.keys(): inven[ainven[i]] += 1 dispinventory(stuff) print('\n') print(loot) addinventory(stuff,loot) dispinventory(stuff)
dd0358dd5cf112ebb7efaf1acb944d967a41d2a7
Drag0nus/Challenges
/Easy_Challenges/list_low10.py
719
4.40625
4
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] for item in a: if item < 5: print(item) num = int(input("Enter number: ")) result = [item for item in a if item < num] print(result) # Take a list, say for example this one: # a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] # and write a program that prints out all the elements of the list that are less than 5. # # Extras: # Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list # in it and print out this new list. Write this in one line of Python. Ask the user for a number and return a # list that contains only elements from the original list a that are smaller than that number given by the user.
7eae9cd800f809d5967710afceecb8b7b1f140f5
zjlyyq/algorithm009-class01
/LeetCode/9. 回文数(翻转数字).py
499
3.578125
4
class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False x_reversed = 0 x_length = 0 x_copy = x while x_copy > 0: x_copy = int(x_copy / 10) x_length = x_length + 1 l = int(x_length / 2) while l > 0: x_reversed = x_reversed * 10 + (x % 10) x = int(x / 10) l = l - 1 if (x_length % 2) != 0: x = int(x / 10) return x == x_reversed
5a5590671f8c21cb76c07d08aba345f3d1bc72d9
grebwerd/python
/practice/practice_problems/flipAndInvertImage.py
393
3.5
4
class Solution: def flipAndInvertImage(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ for l in A: l.reverse() for index, value in enumerate(l): if value is 0: l[index] = 1 else: l[index] = 0 return A
c1f8b26952c31e48b18fb1815e2cc8540727bd85
sidrashareef99/exactDollar
/main.py
668
3.96875
4
pennies = int(input('Enter the number of pennies:')) quarters = int(input('Enter the number of quarters:')) nickels = int(input('Enter the number of nickels:')) dimes = int(input('Enter the number of dimes:')) pennies_total = pennies * 0.01 nickels_total = nickels * 0.05 quarters_total = quarters *.25 dimes_total = dimes*.1 total_amount = pennies_total+nickels_total+quarters_total+dimes_total print('Total amount entered: $',format(total_amount, '.2f'),sep='') if total_amount == 1: print('You have exactly one dollar.') elif total_amount > 1: print('The amount entered is more than one dollar.') else: print('The amount entered is less than one dollar.')
fdfd63c1817570142894f7ce1a77cfe62a553c5b
sgarcialaguna/Project_Euler
/problem2.py
675
3.953125
4
"""Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.""" from functools import lru_cache @lru_cache() def fib(n): if n == 0: return 1 if n == 1: return 2 return fib(n-1) + fib(n-2) if __name__ == '__main__': sum_ = 0 for i in range(1, 1000000): f = fib(i) if f > 4000000: break if f % 2 == 0: sum_ += f print(sum_)
80362116992cdbfadd72cf4f7c24c1938d64470a
xjh1230/py_algorithm
/test/l617merge_tree.py
5,003
3.59375
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Author : 1230 # @Email : xjh_0125@sina.com # @Time : 2019/11/22 13:09 # @Software: PyCharm # @File : l617merge_tree.py from data_structure.leecode_tree_node import TreeNode from data_structure.leecode_tree_node import gen_tree from data_structure.leecode_tree_node import print_tree import math class Solution: def __init__(self): """ """ pass def mergeTrees1(self, t1: TreeNode, t2: TreeNode) -> TreeNode: def get_one(li): if li: return li.pop(0) else: return None if not t1 and not t2: return None res_t = TreeNode(0) left_stack = [t1] right_stack = [t2] res_stack = [res_t] while left_stack or right_stack: left = get_one(left_stack) right = get_one(right_stack) cur = get_one(res_stack) if cur: if left: cur.val += left.val left_stack.append(left.left) left_stack.append(left.right) else: left_stack.append(None) left_stack.append(None) if right: cur.val += right.val right_stack.append(right.left) right_stack.append(right.right) else: right_stack.append(None) right_stack.append(None) if (left and left.left) or (right and right.left): cur.left = TreeNode(0) else: cur.left = None res_stack.append(cur.left) if (left and left.right) or (right and right.right): cur.right = TreeNode(0) else: cur.right = None res_stack.append(cur.right) return res_t def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: ''' 超时没通过 :param t1: :param t2: :return: ''' def to_li(t: TreeNode): if t: stack = [t] res = [] dep = 0 while stack: c = len(stack) tmp = [None] * 2 * c has_next = False i = 0 dep += 1 while stack: cur = stack.pop(0) if cur: has_next = True res.append(cur.val) tmp[i * 2] = cur.left tmp[i * 2 + 1] = cur.right else: res.append(None) tmp[i * 2] = None tmp[i * 2 + 1] = None i += 1 if has_next: stack = tmp res = res[:int(math.pow(2, dep - 1)) - 1] return res def add_li(li1, li2): def my_sum(l, r): if l is None: return r elif r is None: return l return l + r c1 = len(li1) c2 = len(li2) if c1 > c2: sub = c1 - c2 li2.extend([None] * sub) elif c2 > c1: sub = c2 - c1 li1.extend([None] * sub) res = [my_sum(li1[i], li2[i]) for i in range(len(li1))] return res def to_tree(li): root = TreeNode(li.pop(0)) stack = [root] while li: cur = stack.pop(0) if cur: v_left = li.pop(0) v_right = li.pop(0) left = TreeNode(v_left) if v_left is not None else None right = TreeNode(v_right) if v_right is not None else None cur.left = left cur.right = right stack.append(left) stack.append(right) else: li.pop(0) li.pop(0) stack.append(None) stack.append(None) return root if t1 is None: return t2 if t2 is None: return t1 li1 = to_li(t1) li2 = to_li(t2) res = add_li(li1, li2) return to_tree(res) if __name__ == '__main__': sc = Solution() li1 = [4, -9, 5, None, -1, None, 8, -6, 0, 7, None, None, -2, None, None, None, None, -3] li2 = [5] t1 = gen_tree(li1) t2 = gen_tree(li2) t = sc.mergeTrees(t1, t2) print(print_tree(t, True)) t = sc.mergeTrees1(t1, t2) print(print_tree(t, True)) # [9,-9,5,null,-1,null,8,-6,0,7,null,null,-2,null,null,null,null,-3]
65e579b0d9fb523b7e44bdf4efffa5cff325c996
AbidMerchant-1106/CompetitiveProgramming
/binlevelordertraversal.py
2,203
3.765625
4
class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None class Solution2: def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ def dfs(node, depth): if node is None: return if len(self.ans) > depth: self.ans[-1-depth].append(node.val) else: self.ans = [[node.val]]+self.ans dfs(node.left, depth+1) dfs(node.right, depth+1) self.ans = [] dfs(root, 0) return self.ans class Solution: def bfs(self, root): """ :type root: TreeNode :rtype: List[int] """ traversedvalues = list() queue = list() queue.append(root) while (queue): currentnode = queue.pop(0) if (currentnode.left): queue.append(currentnode.left) if (currentnode.right): queue.append(currentnode.right) traversedvalues.append(currentnode.val) return traversedvalues def dfs(self, node, depth): if node is None: return if len(self.leveltraversed) > depth: self.leveltraversed[-depth - 1].append(node.val) else: self.leveltraversed = [[node.val]] + self.leveltraversed self.dfs(node.left, depth + 1) self.dfs(node.right, depth + 1) def levelOrderTraversal(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ self.leveltraversed = [] self.dfs(root, 0) return self.leveltraversed root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) root.right.right = TreeNode(6) root.left.left.left = TreeNode(7) root.left.left.right = TreeNode(8) root.left.right.left = TreeNode(9) root.left.right.right = TreeNode(10) root.right.right.left = TreeNode(11) print (Solution().levelOrderTraversal(root))
e9b4a865844c6da50ad1da9ba9424eadfd6714be
jasminro/2021python
/Week4/h5.py
625
4.1875
4
''' Harjoitus 5 Palindromi Kirjoita funktio, joka tarkistaa, onko sana palindromi. Palindromi on sana, joka on sama kirjoitettuna oikein ja väärin päin. Sanan kirjainten koolla ei ole merkitystä. Oletus: Sana ei sisällä white space -merkkejä (rivinvaihto, välilyönti, tabulaattori). Bonus: Sana saa sisältää white space -merkkejä, mutta niitä ei oteta huomioon tarkistettaessa, onko sana palindromi. ''' def isPalindrome(s): return s == s[::-1] # Driver code s = input("give a word : ") ans = isPalindrome(s) if ans: print("Yeah, it's a palindrome!") else: print("Nope, it's not a palindrome.")
a654bc0124c1097504d2d8c46af60d21ace10bf9
AmuroPeng/CodingForInterview
/2020April-30-day-leetcoding-challenge/16-Valid Parenthesis String/16-Valid Parenthesis String.py
1,217
3.734375
4
import collections class Solution: def checkValidString(self, s: str) -> bool: # chars = collections.deque(s) # left = 0 # right = 0 chars = [] count = 0 for i in s: if i == "(" or i == "*": chars.append(i) else: # ")" if chars == []: if count: count -= 1 else: return False elif chars[-1] == "(": chars.pop() else: for j in reversed(chars): if j == "*": chars.pop() count += 1 else: chars.pop() break while chars: if chars[-1] == "*": count += 1 chars.pop() else: # "(" if count: count -= 1 chars.pop() else: return False return True if __name__ == "__main__": s = Solution() print(s.checkValidString("(*))"))
65b795173f96011785806c20edfc067ecd553e96
runbrain/fluffy-doodle
/AByteOfPython/if.py
212
3.875
4
import antigravity number = 32 guess = int(input('input integer : ')) if guess == number: print('congradulations you right') elif guess < number: print('value is biger') else: print('value is smaler')
922a17d63c01c8bc1a4706a733c6bcd2941f6de2
Abel-Fan/USTF1908
/python02/01回顾.py
2,923
4.03125
4
# python # 语法特点:面向对象的、动态类型、强类型语言。严格的缩进模式 # 注释: # 单行注释 # # 多行注释 """ """ ''' ''' # 输入输出 # input(info) info:用户提示信息 # print([arg1,arg2,....]) 参数不限 参数可以是 变量、值、表达式 # end 输出内容末位的字符,默认\n # name = "小白" # print(name,19,20+56) # print("123",end="") # print("456",end="") # 变量 # 变量定义:可变的数据 # 变量的定义语法: # 简单定义 name="小白" # 链式定义 name=name1="小白" # 多元定义 name1,name2,nam3 = 小白,小黑,小红 # 变量名 命名的规范: # 1.变量名只能由字母、数字、下划线构成 数字不能开头 中文也可以作为变量名 # 2.不能使用关键字和保留字 del list print input # 3.严格区分大小写 # 4.尽量语义化 # 数据类型(8个) # Number( int | float ) # 二进制 八进制 十进制 十六进制 # 科学记数法 # Str # 字符编码:ASCII GBK GB2312 UTF-8 unicode # 语法: '' "" ''' ''' """ """ # 转义字符: \" \' \\ \n \r \t # 字符前缀: r"" 取消转义字符 # r"\n" \n # 切片工具 # [start:end:step] # 补充: 模板字符串 # s d f # 语法 # t1 = '%s/%s/%s %s:%s:%s'%(2019,8,27,9,6,10) # t2 = '%d/%2d/%2d'%(2019,1,1) # t3 = '%d/%2d/%2d'%(2019,11,11) # p1 = "$%0.2f"%(30) # print(p1) # None # Bool # True False # List # 定义: 用来存储一系列相关数据的集合 # 语法: [item1,item2,...] # 注意:可以创建空列表、含有一个元素的列表;列表元素可以是任意数据类型 # [ [] ,[], True,None ,"sdf",123,{},{'name':'小白'}] # 二维列表与多维列表 # 基本操作 # 1.addItem # 2.delItem # 3.deitItem # 4.访问 item # arr1 = [ [1,2] , [3,4] ] # 访问 # print(arr1[0][0]) # Tuple # 元组:不可改变的列表 # 语法: t1 = (item1,item2,...) # 注意: 元组可以创建空元组 ,也可以创建只有一个元素的元组,形式:(1,)。 # t1 = ([1,2],[3,4]) # t1[0][0]="aa" # print(t1) # 浅拷贝 与 深拷贝 # arr1 = [1,2,3,4] # arr2 = arr1 # arr2 = [] # arr2.append(arr1[0]) # arr2.append(arr1[1]) # arr2.append(arr1[2]) # arr2.append(arr1[3]) # arr1 = [[1,2],[2,3]] # arr2 = [] # arr2.append(arr1[0]) # arr2.append(arr1[1]) # # arr2[0][0]="aa" # print(arr1) import copy # arr1 = [1,2,3] # arr2 = copy.copy(arr1) # arr2[0] = "aa" # print(arr1) # arr1 = [[1,2],[2,3]] # arr2 = copy.deepcopy(arr1) # arr2[0][0]="aa" # print(arr1) # 字典 # 语法:{'键':'值',} 键值对 # 注意: 值可以是任意类型,键必须是不可变数据,字典没有顺序的。 # 基本操作 # 访问 # 添加 # 删除 # 修改 # 集合 # 语法 {item1,item2,...} # 注意点:集合是不重复的 # 操作 # 添加 update add # 删除 remove pop(首位删除) # 交并补 # 数据类型转换 # int float str bool list set
6b14803f68ed877e172854c6c768c14aebd61994
DeathStroXX/Coding
/Codes/Array/Q5aUsingTwoPointer.py
1,015
3.765625
4
def NumberOfTriangles(array): n = len(array) array.sort() print(array) count = 0 for i in range(n-1,0,-1): l = 0 # This is the beginning pointer. r = i - 1 # this is the pointer just before the end pointer. while l < r: if array[l] + array[r] > array[i]: count += r - l # for explanation of this if forget must see the video again. r = r-1 # Checking for more values by decreasing the 2nd last pointer. else: l+=1 # If not found result then increasing the value of the starting pointer print("Number of possible Triangles: ",count) array = [4, 6, 3, 7] NumberOfTriangles(array) # [a,b,c,d] # 1< 5> 2 <4>3 # def findA(arr): # n=len(arr) # mid=n//2+1 # for i in range(0,n):+ # if a[i]>a[i+1]: # a[i+1],a[i]=a[i],a[i+1] # if i+1<n: # if a[i]<a[i+1]: # a[i+1],a[i]=a[i],a[i+1] # array = [2,3,4,5,6,8,9] # findA(array)
ad3061242c6fad992cc271d57a0185d8b616e3d1
jrpresta/AdventOfCode2020
/Day2/puzzle.py
1,599
3.65625
4
class PasswordRules: def __init__(self, min, max, letter, pw): self.min = int(min) self.max = int(max) self.letter = letter self.pw = pw def validate(self): count = self.pw.count(self.letter) return self.min <= count <= self.max class PasswordRulesNew: def __init__(self, first_position, second_position, letter, pw): self.first_position = int(first_position) self.second_position = int(second_position) self.letter = letter self.pw = pw def validate(self): fp_valid = self.pw[self.first_position-1] == self.letter sp_valid = self.pw[self.second_position-1] == self.letter return fp_valid + sp_valid == 1 def parse_lines(ln): """Parse apart the format from the given txt file""" triplets = ln.split() min = triplets[0].split('-')[0] max = triplets[0].split('-')[1] letter = triplets[1].split(':')[0] pw = triplets[2] return (min, max, letter, pw) def main1(input_path): with open(input_path, 'r') as f: data = [parse_lines(ln) for ln in f.readlines()] data = [PasswordRules(v[0], v[1], v[2], v[3]) for v in data] return sum([p.validate() for p in data]) def main2(input_path): with open(input_path, 'r') as f: data = [parse_lines(ln) for ln in f.readlines()] data = [PasswordRulesNew(v[0], v[1], v[2], v[3]) for v in data] return sum([p.validate() for p in data]) if __name__ == '__main__': input_file = './input.txt' print(main1(input_file)) print(main2(input_file))
694e8f7bc11806c24d3907c7af74805fb62d735e
LucMatheus/py3.GuanaPy
/World 3 - Mundo 3 - Intermediario/73 - Brasileirão.py
1,239
3.953125
4
''' Exercicios de tuplas agora trabalhando com a tabela do brasileirão @author Lucas Matheus Costa <teclucas.costa@hotmail.com> @since 18/07/2021 ''' #Colocando a tabela do Brasileirão tabelaDoBrasileirao = ('Palmeiras','Atlético-MG','Fortaleza','Bragantino','Athletico-PR','Ceará SC','Bahia','Fluminense','Flamengo','Santos','Atlético-GO','Corinthians','Juventude','São Paulo','Internacional','América-MG','Cuiabá','Sport Recife','Grêmio','Chapecoense') tam = len(tabelaDoBrasileirao) # <- Variável de controle #Imprimindo os primeiros colocados print("===OS PRIMEIROS COLOCADOS SÃO ===") for times in range(0, 5): print("{}ª Posição - {}".format(times+1,tabelaDoBrasileirao[times])) #Imprimindo os últimos colocados print("=== OS LANTERNAS SÃO ===") gatilhoLanterna = tam - 5 for times in range(gatilhoLanterna,tam): print("{}ª Posição - {}".format(times+1,tabelaDoBrasileirao[times])) #Imprimindo os times em ordem alfabética print("=== OS TIMES EM ORDEM ALFABÉTICA SÃO ===") timesEmOrdemAlfabetica = sorted(tabelaDoBrasileirao) for time in timesEmOrdemAlfabetica: print("- {}".format(time)) #Colocando a chapecoense print("="*30) print("A Chapecoense está na {}ª posição".format(tabelaDoBrasileirao.index('Chapecoense')+1))
5e914eb40b7c003f543d7c78aab7460691b7bd6d
mrgyange/python-project
/Matamorosa_e1.py
701
3.828125
4
# filename : Matamorosa_e1.py # author : Marge Angela P. Matamorosa # description : This is a python program that prints # the contents of a dictionary in a specific format message = "I am {}.\n" + "My spirit animal is {},\n" + \ "because {}.\n" + \ "When not in school, I love to {}.\n" + \ "I dream of being a/an {} in the future." data = {"Name" : "Marge Angela Pilapil Matamorosa", "spirit_animal" : "Dog", "reason" : "dogs shows service and loyalty generously to others", "hobby" : "sleep", "profession" : "Psychologist"} print(message.format(data["Name"], data["spirit_animal"], data["reason"], data["hobby"], data["profession"]))
3b7b15ec3edf9790f32da1e19aa6c8320cfb459b
gmotzespina/Algorithms
/numbers/plusOneSplit.py
335
3.515625
4
#!/usr/bin/python3 number = ["9","9","9"] convertArrayToString = lambda number: "".join(number) incrementByOne = lambda number: number+1 numToIncrement = int(convertArrayToString(number)) incrementedNumber = incrementByOne(numToIncrement) incNumString = str(incrementedNumber) incNumArray = list(incNumString) print(incNumArray)
e31e59c6552e1efc52c96c68d901b78d82bc4f8e
yom-elect/free-up
/gufdd.py
1,530
3.5625
4
from collections import Counter import statistics '''d = {'a':2, 'b':4, 'c':10} def fun(a, b, c): print(a, b, c) # A call with unpacking of dictionary fun(**d) string1 = input ("insert string1 :") string2 = input ("insert string2 :") dict1, dict2 = Counter(string1), Counter(string2) keys1, keys2 = dict1.keys(), dict2.keys() len1, len2 = len(keys1) , len(keys2) set1 = set(keys1) commmon_keys = len (set1.intersection(keys2)) if commmon_keys ==0 : print (len1 + len2 ) else : print (max(len1,len2)- commmon_keys)''' data = [1,2,4,5,7,7,8] n = len (data) mean = 0 for i in range (0, n): mean += data[i] print (float(mean/n)) if n% 2!= 0 : median = sorted(data) print (median[n//2]) elif n % 2 ==0 : med = sorted(data) median = ((med[(n-1)//2])+(med[n//2]))//2 print (median) print (statistics.mode(data)) ''n=int(input()) x=sorted(list(int(i) for i in input().split(" "))) t=max(x.count(i) for i in x) print(sum(x)/n) print((x[len(x)//2]+x[len(x)//2-1])/2) print(min(i for i in x if x.count(i)==t)) n = int (input()) data = s''' import statistics data = map(int,input().split()) n = (input()) mean = 0 for i in range (0, n): mean += data[i] print ((mean/n)) if n% 2!= 0 : median = sorted(data) print (median[n//2]) elif n % 2 ==0 : med = sorted(data) median = ((med[(n-1)//2])+(med[n//2]))//2 print (median) print (statistics.mode(data))
38f79d163a869392b37353023b55836a303d0842
davidlowryduda/AoC18
/python/utils.py
895
3.78125
4
#! /usr/bin/env python3 """ utils.py --- Common utilities Opens files, maybe does little math things, whatnot. """ def _read_file(filename): try: return open(filename, "r") except FileNotFoundError: print("The file was not found.") raise def read_input(day, test=False): """ Returns file of input for `day`. The input is assumed to be in `inputs/input<day>.txt`, where <day> is replaced with the number of the day. Note that it's likely that `read_input(<day>).read()` will be called. """ if test: return _read_file("inputs/test_input{}.txt".format(day)) return _read_file("inputs/input{}.txt".format(day)) def input_lines(day, test=False): """ Saves the inputfile from day `day` line-by-line, stripping linebreaks. """ return list(map(lambda x: x.strip(), read_input(day, test=test).readlines()))
cd55c46b76add264e9fce1f1beba3d6bb40e35eb
ksu3101/studyPythonRepo
/testString.py
1,941
3.546875
4
montyPython = "Monty python's Flying Circus" # 문자열의 길이 `len()` print("monty's count = %d" % len(montyPython)) # 문자열에서 특정 문자나 단어의 갯수 세기 `count()` print(montyPython.count('o')) print(montyPython.count('on')) # 문자열에서 특정 문자의 인덱스 얻기 `find()` : 없을 경우 -1 # 가장 처음을 찾게 되는 문자의 인덱스를 얻는다. print(montyPython.find('p')) print(montyPython.find('z')) print(montyPython.find('Circus')) # find() 와 동일 하게 특정 문자의 인덱스를 얻는 `index()` # 다른 점은 찾는 문자가 없을 경우 오류가 발생 된다. print(montyPython.index('p')) #print(montyPython.index('z')) # 오류 발생 # 어떤 문자열의 문자들 사이 마다 주어지는 문자열을 삽입 하는 `join()` joinText = "," print(joinText.join(montyPython)) # M,o,n,t,y, ,p,y,t,h,o,n,',s, ,F,l,y,i,n,g, ,C,i,r,c,u,s # 소문자를 대문자로 바꾸는 `upper()` print(montyPython.upper()) # 대문자를 소문자로 바꾸는 `lower()` upperString = "MONTY PYTHON'S FLYING CIRCUS" print(montyPython.lower()) # 왼쪽 공백을 모두 지우는 `lstrip()` spacestring = " abc d " print(spacestring.lstrip()) # 오른쪽 공백을 모두 지우는 `rstring()` print(spacestring.rstrip()) # 왼쪽과 오른쪽 공백을 지우는 `strip()` print(spacestring.strip()) # 문자열에서 어떤 문자열을 대상 문자열로 치환 하는 `replace()` # 입력한 패러미터에서 첫번째는 치환할 대상 문자열 # 입력한 두번째 패러미터는 치환될 문자열 print(montyPython.replace("on", "9999")) # M9999ty pyth9999's Flying Circus # 문자열을 단어 단위로 나누는 `split()` # 공백을 기준으로 문자열을 나눈다. [] 는 배열이라는 자료 형 으로서 나중에 알아 볼 것 이다. print(montyPython.split()) # ['Monty', "python's", 'Flying', 'Circus']
bfbe7b557f7a484918b1b86e83a441122d959c38
ryanvgates/intro-to-pytest-2019-08-12
/pytests/functions.py
346
3.875
4
def divide_by_two(a): return a / 2 def divide_by(a, b): return a / b def sum_all(list_el): if type(list_el) != list: raise ValueError('It suppose to be a list') if len(list_el) == 0: raise ValueError('The list have to has at least 1 element') acc = 0 for el in list_el: acc += el return acc
68351451b4348d8fca11963685bf3d1cc7c7b96d
linruili/leetcode-python3.5
/49. Group Anagrams.py
407
3.703125
4
import collections def groupAnagrams(strs): """ :type strs: List[str] :rtype: List[List[str]] """ if strs[0] == "": return [[""]] L = [] d = collections.defaultdict(list) for x in strs: d["".join(sorted(x))].append(x) for x in d.values(): x.sort() L.append(x) return L print(groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
9028ab6c8800e84778f67a6c3b86611213c96cc9
RajVjti/CCTech
/testing of buildiing.py
2,608
3.65625
4
buildings= [] temp = [] H=[] W=[] ''' Code to take input starts here Enter input as cordinates comma seprated eg. 3,4 To break the input cordinates enter an integrer value eg. 4,0 4,-5 7,-5 7,0 1 ## to break 1,1 ## Source input ''' def tempLength(temp): if len(temp)== 4: buildings.append(temp.copy()) temp.clear() while True: cordinate = list(map(float, input().strip().split(","))) tempLength(temp) if len(cordinate) < 2: ##To break the input stream when cordinates are entered please enter an integer## break else: W.append(cordinate[0]) H.append(cordinate[1]) temp.append(cordinate) ''' Code to take input ends here''' source = list(map(float, input().strip().split(","))) '''input cordinates are reversed so that smallest building comes firts''' H.reverse() W.reverse() '''To calculate the area exposed to sunlight when only one building is present''' def SurfaceArea(source,H,W,y): if source[1] >= max(H): roof = abs(abs(max(W)) - abs(min(W))) side = abs(abs(max(H)) - abs(y)) return roof+side '''To calculate the slope of line between the source and the max(cordinates) of firts building''' def slope(source, x2, y2): # Here x2 & y2 is the cordinates of first building x1,y1 = source[0], source[1] return ((y2-y1)/(x2-x1)) '''Calculates the y cordinate of the second building intersected by sunray''' def calY(source, x1, y1, x2): # Here x1 & y1 is the cordinate of first building # and x2 is cordinate of next building s = slope(source, x1, y1) return ((s*(x2-x1))+y1) # returns value of y2 '''Calculates the total area exposed to sunlight due to all the buildings by adding surface area of firts building''' def totalSurface(source, H,W): no_building=len(H)//4 previousSum = 0 Htemp = [] Wtemp = [] tempCordinate = [min(W[:4]),min(H[:4])] for i in range(len(H)): Htemp.append(H[i]) Wtemp.append(W[i]) if len(Htemp) == 4: nextCordinate = min(Wtemp) y = calY(source, tempCordinate[0], tempCordinate[1], nextCordinate) previousSum += SurfaceArea(source,Htemp,Wtemp,y) if no_building > 1: tempCordinate = [max(Wtemp),max(Htemp)] Htemp.clear() Wtemp.clear() print(previousSum) totalSurface(source, H,W)
4198427ee8c953a4d1f37dfea509bc666861bf60
chitn/Algorithms-illustrated-by-Python
/example/list.py
956
4.1875
4
# List as an array # One-dimensional a1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] a1.append(10) # Add an element to a list a1.append(3.14) a1.append('hello') b = a1[1:4:1] # Slicing a list to crete another list b = a1[:4] b = a1[1:] print(a1[ 0]) # Print the first element print(a1[-2]) # Print the second last element # Multi-dimensional matrix1 = [1, 2, 3, 4] matrix2 = [2, 3, 4, 1] matrix3 = [3, 4, 1, 2] matrix4 = [4, 1, 2, 3] matrix = [] matrix.append(matrix1) # Create multi-dimensional array matrix.append(matrix2) matrix.append(matrix3) matrix.append(matrix4) print(len(matrix)) print(len(matrix[0])) # Transpose rows and columns by List-comprehension transposed = [[row[i] for row in matrix] for i in range(4)] # which is equal to: transposed = [] for i in range(4): transposed_row = [] for row in matrix: transposed_row.append(row[i]) transposed.append(transposed_row)
a35cdea62cd73afe63a5c6a19792f6fbd7e92ad9
r50206v/Leetcode-Practice
/2022/*Medium-19-RemoveNthNodeFromEndOfList.py
1,568
3.875
4
''' two pass time: O(N) space: O(N) ''' # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: length = head rn = head #We start counting the nodes. nodes = 1 while length.next != None: nodes += 1 length = length.next #Let's say that nodes are 1=> 2=> 3, and n = 3. #We would remove the first node. So we just simply return rn.next, without going for the second iteration. if nodes == n: return rn.next times = nodes - n -1 #Second iteration for i in range(times): head = head.next head.next = head.next.next return rn ''' one pass time: O(N) space: O(N) ''' class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: cur = head nth = None # node to remove nth_prev = None # before node to remove nth_next = head # after node to remove counter = 0 while cur: counter += 1 if counter >= n: nth_prev = nth nth = nth_next nth_next = nth_next.next cur = cur.next if not nth_prev: return nth_next # removing head else: nth_prev.next = nth_next # remove nth return head
07d9070b4a79140c341bc6d8fa150d569d346b52
ze25800000/gaoji_python
/py_file/2-3.py
446
3.578125
4
# 如何统计序列中元素出现频度 from random import randint # 方法1 data = [randint(0, 20) for _ in range(30)] c = dict.fromkeys(data, 0) for x in data: c[x] += 1 print(c) # 方法2 from collections import Counter c2 = Counter(data) # 出现频度最高的元素 print(c2.most_common(3)) # 方法3 import re txt = open('2-2.txt').read() txt = re.split('\W+', txt) c3 = Counter(txt) print(c3) print(c3.most_common(10))
ef8eceb31544e2f93c390e4dfa03b87b2c5c142d
Kim-Ly-L/LPTHW
/EX09/ex9.py
755
3.546875
4
# Here's some new strange stuff, remember type it exactly. days = "Mon Tue Wed Thu Fri Sat Sun" # when it comes to "\n" the kind of the slash does play a role! # even on Windows # "\n" separates the terms/characters within a string into different lines # ...even though there's no spacing - magic! months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug" # 11 & 12: There need to be a space after the ":" # otherwise the days/months would be printed right afterwards without any space # it would look ugly print "Here are the days: ", days print "Here are the months: ", months print """"""""""""""" There's something going on here. With the three double-quotes. We'll be able to type as much as we like. Even 4 lines if we want, or 5, or 6. """""""""""""""
fd671455aae8fae94ce1e0a875e9251e52647d57
isakss/Forritun1_Python
/midterm_list_exercise5.py
948
4.375
4
""" This program allows the user to input as many values into a list as the user dictates and then finds the lowest element from that list. The program ignores values that are not of type int. """ def populate_list(int_object): new_list = [] while len(new_list) != int_object: list_element = input("Enter an element to put into the list: ") try: new_list.append(int(list_element)) except ValueError: pass return new_list def get_min_from_list(list_object): min_value = list_object[0] for element in list_object: if element < min_value: min_value = element return min_value def main_func(): size_num = int(input("Enter the size of the list: ")) value_list = populate_list(size_num) min_list_value = get_min_from_list(value_list) print(value_list) print("The lowest value from the list is {}".format(min_list_value)) main_func()
2dcaef0a9761f3892b7b772a37658e14d9344cb2
summertian4/Practice
/LeetCode/0141.py
504
3.671875
4
# Definition for singly-linked list. class ListNode(object): def __init__(self): self.next = None class Solution(object): def hasCycle(self, head): slowerNode = head fasterNode = head while(slowerNode is not None and fasterNode is not None and fasterNode.next is not None): slowerNode = slowerNode.next fasterNode = fasterNode.next.next if(slowerNode == fasterNode): return True return False
c15281f3f29a5771d62155fbd3f775b79ee6567f
Neha-kumari200/python-Project2
/largestarray.py
275
4.46875
4
#Python program to find largest element in an array def largest(arr, n): max = arr[0] for i in range(1,n): if arr[i]>max: max = arr[i] return max arr = [50, 55, 30, 79, 34] n = len(arr) ans = largest(arr, n) print("Largest element is:",ans)
41955dfe1c01e58e7830c997e3311ee9ee9f0714
shankar7791/MI-10-DevOps
/Personel/Chandrakar/Assessment/09jul/pro03.py
305
3.65625
4
def f(n): b=1 for c in range(1,n+1): b = b*c return b n = int(input("Enter the number : ")) for i in range(0, n): for j in range(1,n-i): print(" ", end="") for k in range(0, i+1): a = int(f(i)/(f(k)*f(i-k))) print(" ", a, end="") print()
a74b465fbb6f86c6b271275799a1981d526a2b76
AHartNtkn/DS-Unit-3-Sprint-1-Software-Engineering
/sprint-challenge/acme_test.py
1,927
3.546875
4
#!/usr/bin/env python import unittest from acme import Product from acme_report import generate_products, ADJECTIVES, NOUNS class AcmeProductTests(unittest.TestCase): """Making sure Acme products are the tops!""" def test_default_product_price(self): """Test default product price being 10.""" prod = Product('Test Product') self.assertEqual(prod.price, 10) def test_default_product_flammability(self): """Test default product flammability being 0.5.""" prod = Product('Test Product') self.assertEqual(prod.flammability, 0.5) def test_stealability(self): """Test high price and low weight => high stealability.""" prod = Product('Test Product', price=100, weight=1) self.assertEqual(prod.stealability(), "Very stealable!") def test_explode(self): """Test highish flamability + mid weight => \"...boom!\" """ prod = Product('Test Product', weight=4, flammability=10) self.assertEqual(prod.explode(), "...boom!") class AcmeReportTests(unittest.TestCase): """Making sure Acme product *reports* are the tops!""" def test_default_num_products(self): """Test that 30 products are generated by default.""" gen_prods = generate_products() self.assertEqual(len(gen_prods), 30) def test_legal_names(self): """Check that all generated names are valid by making sure first part of a name is in ADJECTIVES and second part is in NOUNS.""" gen_prods_split = [p.name.split(" ") for p in generate_products()] should_be_adjs = [n[0] for n in gen_prods_split] should_be_nouns = [n[1] for n in gen_prods_split] for a in should_be_adjs: self.assertIn(a, ADJECTIVES) for n in should_be_nouns: self.assertIn(n, NOUNS) if __name__ == '__main__': unittest.main()
ecb8154c84dd8e1692b23a13998d157fa4011143
pmarcol/Python-excercises
/Python - General/Basic/011-020/excercise016.py
497
3.703125
4
""" Write a Python program to get the difference between a given number and 17, if the number is greater than 17 return double the absolute difference. """ """ SOLUTION: """ import sys from pathlib import Path abspath = Path(__file__) toolspath = abspath.parents[3] sys.path.append(str(toolspath / 'tools')) from GetFromUser import GetInteger def difference17(num): if(num>17): return 2*abs(17-num) else: return 17-num myInt = GetInteger() print(difference17(myInt))
825172e0f36ca657f5f4adb3cc28e52a9575cbe1
Dumacrevano/CSCI318-Task1
/Paper 1-Based ART.py
1,113
3.765625
4
from random import * f = 5 def calculate_min_dist(ci, T): x2 = 0 s_Dist = 100 for y in T: x1 = abs(y - ci) print('Candidate Value:', ci, ', Existing Value:', y, ', Difference:', x1, ', Current Shortest Distance:', s_Dist) if (x1 < s_Dist): s_Dist = x1 x2 = x1 return x2 def ART(T): D = 0 t = 0 k = [randint(1, 100), randint(1, 100), randint(1, 100)] print('\nCandidate Data Points', k) print('Existing Data Points', T) for ci in k: if(len(T) < 1): if(ci > D): D = ci t = ci else: print('\nExecuting Distance Calculation') di = calculate_min_dist(ci, T) print("Shortest Distance:", di) if (di > D): D = di t = ci T.append(t) print('New Data Point: ', t) return T def main(): T = [] while True: data = ART(T) if(data[-1] < f): print("\nIteration(s):", len(data)) print("\nFinal Data Points:", data) break main()
3db5636264f49a68885b815135c28ac54b0c031c
Jayasri001/pandas-python
/pandas python 3.py
2,136
4.46875
4
import pandas as pd import numpy as np #"**22.** You have a DataFrame `df` with a column 'A' of integers. For example:\n", #"How do you filter out rows which contain the same integer as the row immediately above?" df = pd.DataFrame({'A': [1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7]}) print(df) duplicate = df.loc[df.duplicated('A',keep='last'),:] print(duplicate) #how do you subtract the row mean from each element in the row? #"**23.** Given a DataFrame of numeric values, say\n" #df = pd.DataFrame(np.random.random(size=(5, 3))) # a 5x3 frame of float values\n", df2 = pd.DataFrame(np.random.random(size=(5, 3))) print(df2) df3 = df2.mean(axis=1) print(df3) df4=df2.sub(df3,axis=1) print(df4) #"**24.** Suppose you have DataFrame with 10 columns of real numbers, for example:\n #"Which column of numbers has the smallest sum? (Find that column's label.) df5 = pd.DataFrame(np.random.random(size=(5, 10)), columns=list('abcdefghij')) print(df5) df6 = df5.sum().idxmin() print(df6) #"**25.** How do you count how many unique rows a DataFrame has (i.e. ignore all rows that are duplicates)?" df7 = len(df5.drop_duplicates(keep=False)) print(df7) #26 You have a DataFrame that consists of 10 columns of floating--point numbers. Suppose that exactly 5 entries # in each row are NaN values. For each row of the DataFrame, find the *column* which contains the *third* NaN value. # \n", df8 = (df5.isnull().cumsum(axis=1) == 3).idxmax(axis=1) print(df8) #"**27.** A DataFrame has a column of groups 'grps' and and column of numbers 'vals'. For example: \n", df9 = pd.DataFrame({'grps': list('aaabbcaabcccbbc'), 'vals': [12,345,3,1,45,14,4,52,54,23,235,21,57,3,87]}) print(df9.groupby('grps')['vals'].nlargest(3).sum(level=0)) # "**28.** A DataFrame has two integer columns 'A' and 'B'. The values in 'A' are between 1 and 100 (inclusive). # For each group of 10 consecutive integers in 'A' (i.e. `(0, 10]`, `(10, 20]`, ...), # calculate the sum of the corresponding values in column 'B'." df11 = df.groupby(pd.cut(df['A'], np.arange(0, 101, 10)))['B'].sum() print(df11)
29cfba7df070db8899931b191d9b187b1b53ee7a
bohdanpuzii/Test_task
/task2/main.py
605
3.734375
4
def get_dictionary_by_value(value): result = {'$$@@': value % 3 == 0 and value % 5 == 0, '$$': value % 3 == 0, '@@': value % 5 == 0} return result def get_first_true_key(dictionary): keys = dictionary.keys() for key in keys: if dictionary[key]: return key def print_results_in_range(start, end): for value in range(start, end + 1): dictionary = get_dictionary_by_value(value) first_key = get_first_true_key(dictionary) print(first_key or value) if __name__ == '__main__': print_results_in_range(11, 79)
d41d1fa214dd3488b97f1f6ad7f10a45fd39d3a9
sanjeevseera/Python-Practice
/Basic_Programs/Part1/P022_countInList.py
253
4.03125
4
""" Write a Python program to count the number 4 in a given list """ numbers=input("enter the numbers with comma seperated:\n").split(",") count=0 for i in numbers: if int(i) == 4: count+=1 print("number of 4s in list: %i"%count)
694ac91eec52f84fdac4581f1cd3be42554925d4
CertifiedErickBaps/Python36
/Listas/Practica 7/positives.py
1,028
4.125
4
# Authors: # A013979896 Erick Bautista Perez # #Write a program called positives.py. Define in this program a function called #positives(x) that takes a list of numbers x as its argument, and returns a new #list that only contains the positive numbers of x. # # October 28, 2016. def positives(x): a = [] for c in x: if c >= 0: a += [c] return a def main(): print(positives([-21, -31])) print(positives([-48, -2, 0, -47, 45])) print(positives([-9, -38, 49, -49, 32, 6, 4, 26, -8, 45])) print(positives([-27, 48, 13, 5, 27, 5, -48, -42, -35, 49, -41, -24, 11, 29, 33, -8, 45, -44, 12, 46])) print(positives([-2, 0, 27, 47, -13, -23, 8, -28, 23, 7, -29, -24, -30, -6, -21, -17, -35, -8, -30, -7, -48, -18, -2, 1, -1, 18, 35, -32, -42, -5, 46, 8, 0, -31, -23, -47, -4, 37, -5, -45, -17, -5, -29, -35, -2, 40, 9, 25, -11, -32])) main()
7c1eb2b2c0a60ccdd82c9112705dfb9d3eb784e5
dxrogel/ANN-1
/venv/punto.py
1,202
3.515625
4
import numpy as np softmax_output = [0.7, 0.1, 0.2] softmax_output = np.array(softmax_output).reshape(-1, 1) print(softmax_output) print(np.diagflat(softmax_output)) print(np.dot(softmax_output, softmax_output.T)) # Validate the model # Create test dataset X_test, y_test = spiral_data(samples=100, classes=3) # Perform a forward pass of our testing data through this layer dense1.forward(X_test) # Perform a forward pass through the activation/loss function # takes the output of first dense layer here activation1.forward(dense1.output) # Perform a forward pass through second Dense layer # takes outputs of activation function of first layer as inputs dense2.forward(activation1.output) # Perform a forward pass through the activation/loss function # takes the output os second dense layer here and returns loss loss = loss_activation.forward(dense2.output, y_test) # Calculate accuracy from output of activation2 and targets # calculate values along first axis predictions = np.argmax(loss_activation.output, axis=1) if len(y_test.shape) == 2: y_test = np.argmax(y_test, axis=1) accuracy = np.mean(predictions == y_test) print(f'validation, acc: {accuracy:.3f}, loss: {loss:.3f}')
468bab6d59be58a54098da68986f43984c2b25d2
jessjoschwartz/Exercise09
/markov.py
972
3.734375
4
#!/usr/bin/env python from sys import argv script, filename = argv def make_chains(corpus): """Takes an input text as a string and returns a dictionary of markov chains.""" input_text = corpus.read() words = input_text.split() chain_dict = {} for i in range(len(words) -2): tuple_words = (words[i], words[i+1]) chain_dict[tuple_words] = words[i+2] # print chain_dict return chain_dict def make_text(chains): """Takes a dictionary of markov chains and returns random text based off an original text.""" original_text = "everyone cuddles" return "Here's some random text." def main(): # args = sys.argv # my_file = argv[1] input_text = open(filename) # Change this to read input_text from a file # input_text = "Some text" chain_dict = make_chains(input_text) random_text = make_text(chain_dict) # print random_text if __name__ == "__main__": main()
fb5f236e31ac0efdc9fca7423171a2b52c05ea8c
gvashishtha/cs182_gjk
/example.py
848
3.703125
4
import midi from note import Note def compile_notes(notes_list): """ Takes in a list of Note objects and returns a playable midi track example use of midi library defined here: https://github.com/vishnubob/python-midi Follow installation instructions from Github readme to use. """ pattern = midi.Pattern() track = midi.Track() pattern.append(track) for note in notes_list: on = midi.NoteOnEvent(tick=0, velocity=70, pitch=note.getPitch()) track.append(on) off = midi.NoteOffEvent(tick=100, pitch=note.getPitch()) track.append(off) eot = midi.EndOfTrackEvent(tick=1) track.append(eot) midi.write_midifile("example.mid", pattern) note_list = [midi.G_3, midi.A_3, midi.B_3] note_list = map(lambda x: Note(x), note_list) print(note_list) compile_notes(note_list)
fe2c2c3b0cbe134f86c9d23c2bfedd88e2b3babd
AlexKVal/leetcode
/remove_duplicates_sorted_array/rm_dups.py
3,942
3.796875
4
from typing import List def removeDuplicates(nums: List[int]) -> int: if len(nums) == 0: return 0 curr_index = 0 for next_index in range(1, len(nums)): if nums[curr_index] != nums[next_index]: curr_index += 1 nums[curr_index] = nums[next_index] return curr_index + 1 # nums = [] # nums = [1] # nums = [1,1,3] nums = [0,0,1,1,1,2,2,3,3,4] print( removeDuplicates(nums), nums ) # submitted 1 # def removeDuplicates(nums: List[int]) -> int: # if len(nums) == 0: # return 0 # curr_num = nums[0] # next_index = replace_position = 1 # while next_index < len(nums): # next_num = nums[next_index] # if curr_num != next_num: # if replace_position != next_index: # nums[replace_position] = next_num # replace_position += 1 # curr_num = next_num # next_index += 1 # return replace_position # new length # working 'while' 2 with debug # curr_num = nums[0] # next_index = replace_position = 1 # while next_index < len(nums): # next_num = nums[next_index] # print(f"curr:{curr_num} next:{next_num} next_idx:{next_index} repl_pos:{replace_position}") # if curr_num != next_num: # print("curr != next") # if replace_position != next_index: # print("repl_pos != next_index") # nums[replace_position] = next_num # replace_position += 1 # curr_num = next_num # print(f"end:{nums}") # next_index += 1 # return replace_position # new length # working 'for' with debug # if len(nums) <= 1: # edge cases # return len(nums) # for next_index, next_num in enumerate(nums): # if next_index == 0: # print("skip 0") # continue # skip next_index = 0 # print(f"curr:{curr_num} next:{next_num} next_idx:{next_index} repl_pos:{replace_position}") # if curr_num != next_num: # print("curr != next") # if replace_position != next_index: # print("repl_pos != next_index") # nums[replace_position] = next_num # replace_position += 1 # curr_num = next_num # if next_index == last_index: # print("next_index == last_index; break") # break # print(f"end:{nums}") # return replace_position # new length # before_last_index = len(nums)-2 # for index, num in enumerate(nums): # if index == 0: # continue # if nums[index-1] == num: # indexes_to_remove.append(index) # last_index = len(nums) - 1 # curr_num = nums[0] # replace_position = 1 # next_index = 0 # || # [1,2,3,3,3,4] # != # 1 2 # next_index += 1 # next_num = nums[next_index] # if curr_num != next_num: # if replace_position != next_index: # nums[replace_position] = next_num # replace_position += 1 # curr_num = next_num # if next_index == last_index: # return replace_position + 1 # new length # || # [1,2,3,3,3,4] # != # 2 3 # || # [1,2,3,3,3,4] # == # 3 3 # | | # [1,2,3,3,3,4] # == # 3 3 # | | # [1,2,3,3,3,4] # != # 3 4 # # ======================== # replace_position = 1 # curr_num = 1 # || # [1,1,2,3,3,3,4] # next_num = 1 # == # if next_index == last_index: # return # else: # next_index += 1 # | | # [1,1,2,3,3,3,4] # curr_num = 1 # next_num = 2 # != # curr_num = nums[replace_position] = next_num # if next_index == last_index: # return # else: # replace_position += 1 # next_index += 1 # | | # [1,2,2,3,3,3,4] # curr_num = 2 # next_num = 3 # != # curr_num = nums[replace_position] = next_num # replace_position += 1 # next_index += 1 # | | # [1,2,3,3,3,3,4] # curr_num = 3 # next_num = 3 # == # if next_index == last_index: # return # else: # next_index += 1 # | | # [1,2,3,3,3,3,4] # curr_num = 3 # next_num = 3 # == # next_index += 1 # | | # [1,2,3,3,3,3,4] # curr_num = 3 # next_num = 4 # != # curr_num = nums[replace_position] = next_num # if next_index == last_index: # return replace_position + 1 # [1,2,3,4,3,3,4]
dfe038db09dd6b641500efa532cac99ff4b5a098
budytanico/examen-final
/python/repaso4.py
325
4.0625
4
print("COMPARADOR DE NÚMEROS") numero1 = int(input("Escriba un número: ")) numero2 = int(input("Escriba otro número: ")) if numero1 > numero2: print('El mayor es el primero: ' + str(numero1)) elif numero1 < numero2: print('El mayor es el segundo: ' + str(numero2)) else: print("Los dos números son iguales")
0a18aee3eb6f4e6156e675cd71cd081e7b45119b
danwwww/AI-Expendibot
/partB-3/your_team_name_3/player.py
6,310
3.625
4
import sys import json from math import inf from your_team_name_3.search import * import random class ExamplePlayer: def __init__(self, colour): """ This method is called once at the beginning of the game to initialise your player. You should use this opportunity to set up your own internal representation of the game state, and any other information about the game state you would like to maintain for the duration of the game. The parameter colour will be a string representing the player your program will play as (White or Black). The value will be one of the strings "white" or "black" correspondingly. """ # TODO: Set up state representation. # load and analyse input stacks = {(0, 0): 1, (1, 0): 1, (0, 1): 1, (1, 1): 1, (3, 0): 1, (4, 0): 1, (3, 1): 1, (4, 1): 1, (6, 0): 1, (7, 0): 1, (6, 1): 1, (7, 1): 1} targets = {(4, 7): 1, (6, 7): 1, (4, 6): 1, (6, 6): 1, (7, 6): 1, (7, 7): 1, (0, 7): 1, (0, 6): 1, (1, 6): 1, (3, 6): 1, (1, 7): 1, (3, 7): 1} target_groups = find_explosion_groups(targets.keys()) # search for an action sequence self.colour = colour self.state = State(stacks, target_groups, targets) if colour == "black": self.state = self.state.reverse() print(self.state.heuristic()) def scode3(self, state): N = sum(state.stacks.values()) # token number G = len(state.reverse().groups) # group number D = 0 if N > 2: for s1 in state.stacks.keys(): S = inf for s2 in state.stacks.keys(): if s1 != s2: S = min(S, min(pow(manhattan_distance(s1, s2) + 2, 2), 25) ) D = D + S D = D / N # average distance return N,G,D,N * 100 + G * 10 + D def score(self, state): # higher the better # state.print((self.scode3(state),self.scode3(state.reverse()))) #state.print((state.heuristic(), state.reverse().heuristic(), len(state.reverse().groups), sum(state.targets.values()))) return self.scode3(state)[3] - self.scode3(state.reverse())[3] # len(state.reverse().groups) - sum(state.targets.values()) #return sum(state.stacks.values()) - sum(state.targets.values()) #return -state.heuristic() - (-state.reverse().heuristic()) def print_auction(self,action): if isinstance(action, Move): return ("MOVE", action.n, action.a, action.b) else: return ("BOOM", action.square) def terminal_state(self, state): return state.is_goal() def action(self): """ This method is called at the beginning of each of your turns to request a choice of action from your program. Based on the current state of the game, your player should select and return an allowed action to play on this turn. The action must be represented based on the spec's instructions for representing actions. """ # TODO: Decide what action to take, and return it # "MOVE" n, a, b def minimax(self, node, depth, maximizingPlayer): if depth == 0 or self.terminal_state(node): return (None, self.score(node) * (1 if maximizingPlayer else -1)) if maximizingPlayer: value = -10000 final_action = None for (action, successor_state) in node.actions_successors(): successor_state = successor_state.reverse() _, new_value = self.minimax(successor_state, depth - 1, False) #print(str(self.print_auction(action)) + "|" + str(new_value) + "|" + str(self.colour)) if new_value > value or (random.randint(0, 1) == 0 and new_value == value): value = new_value final_action = action return (final_action, value) else: value = 10000 final_action = None for (action, successor_state) in node.actions_successors(): successor_state = successor_state.reverse() _, new_value = self.minimax(successor_state, depth - 1, True) if new_value < value or (random.randint(0, 1) == 0 and new_value == value): value = new_value final_action = action return (final_action, value) action, score = self.minimax(self.state, 1, True) if isinstance(action, Move): return ("MOVE", action.n, action.a, action.b) else: return ("BOOM", action.square) def update(self, colour, action): """ This method is called at the end of every turn (including your player’s turns) to inform your player about the most recent action. You should use this opportunity to maintain your internal representation of the game state and any other information about the game you are storing. The parameter colour will be a string representing the player whose turn it is (White or Black). The value will be one of the strings "white" or "black" correspondingly. The parameter action is a representation of the most recent action conforming to the spec's instructions for representing actions. You may assume that action will always correspond to an allowed action for the player colour (your method does not need to validate the action against the game rules). """ # TODO: Update state representation in response to action. # print("-"*30) atype, *aargs = action if atype == "MOVE": n, a, b = aargs next_aution = Move(n, a, b) else: start_square, = aargs next_aution = Boom(start_square) if colour == self.colour: self.state = next_aution.apply_to(self.state) else: self.state = self.state.reverse() self.state = next_aution.apply_to(self.state) self.state = self.state.reverse()
e71e12c3b688ee73489c3540458cffeffc30c5c9
jcebo/pp1
/04-Subroutines/27.py
381
3.609375
4
tekst='Nam strzelać nie kazano. Wstąpiłem na działo. I spojrzałem na pole, dwieście armat grzmiało. Artyleryji ruskiej ciągną się szeregi, Prosto, długo, daleko, jako morza brzegi.' def ile(a,tekst): i=0 for n in tekst.lower(): if n==a: i+=1 return i a=input('Podaj samogloske: ') print(f'Samogloska wystepuje {ile(a,tekst)} razy w tekscie')
cd8abdba0ea98a0bd2f9f8244662e25378ebfc96
ayesha-syed/datasturctures-BloomFilter
/Bloom Filter/Project/document.py
2,716
3.84375
4
from dataclasses import dataclass import pathlib @dataclass class Location: """The location of a word in a document.""" doc_id: str start: int stop: int class Document: """A document in a corpus. It allows to access the contained words with stop words and punctuation filterd out.""" def __init__(self, path: str): """Creates the document. Args: - self: this document, the one to create. - path: path in the file system to the file which contains the document. Returns: None. """ # Extract ID from path. path = pathlib.Path(path) self.doc_id = path.stem # Tokenize the content, replacing Unicode characters with '?' content = path.read_text(encoding='UTF-8', errors='replace') # content = path.read_text(errors='replace') self._words = document_tokenize(content) def words(self) -> [(str, [Location])]: """Returns words along with their locations in the document. Args: - self: words of this document are sought, mandatory object reference. Returns: list of pairs where each pair contains a unique word in the document and the locations where it appears. """ words = [] for word, locs in self._words.items(): locs = [Location(self.doc_id, start, stop) for start, stop in locs] words.append(word) return words # ------------------------- Helpers ------------------------- def document_tokenize(content: str) -> {str: [(int, int)]}: """Returns tokens from content in the form of words and the (start, stop) indexes in content. content is usually the entire content of a document but can also be any arbitrary string. (start, stop) indexes follow python slicing convention. Args: - content: the string to tokenize Returns: A dictionary in which each key is a unique token from content and the value is a list of (start, stop) indexes in content where the word appears. """ # Extract ID from path and read the content. i = 0 words = dict() while content[i:]: # Ignore non-letters if not content[i].isalpha(): i += 1 continue # A word stops at a space. start = i stop = content.find(' ', i) if stop == -1: stop = len(content) word = content[start:stop] # Save index bounds of word, proceed with the remaining content. words[word] = words.get(word, []) + [(start, stop)] i = stop + 1 return words
7788c5b7a3aaa79bfb14e0563e7f52a49228cbba
hyperlolo/Blackjack_Python
/main.py
3,122
4.0625
4
###########Blackjack project by Karanjit Gill########### ###########Requirements for game########### ## Cards are removed from the deck as drawn ## Cards have the same probability of being drawn from deck ## The deck is unlimited in size. ## There are no jokers. ## The Jack/Queen/King all count as 10. ## The the Ace can count as 11 or 1. import random from art import logo """Returns a random number of cards""" def deal_card(): cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] card = random.choice(cards) return card """Calculates the users score""" def calculate_score(cards): """Checks for immediate Blackjack""" if sum(cards) == 21 and len(cards) == 2: return 0 """Checks if having an 11 puts the player above 21, if it does, then their Ace is changed to a 1""" if 11 in cards and sum(cards) > 21: cards.remove(11) cards.append(1) return sum(cards) def compare(user_score, computer_score): """Checks if both user and computer are over, if so then game over""" if user_score > 21 and computer_score > 21: return "You went over. You lose" """Checks for Win, Draw, or lose""" if user_score == computer_score: return "Draw" elif computer_score == 0: return "Lose, opponent has Blackjack" elif user_score == 0: return "Win with a Blackjack" elif user_score > 21: return "You went over. You lose" elif computer_score > 21: return "Opponent went over. You win" elif user_score > computer_score: return "You win" else: return "You lose" """Starts Game""" def play_game(): print(logo) """Initializes game and calls deal function""" user_cards = [] computer_cards = [] is_game_over = False for _ in range(2): user_cards.append(deal_card()) computer_cards.append(deal_card()) """Continues game and checks for Blackjack and if the user wants more cards""" while not is_game_over: user_score = calculate_score(user_cards) computer_score = calculate_score(computer_cards) print(f" Your cards: {user_cards}, current score: {user_score}") print(f" Computer's first card: {computer_cards[0]}") if user_score == 0 or computer_score == 0 or user_score > 21: is_game_over = True else: user_should_deal = input("Type 'y' to get another card, type 'n' to pass: ") if user_should_deal == "y": user_cards.append(deal_card()) else: is_game_over = True """Once the user is done, it is the computers turn to play""" while computer_score != 0 and computer_score < 17: computer_cards.append(deal_card()) computer_score = calculate_score(computer_cards) print(f" Your final hand: {user_cards}, final score: {user_score}") print(f" Computer's final hand: {computer_cards}, final score: {computer_score}") print(compare(user_score, computer_score)) while input("Do you want to play a game of Blackjack? Type 'y' or 'n': ") == "y": play_game()
c6f8dd8c214583f943099efdbae480bb71e4d76a
borisachen/leetcode
/134. Gas Station.py
1,304
3.953125
4
134. Gas Station There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. Return the starting gas stations index if you can travel around the circuit once, otherwise return -1. Note: The solution is guaranteed to be unique. 1. naive, try starting each i. at each step, fill the tank, see if you can get back to the ith station. 2. observations if total gas > cost, there must be a solution if car starts at A and cannot reach B, nothing between A and B can reach B iterate through the stations, keep track of start, running tank, and total shortage so far (total = negative number) at each step, update the tank, if tank is negaitve, means we cant get here so move the start index up add the deficit up to total reset tank to 0 class Solution(object): def canCompleteCircuit(self, gas, cost): """ :type gas: List[int] :type cost: List[int] :rtype: int """ start = total = tank = 0 for i in range(len(gas)): tank += gas[i] - cost[i] if tank < 0: start = i + 1 total += tank tank = 0 return -1 if total + tank < 0 else start
571b993c2f787223f687b668d9725b72ad94c136
Mandarpowar13/basics-of-python
/while loop.py
69
3.765625
4
i = 2 while i <= 20: print(i) i += 2 print("done with loop")
bdb1901f4414123ac96cb8a085e39dc1a9033a76
manu-j3400/The-Simple-Math-Game-SMG-
/main.py
1,153
3.6875
4
import time, os, mathOperations import mathIntroAnimation Red = "\033[0;31m" Green = "\033[0;32m" White = "\033[0;37m" red = "\033[0;91m" green = "\033[0;92m" yellow = "\033[0;93m" blue = "\033[0;94m" magenta = "\033[0;95m" cyan = "\033[0;96m" white = "\033[0;97m" blue_back = "\033[0;44m" orange_back = "\033[0;43m" red_back = "\033[0;41m" grey_back = "\033[0;40m" off = "\003[0;0m" def clear(): os.system('clear') #Intro def introAndStart(): option = input(red_back + "[SELECT YOUR DIFFICULT: EASY, MEDIUM, HARD, EXTREME]\n" + white) print(red + "_____________________________________\n") if option == "EASY": #CODE elif option == "MEDIUM": #CODE elif option == "HARD": #CODE elif option == "EXTREME": #CODE def countdown(): print("5...") time.sleep(1) print("4...") time.sleep(1) print("3...") time.sleep(1) print("2...") time.sleep(1) print("1...") print("______________________________\n") clear() if __name__ == "__main__": mathIntroAnimation.introAnimation() introAndStart() countdown() mathOperations.mathFunctions()
75ed893b4fc9d8fbdbb35bab7ecb6bbbc23fe8da
calebballw/old_code
/quizlet.py
331
3.84375
4
def quizlet(question, answer): question = str(question) answer = str(answer) user = input(question) if user == answer: print ("Good Job") else: print ("Wrong answer") while 1 == 1: quizlet(input("Type in a question: "), input("Type the answer to that question: ")) continue
d6fdc22875fd3b2bdad71c5980fe08592d63244c
caryt/utensils
/null/tests.py
2,005
3.796875
4
"""Test Null ============ """ from unittest import TestCase from null import Null class TestNull(TestCase): """Test the :class:`.Null` object. """ def assertNull(self, obj): return self.assertIs(obj, Null) def test_Null(self): """Test Null object.""" self.assertNull(Null) self.assertNull(Null()) self.assertNull(Null.foo) self.assertNull(Null(foo='foo', bar='bar')) self.assertNull(Null.foo(bar='bar')) self.assertNull(Null + 1) self.assertNull(Null - 1) self.assertNull(Null * 2) self.assertNull(Null / 2) self.assertNull(Null / 2) self.assertNull(Null // 2) self.assertNull(Null & 2) self.assertNull(Null | 2) self.assertNull(Null ^ 2) self.assertNull(Null >> 2) self.assertNull(Null << 2) self.assertNull(Null['foo']) self.assertNull(Null ** 2) self.assertNull(-Null) self.assertNull(+Null) self.assertNull(abs(Null)) self.assertNull(~Null) def test_Equal(self): """Test Null object.""" self.assertEqual(repr(Null), 'Null') self.assertEqual(str(Null), 'Null') self.assertEqual(Null.format('spec'), Null) self.assertEqual(Null.__html__(), 'Null') self.assertEqual(unicode(Null), u'Null') self.assertEqual([x for x in Null], []) self.assertEqual(len(Null), 0) self.assertEqual(float(Null), 0.0) self.assertEqual(Null, Null) def test_False(self): """Test Null object.""" self.assertFalse(Null < 0) self.assertFalse(Null == 0) self.assertFalse(Null == False) self.assertFalse(Null == None) self.assertFalse(Null == None) self.assertFalse(Null == []) self.assertFalse(Null == {}) def test_True(self): """Test Null object.""" self.assertTrue(Null == Null) self.assertTrue(Null is Null)
13550b0324c7fbfa53694e0b14ec0c615818183f
yangzongwu/leetcode
/archives/leetcode2/0445. Add Two Numbers II.py
614
3.734375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ a=0 while l1: a=a*10+l1.val l1=l1.next b=0 while l2: b=b*10+l2.val l2=l2.next rep=str(a+b) node=ListNode(0) p=node for s in rep: p.next=ListNode(int(s)) p=p.next return node.next
ea6257664593a399b533965118bda14162a6025f
Valeriy73/Douson
/douson_gl6_3.py
1,496
4.125
4
# Доступ отовсюду # Демонстрирует работу с глобальными переменными def read_global(): print("В области видимости функции read_global значение value равно", value) def shadow_global(): value = -10 print("В области видимости функции shadow_global значение value равно", value) def change_global(): global value value = -10 print("В области видимости функции change_global значение value равно", value) # основная часть # value - глобальная пекременная, потому что сейчас мы находимся в глобальной обла- # сти видимости value = 10 print("В глобальной области видимости значение переменной value сейчас стало равным", value,"\n") read_global() print("Вернемся в глобальную область видимости. Здесь value по-прежнему равно", value, "\n") shadow_global() print("Вернемся в глобальную область видимости. Здесь value по-прежнему равно", value, "\n") change_global() print("Вернемся в глобальную область видимости. Значение value изменилось на", value, "\n") input("\n\nНажмите Enter, чтобы выйти.")
3460deb0c5618d2e6dc9ce992117e25e6375d52c
PanMaster13/Python-Programming
/Week 4/Practice Files/Week 4, Practice 6.py
1,841
4.09375
4
x = int(input("Input birthday:")) y = input("Input month of birth (e.g. March, July etc):") if (y == "January" and (x >= 20 and x <= 31)) or (y == "February" and (x >= 1 and x <= 18)): print("Your Astrological sign is : Aquarius") elif (y == "February" and (x >= 19 and x <= 29)) or (y == "March" and (x >= 1 and x <= 20)): print("Your Astrological sign is : Pices") elif (y == "March" and (x >= 21 and x <= 31)) or (y == "April" and (x >= 1 and x <= 19)): print("Your Astrological sign is : Aries") elif (y == "April" and (x >= 20 and x <= 30)) or (y == "May" and (x >= 1 and x <= 20)): print("Your Astrological sign is : Taurus") elif (y == "May" and (x >= 21 and x <= 31)) or (y == "June" and (x >= 1 and x <= 20)): print("Your Astrological sign is : Gemini") elif (y == "June" and (x >= 21 and x <= 30)) or (y == "July" and (x >= 1 and x <= 22)): print("Your Astrological sign is : Cancer") elif (y == "July" and (x >= 23 and x <= 31)) or (y == "August" and (x >= 1 and x <= 22)): print("Your Astrological sign is : Leo") elif (y == "August" and (x >= 23 and x <= 31)) or (y == "September" and (x >= 1 and x <= 22)): print("Your Astrological sign is : Vigro") elif (y == "September" and (x >= 23 and x <= 30)) or (y == "October" and (x >= 1 and x <= 22)): print("Your Astrological sign is : Libra") elif (y == "October" and (x >= 23 and x <= 31)) or (y == "November" and (x >= 1 and x <= 21)): print("Your Astrological sign is : Scorpio") elif (y == "November" and (x >= 22 and x <= 30)) or (y == "Decenber" and (x >= 1 and x <= 21)): print("Your Astrological sign is : Sagittarius") elif (y == "December" and (x >= 22 and x <= 31)) or (y == "January" and (x >= 1 and x <= 19)): print("Your Astrological sign is : Capricorn") else: print("Incorrect day or name of month")
2191caf07fefebe7287a4ce1493598374fdc8fcb
frankskol/programmingChallenges
/ButtonClicker.py
678
3.53125
4
from tkinter import * class Application(Frame): """A GUI application for Fahrenheit and Celsius Conversion""" def __init__(self, master): #Initializes Frame Frame.__init__(self, master) self.grid() self.button_clicks = 0 self.create_widgets() def create_widgets(self): #Creates the buttons self.button = Button (self) self.button ["text"] = "Total clicks: 0" self.button["command"] = self.update_count self.button.grid() def update_count(self): self.button_clicks += 1 self.button["text"] = "Total Clicks: " + str(self.button_clicks) root = Tk() root.title("Button Click Counter") root.geometry ("300x150") app = Application(root) root.mainloop()
c577291a8c8658def33fbefef826d95262c811cb
avivalipkowitz/OOP_lesson
/game.py
11,950
3.5625
4
import core import pyglet from pyglet.window import key from core import GameElement import sys username = raw_input("To choose a player type 'Aviva' or 'Katie': ") if username == "Aviva": princess = "Katie" else: princess = "Aviva" in_game = True users_message = [] #### DO NOT TOUCH #### GAME_BOARD = None DEBUG = False KEYBOARD = None PLAYER = None ###################### GAME_WIDTH = 15 GAME_HEIGHT = 10 #### Put class definitions here #### class Rock(GameElement): IMAGE = "Rock" SOLID = True RETURN = False class TallTree(GameElement): IMAGE = "TallTree" SOLID = True RETURN = False class Wall(GameElement): IMAGE = "Wall" SOLID = True RETURN = False class Campanile(GameElement): IMAGE = "Campanile" SOLID = True RETURN = False class StanfordTree(GameElement): IMAGE = "StanfordTree" SOLID = True RETURN = True def interact(self, player): GAME_BOARD.draw_msg("You touched the Stanford Tree! So you're stuck in prison until eternity...") next_x = 2 next_y = 2 class Water(GameElement): IMAGE = "Water" SOLID = True RETURN = False class Key(GameElement): IMAGE = "Key" SOLID = False RETURN = False def interact(self, player): player.inventory["gold_key"] = self GAME_BOARD.draw_msg("You just acquired a key! You have %d item(s)!" %(len(player.inventory))) print player.inventory class Door(GameElement): IMAGE = "DoorClosed" SOLID = True RETURN = False def interact(self, player): if "gold_key" in player.inventory: GAME_BOARD.del_el(door_closed.x, door_closed.y) GAME_BOARD.draw_msg("You've reached the Campanile, go rescue Princess %s!" % PRINCESS.IMAGE) else: GAME_BOARD.draw_msg("You need a key to get into the Campanile. Maybe someone *cough Yoshua cough* has it. (Hint: The world always ends in two days.)") class Character(GameElement): IMAGE = None SOLID = True def __init__(self): GameElement.__init__(self) self.inventory = {} def next_pos(self, direction): if direction == "up": return (self.x, self.y-1) elif direction == "down": return (self.x, self.y+1) elif direction == "left": return (self.x-1, self.y) elif direction == "right": return (self.x+1, self.y) return None def speak(self): GAME_BOARD.draw_msg("I am a character!") class Player(Character): def __init__(self, image): GameElement.__init__(self) self.inventory = {} self.IMAGE = image class Princess(Character): IMAGE = princess RETURN = False SOLID = True def interact(self, player): GAME_BOARD.draw_msg("Thank you for rescuing me %s! You win!!" % PLAYER.IMAGE) def __init__(self, image): GameElement.__init__(self) self.inventory = {} self.IMAGE = image class Yoshua(Character): IMAGE = "Yoshua" SOLID = True RETURN = False DEFEATED = False def interact(self, player): global users_message GAME_BOARD.draw_msg("'God's going to burn up this universe, sun, moon, and stars, and fold it up and burn it up.' You've just met Yoshua! Answer his riddle to move past him. 'How many days until the end of the world?'") if users_message == ['2']: global yoshua GAME_BOARD.del_el(yoshua.x, yoshua.y) gold_key = Key() GAME_BOARD.register(gold_key) GAME_BOARD.set_el(4, 3, gold_key) # GAME_BOARD.set_el(3, 3, yoshua2) GAME_BOARD.draw_msg("You got the answer! Here's a key to the Campanile. See you in Heaven!") # if yoshua2.DEFEATED: # GAME_BOARD.draw_msg("You already took my key. Go away. 2 days.") # else: # GAME_BOARD.draw_msg("'It's going to happen, it's going to happen, it happened on May 21, five months ago' Hm. That didn't work. Guess again.") class Happy(Character): IMAGE = "Happy" SOLID = True RETURN = False def interact(self, player): global users_message GAME_BOARD.draw_msg("'Happy, happy, happy!' You've just met the Happy Happy Happy Man! Answer his riddle to move past him. 'Why did the chicken cross the road?' ") if users_message == ['h','a','p','p','y']: GAME_BOARD.del_el(happy.x, happy.y) happy2 = Happy() GAME_BOARD.register(happy2) GAME_BOARD.set_el(2, 6, happy2) GAME_BOARD.draw_msg("You got the answer! Come on through!") class Oski(Character): IMAGE = "Oski" SOLID = True RETURN = False def interact(self, player): global users_message GAME_BOARD.draw_msg("*Silence* You've just met Oski! How will you get by? (a) Beat him in a staring contest (b) Distract him with candy (c) Give him a big bear hug") if users_message == ['a']: GAME_BOARD.draw_msg("Silly %s...you can't defeat Oski in a staring contest - he has no eyelids!!" % PLAYER.IMAGE) if users_message == ['b']: GAME_BOARD.draw_msg("Oh %s...Oski only eats organic, free-range, non-GMO candy. Try again." % PLAYER.IMAGE) if users_message == ['c']: GAME_BOARD.del_el(oski.x, oski.y) oski2 = Oski() GAME_BOARD.register(oski2) GAME_BOARD.set_el(11, 0, oski2) GAME_BOARD.draw_msg("Woohoo! Oski steps aside!") #### End class definitions #### def in_game_keyboard_handler(): direction = None if KEYBOARD[key.UP] and PLAYER.y != 0: direction = "up" if KEYBOARD[key.DOWN] and PLAYER.y != 9: direction = "down" if KEYBOARD[key.LEFT] and PLAYER.x != 0: direction = "left" if KEYBOARD[key.RIGHT] and PLAYER.x != 14: direction = "right" for keypress in range(48,58): if KEYBOARD[keypress]: global users_message users_message += [chr(keypress)] GAME_BOARD.draw_msg(''.join(users_message)) for keypress in range(97,123): if KEYBOARD[keypress]: global users_message users_message += [chr(keypress)] GAME_BOARD.draw_msg(''.join(users_message)) if KEYBOARD[key.BACKSPACE]: if len(users_message) >= 1: users_message.pop() GAME_BOARD.draw_msg(''.join(users_message)) if direction: next_location = PLAYER.next_pos(direction) next_x = next_location[0] next_y = next_location[1] # Check to see if there is an element already at those coordinates existing_el = GAME_BOARD.get_el(next_x, next_y) if existing_el: existing_el.interact(PLAYER) if existing_el is not None and existing_el.RETURN: GAME_BOARD.del_el(PLAYER.x, PLAYER.y) GAME_BOARD.set_el(2, 2, PLAYER) elif existing_el is None or not existing_el.SOLID: # If there's nothing there _or_ if the existing element is not solid, walk through GAME_BOARD.del_el(PLAYER.x, PLAYER.y) GAME_BOARD.set_el(next_x, next_y, PLAYER) def initialize(): """Put game initialization code here""" GAME_BOARD.draw_msg("%s is trapped in the Campanile. Defeat all the Berkeley characters to get the key to free %s!!!" % (princess, princess)) print in_game in_game_keyboard_handler() # Initialize water water_positions = [ (12,0), (12,2), (13,2), (14,2) ] for pos in water_positions: water = Water() GAME_BOARD.register(water) GAME_BOARD.set_el(pos[0],pos[1],water) # Initialize tall trees talltree_positions = [ (8,8), (11,4), (10,6), (12,8) ] for pos in talltree_positions: talltree = TallTree() GAME_BOARD.register(talltree) GAME_BOARD.set_el(pos[0],pos[1],talltree) # Initialize walls wall_positions = [ (0,5), (1,6), (3,8), (4,9) ] for pos in wall_positions: wall = Wall() GAME_BOARD.register(wall) GAME_BOARD.set_el(pos[0],pos[1],wall) # Initialize rocks rock_positions = [ (2,1), (1,2), (3,2), (2,3) ] for pos in rock_positions: rock = Rock() GAME_BOARD.register(rock) GAME_BOARD.set_el(pos[0],pos[1],rock) # Initialize player global PLAYER PLAYER = Player(username) GAME_BOARD.register(PLAYER) GAME_BOARD.set_el(0, 9, PLAYER) print PLAYER # Initialize princess global PRINCESS PRINCESS = Princess(princess) GAME_BOARD.register(PRINCESS) GAME_BOARD.set_el(13, 0, PRINCESS) # Initialize Happy global happy happy = Happy() GAME_BOARD.register(happy) GAME_BOARD.set_el(2, 7, happy) # Initialize Yoshua global yoshua yoshua = Yoshua() GAME_BOARD.register(yoshua) GAME_BOARD.set_el(4, 3, yoshua) global yoshua2 yoshua2 = Yoshua() yoshua2.DEFEATED = True GAME_BOARD.register(yoshua2) # Initialize Oski global oski oski = Oski() GAME_BOARD.register(oski) GAME_BOARD.set_el(11, 1, oski) # Initialize Stanford Tree stanfordtree = StanfordTree() GAME_BOARD.register(stanfordtree) GAME_BOARD.set_el(9, 5, stanfordtree) # Initialize campanile campanile = Campanile() GAME_BOARD.register(campanile) GAME_BOARD.set_el(14, 0, campanile) # Initialize door global door_closed door_closed = Door() GAME_BOARD.register(door_closed) GAME_BOARD.set_el(12, 1, door_closed) # GAME_BOARD.erase_msg() # # Initialize and register rock 1 # rock1 = Rock() # GAME_BOARD.register(rock1) # register rock with gameboard so it displays # GAME_BOARD.set_el(1,1,rock1) # places rock on gameboard at coordinates (1,1) # # Initialize and register rock 2 # rock2 = Rock() # GAME_BOARD.register(rock2) # GAME_BOARD.set_el(2,2,rock2) # print "The first rock is at", (rock1.x, rock1.y) # print "The second rock is at", (rock2.x, rock2.y) # print "Rock 1 image", rock1.IMAGE # print "Rock 2 image", rock2.IMAGE # def keyboard_handler(): # if KEYBOARD[key.UP]: # GAME_BOARD.draw_msg("You pressed up") # next_y = PLAYER.y - 1 # GAME_BOARD.del_el(PLAYER.x, PLAYER.y) # GAME_BOARD.set_el(PLAYER.x, next_y, PLAYER) # elif KEYBOARD[key.DOWN]: # GAME_BOARD.draw_msg("Down") # next_y = PLAYER.y + 1 # GAME_BOARD.del_el(PLAYER.x, PLAYER.y) # GAME_BOARD.set_el(PLAYER.x, next_y, PLAYER) # elif KEYBOARD[key.LEFT]: # GAME_BOARD.draw_msg("To the left, to the left") # next_x = PLAYER.x - 1 # GAME_BOARD.del_el(PLAYER.x, PLAYER.y) # GAME_BOARD.set_el(next_x, PLAYER.y, PLAYER) # elif KEYBOARD[key.RIGHT]: # GAME_BOARD.draw_msg("You're right!") # next_x = PLAYER.x + 1 # GAME_BOARD.del_el(PLAYER.x, PLAYER.y) # GAME_BOARD.set_el(next_x, PLAYER.y, PLAYER) # elif KEYBOARD[key.SPACE]: # GAME_BOARD.erase_msg() # class Gem(GameElement): # IMAGE = "BlueGem" # SOLID = False # RETURN = False # def interact(self, player): # player.inventory.append(self) # GAME_BOARD.draw_msg("You just acquired a gem! You have %d item(s)!" %(len(player.inventory))) # class Heart(GameElement): # IMAGE = "Heart" # SOLID = False # RETURN = False # def interact(self, player): # player.inventory.append(self) # GAME_BOARD.draw_msg("You just acquired a heart! You have %d item(s)!" %(len(player.inventory))) # next_x = 2 # next_y = 2
ec2fa6cb6ab3c296efb5faa0cb96d81568b56154
tzabcd/py-study
/python-new-journey/py_28.py
576
3.765625
4
# 解析/构建 XML文档 # from xml.etree.ElementTree import parse # f = open('demo.xml') # et = parse(f) # root = et.getroot() # for child in root: # print(child.get('item')) # list(root.iter()) # .... from xml.etree.ElementTree import Element, ElementTree from xml.etree.ElementTree import tostring e = Element('Data') print(e.tag) e.set('name', 'abc') print(tostring(e)) e2 = Element('Row') e3 = Element("Open") e3.text = '8.80' e2.append(e3) print(tostring(e2)) e.text = None e.append(e2) print(tostring(e)) et = ElementTree(e) et.write('demo.xml')
06caa3ddb87eadd5d6d89b178294ae43c058df57
betty29/code-1
/recipes/Python/269709_Some_python_style_switches/recipe-269709.py
1,901
3.6875
4
#================================================== # 1. Select non-function values: #================================================== location = 'myHome' fileLocation = {'myHome' :path1, 'myOffice' :path2, 'somewhere':path3}[location] #================================================== # 2. Select functions: #================================================== functionName = input('Enter a function name') eval('%s()'% functionName ) #================================================== # 3. Select values with 'range comparisons': #================================================== # # Say, we have a range of values, like: [0,1,2,3]. You want to get a # specific value when x falls into a specific range: # # x<0 : 'return None' # 0<=x<1: 'return 1' # 1<=x<2: 'return 2' # 2<=x<3: 'return 3' # 3<=x : 'return None' # # It is eazy to construct a switch by simply making the above rules # into a dictionary: selector={ x<0 : 'return None', 0<=x<1 : 'return 1', 1<=x<2 : 'return 2', 2<=x<3 : 'return 3', 3<=x : 'return None' }[1] # During the construction of the selector, any given x will turn the # selector into a 2-element dictionary: selector={ 0 : 'return None', 1 : #(return something you want), }[1] # This is very useful in places where a selection is to be made upon any # true/false decision. One more example: selector={ type(x)==str : "it's a str", type(x)==tuple: "it's a tuple", type(x)==dict : "it's a dict" } [1] #================================================== # 4. Select functions with 'range comparisons': #================================================== # # You want to execute a specific function when x falls into a specific range: functionName={ x<0 : 'setup', 0<=x<1: 'loadFiles', 1<=x<2: 'importModules' }[1] eval('%s()'% functionName )
fc6dd12ae34fdd8108916955f737cbfc8ba585fc
moderndragon/garnrechner
/wlc.py
528
3.921875
4
#/usr/bin/python # -*- coding: utf-8 -*- #This little tool calculates the length of the warp needed for a given length of woven ribbon. unit = raw_input("Please specify if you want to use inches or centimeters.\nUse 'in' for inches or 'cm' for cm:") lr = int(raw_input("Please specify the desired length of the finished ribbon:")) if unit == 'cm': lw = int(lr + lr*0.2 + 50) print "Your warp should be min.", lw, "centimetres long." else: lw = int(lr + lr*0.2 + 20) print "Your warp should be min.", lw, "inches long."
f6b6a8902fd6415fd39721dbbec804c4e626cded
Beomsudev/Git
/DAY01/P1/numberTest.py
977
3.859375
4
# numberTest.py a = 14 b = 5 sum = a + b sub = a - b multiply = a * b divide = a / b divide2 = int(a // b) # 이 부분 이해 못함 ! remainder = a % b power = 2 ** 10 print("덧셈 : %d" %(sum)) print("뺄셈 : %d" %(sub)) print("곱셈 : %d" %(multiply)) print("나눗셈 : %f" %(divide)) print("나눗셈2 : %d" %(divide2)) print("나머지 : %f" %(remainder)) print("제곱수 : %d" %(power)) # 양의 정수는 우측 정력 # 정수는 확보할 자리수 print("제곱수2 : [%3d]" %(power)) #power는 4자릿수인데 3자리라서 무시됨 print("제곱수3 : [%6d]" %(power)) #왼쪽부터 6자리해서 남는 2자리 공백 print("제곱수4 : [%-6d]" %(power)) #오른쪽부터 6자리해서 남는 2자리 공백 su = 12.3456789 print("서식1 : [%f]" % (su)) print("서식2 : [%.2f]" % (su)) print("서식3 : [%6.2f]" % (su)) # 6 = 전체 6자리이고, 소수점은 2자리만 표현(소수점 포함 6자리이하) print("서식4 : [%-6.2f]" % (su))
fb060382ca4a499a3b27433ade50f63d74e37300
ndtands/Algorithm_and_data_structer
/Practice_2/sort.py
3,627
4.09375
4
""" Bubble sort for i from 0 to n-2 for j from 0 t0 n-2-i: if a[j]>a[j+1]: swap(a[j],a[j+1]) O(n^2) """ arr=[1,2,3,-12,4,-12,3,-2,0] def Bubble_Sort(arr): n = len(arr) for i in range(n-1): for j in range(n-1-i): if arr[j]>arr[j+1]: arr[j],arr[j+1]=arr[j+1],arr[j] return arr #print(Bubble_Sort(arr)) """ Insertion sort for i from 1 to n-1: for j from 0 to i: if a[i] <a[j] swap(a[i],a[j]) O(N^2) """ def Insertion_sort(arr): for i in range(1,len(arr)): for j in range(i): if arr[i]<arr[j]: arr[j],arr[i]=arr[i],arr[j] return arr #print(Insertion_sort(arr)) """ selection sort: for i from 0 to n-2: min = i for j from i+1,n-1: if a[j] <a[min]: min =j if min != i : swap(a[i],a[min]) return a O(N^2) """ def selection_sort(arr): for i in range(len(arr)-1): min = i for j in range(i+1,len(arr)): if arr[j]<arr[min]: min = j if i != min: arr[min],arr[i]=arr[i],arr[min] return arr #print(selection_sort(arr)) """ Mergesort(arr,left,right): if left==right: return [arr[left]] else: middle = (left+right)//2 left_arr = Mergesort(arr,left,middle) right_arr = Mergesort(arr,middle+1,right) return Merge(left_arr,right_arr) #Ghép 2 mảng lại với nhau mà đảm những phần từ nhỏ nằm về một bên Merge(lef_arr,right_arr): new_arr =[] i=0 j=0 while i<len(left_arr) and j <len(right_arr): if left_arr[i]<right_arr[j]: new_arr.add(left_arr[i]) i+=1 else: new_arr.add(right_arr[j]) j+=1 if i<len(left_arr): new_arr+=left_arr[i:] if j <len(right_arr): new_arr += right_arr[j:] return new_arr T(n)<= 2T(n/2)+O(n) O(nlog(n)) Memory: O(n) """ def Merge(left_arr, right_arr): new_arr = [] i = 0 j = 0 while i < len(left_arr) and j < len(right_arr): if left_arr[i] < right_arr[j]: new_arr.append(left_arr[i]) i += 1 else: new_arr.append(right_arr[j]) j += 1 #add các phần tử còn lại nếu có if i < len(left_arr): new_arr += left_arr[i:] # add các phần tử còn lại nếu có if j < len(right_arr): new_arr += right_arr[j:] return new_arr def MergeSort(arr, start, end): if start == end: return [arr[start]] else: middle = (start + end) // 2 left_arr = MergeSort(arr, start, middle) right_arr = MergeSort(arr, middle+1, end) return Merge(left_arr, right_arr) #print(Merge([3,9,5,2], [1,11,10])) #print(MergeSort(arr,0,len(arr)-1)) """ Quick_sort 2 Thay đổi mảng cho đúng yêu cầu A[k] <= x for all k from l+1 to j A[k] > x for all k from j+1 to i def partition2(arr,start,end): pivot,low,high = arr[start],start+1,end while True: #Check từ end vào có thỏa không while low <=high and arr[high]>=pivot: high = high-1 #Check từ start lên có thỏa không while low <=high and arr[low] <=pivot: low=low+1 #Ko thỏa thì tiến hành hoán đổi if low<=high: arr[low],arr[high]=arr[high],arr[low] else: break #Chuyen pivot vao dung vi tri , luu vao high arr[start],arr[high] =arr[high],arr[start] return high """
614a738b50ed1b6af795099b88717b60ee8e6693
Evilzlegend/Structured-Programming-Logic
/Chapter 01 - An Overview of Computers and Programming/Mindtap Assignments/Executing a Python Program.py
514
4.21875
4
# SUMMARY # In this lab, you will execute a prewritten Python program. # INSTRUCTIONS # 1. Execute the program. There should be no syntax errors. Note the output of this program. # 2. Modify the program so it displays "I'm learning how to program in Python.". Execute the program. # 3. Modify the Python program so it prints two lines of output. Add a second output statement that displays "That's awesome!" Execute the program. print("I'm learning how to program in Python.") print("That's awesome!")
0f5a7d19b1a9dbb1dc326dffa70506881b272aa4
reihanehsr/PythonCourse
/Dec3.py
391
3.921875
4
""" This is the multiline comments """ # This is singleline comment print("Hello") def FirstFunction(): print("Hello Again") FirstFunction() def ReturnSomething(parameter): print(parameter) return parameter print(ReturnSomething(3)) def add(a,b): return a+b print(add(2,4)) def sub(c,d): print(c) print(d) # Perform c - d return(c-d) print (sub(6,8))
c70046996a50e3a6433eb8e2ec188eed97da4d48
harjunpnik/Data-Processing
/Games/Mindreader.py
798
4.15625
4
import sys import random def logic(guess,number): """ This function takes in two numbers and compares the guess to the number and returns a string based on if the guess is Correct, Lower or Higher """ if(guess == number): return("Correct") elif(guess > number): return("Lower") elif(guess < number): return("Higher") number = random.randint(0,10) i = 0 while(True): i += 1 guess = int(input("Guess my number? (between 0-10) \n")) print(logic(guess,number)) if(guess == number): print("It took you {times} to guess my number".format(times = i)) if(input("Write 'y' to Exit \n") == 'y'): print("Thanks for playing") break i = 0 number = random.randint(0,10) exit()
648f6ed098d22aabb83f2c8858c763e93b2e4bac
ankushngpl2311/decision-tree
/tree.py
947
3.859375
4
from collections import deque class node: def __init__(self): self.children ={} # {low:pointer to low,high:pointer to high} def insert(self,name,positive,negative): self.name= name self.positive=positive self.negative=negative # def insert(self,obj): # self.children.append(obj) # def preorderTraversal(root): # for i in root.children: # preorderTraversal(root.children[i]) # print("node name= ",root.name) # print("positive= ",root.positive) # print("negative= ",root.negative) # preorderTraversal(root.ch) def postorder(root): """ :type root: Node :rtype: List[int] """ if root is None: return [] stack, output = [root, ], [] while stack: root = stack.pop() if root is not None: output.append(root.name) for c in root.children: stack.append(root.children[c]) return output[::-1]
bd97d376caa00070e6c60e838bb7d2e0ace9cd7e
viktor1298-dev/WorldOfGames
/Utils.py
983
3.71875
4
SCORES_FILE_NAME = "scores.txt" BAD_RETURN_CODE = "404" def screen_cleaner(): import os os.system('cls||clear') def number_validation(number_list): if len(number_list) == 3: pre_number = 0 while not number_list[1] <= pre_number <= number_list[2]: try: pre_number = int(input(number_list[0])) if not number_list[1] <= pre_number <= number_list[2]: print("You did not enter a number from " + str(number_list[1]) + " to " + str(number_list[2]) + ".") except ValueError: print("You didn't enter a valid number.") pre_number = 0 return pre_number elif len(number_list) == 1: pre_number = "0" while type(pre_number) is not float: try: pre_number = float(input(number_list[0])) except ValueError: print("You didn't enter a valid number.") return pre_number
cf43bbd517df3ed8d1169b58270dbf599f9a7346
Halfoon/BUAA-OJ-Project
/python/1180 简单密码.py
136
3.5
4
word = int(input()) a = int(input()) b = int(input()) c = int(input()) d = int(input()) print("The cyphertext is %d."%((word*a-b)*c+d))
66a18b50bb0fbc664a7ac34e65f1c9fdb18c16ac
sumit88/PythonLearning
/PrimeOrNot.py
318
3.90625
4
num = int(input()) for c in range(num): curr = int(input()) isPrime = True i = 2 while i * i <= curr: if curr % i == 0: isPrime = False break i += 1 if isPrime and curr != 1: print('Prime') else: print('Not prime') isPrime = True
5a96227c28902897521cce3fc4f88232f72ee859
monas1975/Udemy_Python_podstawy
/Udemy_podstawy/8_116_Modul_Math_LAB.py
1,774
3.546875
4
import math if __name__ == '__main__': #1. Zaimportuj moduł math #2 2. Oto wzory pozwalające na wykonanie konwersji stopni na radiany i radianów na stopnie: #1° = (π * rad)/180 #1 rad = 180°/π #3. Zadeklaruj zmienną degree i przypisz jej wartość 360. # Wylicz i wyświetl ile wynosi wartość radianów dla 360 stopni degree = 360 print(degree*math.pi/180) #4. Zmień wartość zmiennej degree na 45 stopni i powtórz obliczenia degree = 45 print(degree*math.pi/180) print('------------------------------') #5. ... ale moduł math ma funkcję radians, która wykonuje konwersję # stopni na radiany! Porównaj wyniki zwracane przez Twoje # obliczenia z obliczeniami funkcji radians. print(math.radians(360)) print(math.radians(45)) #6 6. Pizzeria oferuje pizze: #small - promień 22 cm, cena, 11.50 #big - promień 27 cm, cena 15.60 #family - promień 38cm, cena 22.00 #Zadeklaruj zmienne small_pizza_r, big_pizza_r, family_pizza_r # oraz small_pizza_price, big_pizza_price, family_pizza_price i # zapisz w nich w/w wartości. small_pizza_r = 22 big_pizza_r = 27 family_pizza_r =38 #7. Oblicz pole powierzchni pizz w metrach kwadratowych small_pizza_P = math.pi*(math.pow(small_pizza_r/100,2)) big_pizza_P = math.pi*(math.pow(big_pizza_r/100,2)) family_pizza_P = math.pi*(math.pow(family_pizza_r/100,2)) print(small_pizza_P) print(big_pizza_P) print(family_pizza_P) # 8. Wyznacz cenę metra kwadratowego pizzy small, big i family small_pizza_Price = 11.50/small_pizza_P big_pizza_Price = 15.60/big_pizza_P family_pizza_Price = 22/family_pizza_P print(small_pizza_Price) print(big_pizza_Price) print(family_pizza_Price) #9 math_ls = dir(math) print(math_ls)
30a07b1e4e672119cf0a80c32c1016fe13f192f9
RianMarlon/Python-Geek-University
/secao6_estrutura_repeticao/exercicios/questao45.py
1,126
4.46875
4
""" 45) Faça um algoritmo que converta uma velocidade expressa em km/h para m/s e vice versa. Você deve criar um menu com as duas opções de conversão e com uma opção para finalizar o programa. O usuário poderá fazer quantas conversões desejar, sendo que o programa só será finalizado quando a opção de finalizar for escolhida. """ while True: print("[1] -> Converter velocidade expressa em km/h para m/s\n" "[2] -> Converter velocidade expressa em m/s para km/h \n" "[3] -> Finalizar o programa") opcao = str(input("Digite o número referente à opção que você deseja: ")) print() if (opcao == '1') or (opcao == '[1]'): km_h = float(input("Digite a velocidade expressa em km/h: ")) print() print("Velocidade em m/s: %.2f\n" % (km_h / 3.6)) elif (opcao == '2') or (opcao == '[2]'): m_s = float(input("Digite a velocidade expressa em m/s: ")) print() print("Velocidade em km/h: %.2f\n" % (m_s * 3.6)) elif (opcao == '3') or (opcao == '[3]'): print('FIM') break else: print("ERRO!\n")
edc3e5d94f23305a50f33bd7ea8d9aaba063fca7
imdsoho/python
/class_function/mro_test.py
1,882
3.78125
4
class Base(object): def __init__(self): print('<Base>') #super(Base, self).__init__() super().__init__() print('</Base>') class A(Base): def __init__(self): print('<A>') #super(A, self).__init__() # python 2.7 super().__init__() # (1) print('</A>') class AA(Base): def __init__(self): print('<AA>') #super(AA, self).__init__() # python 2.7 super().__init__() # (2) print('</AA>') class B(A, AA): def __init__(self): print('<B>') #super(B, self).__init__() super().__init__() print('</B>') obj = B() print(B.mro()) # URL: https://codeday.me/ko/qa/20190503/451426.html ''' 상속 체인에서 다음 “up”에 대한 함수 호출로 super를 보지 말아야합니다. 대신, 적절하게 사용되면 super는 MRO의 모든 기능이이 순서로 호출되도록합니다. 그러나 이러한 일이 발생하려면 super call()이 해당 체인의 모든 세그먼트에 있어야합니다. 따라서 A 또는 AA 중 하나에서 super call()을 제거하면 체인이 중단됩니다. 제거하는 항목에 따라 체인이 A 또는 AA에서 중단됩니다. > 중단 없음 (전체 MRO) : B, A, AA,베이스 > 사례 1 (A에서 super call() 없는 경우) : B, A > 사례 2 (AA에서 super call() 없는 경우) : B, A, AA 따라서 제대로 작동하려면 모든 관련 유형에서 항상 super를 일관되게 사용하는 것이 중요합니다. super()에 대해 더 자세히 알고 싶다면 올해 PyCon에서 Raymond Hettinger’s talk “Super considered super!”을 확인해야합니다. 그것은 매우 잘 설명되어 있으며 또한 이해하기 쉬운 몇 가지 예 (실제 사람들을 포함합니다!)가 있습니다. '''
d089f7a1d0e734bea0fb0b5da024c2a37b450b05
italovarzone/Curso_Python_Guanabara
/ex037.py
784
4.28125
4
inteiro = int(input("Digite um número inteiro: ")) print("""Escolha uma das opções: ======================================= [1] Converter o número para BINÁRIO [2] Converter o número para OCTAL [3] Converter o número para HEXADECIMAL =======================================""") esc = int(input("Sua escolha: ")) if esc == 1: print("=" * 39) print("O número {} convertido em BINÁRIO é {}".format(inteiro, bin(inteiro)[2:])) elif esc == 2: print("=" * 39) print("O número {} convertido em OCTAL é {}".format(inteiro, oct(inteiro)[2:])) elif esc == 3: print("=" * 39) print("O número {} convertido em HEXADECIMAL é {}".format(inteiro, hex(inteiro)[2:])) else: print("=" * 39) print("Erro!") print("Escolha inválida, tente novamente!")
4f0eebd888849629419b7e1e5fa18037b3579209
MichalBogoryja/Python_bootcamp
/Modul_03/task_3_1_2.py
229
3.703125
4
limit = 100 divisible = [] cube = [] for num in range(limit+1): if num % 5 == 0: divisible.append(num) cube.append(num**3) result = f"""Podzielne przez 5: {divisible} Ich 3 potęgi: {cube} """ print(result)
7abf69fd28ac978a6301cba69e6d1a8246bee2e6
netnavi20x5/PythonCodes
/Tello Drone/keytest.py
592
3.515625
4
import msvcrt from msvcrt import getch # ... while True: key = ord(getch()) print(key) print(chr(key)) #char = msvcrt.getche() #print(msvcrt.getch().decode(ascii)) #char = msvcrt.getch() # or, to display it on the screen #from msvcrt import getch #while True: # key = ord(getch()) # if key == 27: #ESC # break # elif key == 13: #Enter # select() # elif key == 224: #Special keys (arrows, f keys, ins, del, etc.) # key = ord(getch()) # if key == 80: #Down arrow # moveDown() # elif key == 72: #Up arrow # moveUp()
3bb978b2a6d2112feff99cb462304bee00610fb2
yinyinyin123/algorithm
/数组/findPeakElement.py
400
3.546875
4
### one code one day ### 2020/03/05 ### leetcode 162 寻找峰值 ### 二分法 牛皮 无敌 ### 仔细分析为何可以二分,深入理解二分 def findPeakElement(self, nums: List[int]) -> int: l, r = 0, len(nums)-1 while(l < r): mid = int((l+r)/2) if(nums[mid] > nums[mid+1]): r = mid else: l = mid + 1 return l def test(): pass
285869a6c0ca362c7cbfb302b42e6bad3e668d79
thomashigdon/blackjack-trainer
/bj_count.py
1,756
3.578125
4
#!/usr/bin/python import card_set import random import time import sys plus_one = [ '2', '3', '4', '5', '6' ] minus_one = [ '10', 'J', 'Q', 'K', 'A' ] class Trainer(object): def __init__(self, secs_to_wait, stop_percentage): self.deck = card_set.Deck(6) self.count = 0 self.secs_to_wait = secs_to_wait self.stop_percentage = stop_percentage def go(self): while len(self.deck.card_list) > 0: card = self.deck.deal() if card.value in plus_one: self.count += 1 elif card.value in minus_one: self.count -= 1 print 'Card: %s Decks left: %s' % (card, len(self.deck.card_list) / 52.0) if self.secs_to_wait: if random.random() < self.stop_percentage: return time.sleep(self.secs_to_wait) else: user = raw_input('? ') if user == 'c': print 'Count: ' + str(self.count) def main(argv=None): if argv is None: argv = sys.argv if len(argv) == 3: delay = float(argv[1]) stop_percentage = float(argv[2]) else: delay = None stop_percentage = 0 t = Trainer(delay, stop_percentage) try: while len(t.deck.card_list): t.go() my_count = raw_input("Count? ") if int(my_count) == t.count: print 'Right, it was ' + str(my_count) else: print 'Wrong, it was ' + str(t.count) except KeyboardInterrupt: pass finally: print '\nCount so far was: ' + str(t.count) if __name__ == '__main__': main()
2c62aa2fb2a99f8d8e9d6e191a96c7783b057b27
chuncaohenli/leetcode
/Python/lc121.py
472
3.53125
4
# scan the array for once, and record the minimum price and maximum profit for each element class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if prices == []: return 0 min_price = prices[0] profit = 0 for p in prices: min_price = min(p,min_price) profit = max(profit,p-min_price) return profit
6d195bb3cea67801be370f621fcb658678340751
sietzemm/Codecloud
/CalculateDistanceCoordinates/calc_distance.py
1,808
4.25
4
# Date of creation : 13-10-2018 # Author : Sietze Min # Small exercise : Write a function that takes two points and calculates the distance between them. c1 = (1,2) # coordinate 1 c2 = (-1,1) # coordinate 2 import math import sys print(sys.version) # arguments need to be of type tuple def calc_distance(c1,c2): #Type checking if(type(c1) and type(c2) == tuple): """ Calculates the distance between two coordinates by triangle calculation and the Pythagorean theorem to calculate the final distance. """ a,b = c1,c2 c = tuple() # Create empty tuple placeholder for the C coordinate Cx = abs(b[1]) - abs(a[0]) # Calculate the C coordinate (Cx and Cy) Cx = abs(Cx) + b[0] # Create the C x coordinate value deriven from the length diff between A and B Cy = b[1] # Creates C y coordinate value deriven from the B coordinate c = (Cx,Cy) # Assigns Cx and Cy to the C coordinate tuple line_bc = abs(b[0] - abs(c[0])) # creates side BC for the triangle line_ac = abs(a[1] + abs(c[1])) # creates side AC for the traigle (AB is the hypotenuse and still unkown) # Use Pythagorean theorem (a^2 + b^2 = c^2) a = math.pow(line_bc,2) # creates A^2 b = math.pow(line_ac,2) # creates B^2 c = str(round(math.sqrt(a + b),2)) # creates c, and performs round operation up to 2 decimals result = 'Distance between coordinates : ',c1, 'and ',c2,'is : ',c return result else: print('incorrect input types specified') return False print(calc_distance(c1,c2)) #print(calc_distance('2',2))
1d9b96c6e134b05a348e71a8bd1398ded45bdddd
zembrzuski/think-bayes
/chapter01.py
2,411
3.875
4
""" bayes's theorem p(A and B) = p(B and A) p(A and B) = p(A) * p(B|A) p(B and A) = p(B) * p(A|B) p(A) * p(B|A) = p(B) * p(A|B) p(B|A) = p(B) * p(A|B) ------------- p(A) mas gostamos de usar outras letras, entao posteriori priori likelihood p(H|D) = p(H) * p(D|H) ------------- p(D) normalizacao """ """ the cookie problem bowl 1 --> 30 vanilla 10 chocolate bowl 2 --> 20 vanilla 20 chocolate pego um biscoito de vanilla. qual eh a probabilidade de que tenha vindo do bowl1 ? p(bowl1|vanilla) = ? p(bowl1|vanilla) = p(bowl1) * p(vanilla|bowl1) --------------------- p(vanilla) p(bowl1|vanilla) = .5 * 3/4 ------------ 5/8 """ print(.5*(3./4)/(5./8)) """ tentando usar a tabelinha agora hipotese A - veio do bowl1 hipotese B - veio do bowl2 priori likelihood posteriori p(H) p(D|H) p(H)*p(D|H) p(H|D) ------------------------------------------------------------------- A .5 .75 .375 .6 B .5 .5 .25 .4 the mm problem. b94: 30% brown 20% yellow 20% red 10% green 10% orange 10% tan b96: 24% blue 20% green 16% orange 14% yellow 13% red 13$ brown yellow + green qual eh a probabilidade que o yellow venha da bag b94? HA - yellow veio do b94 e verde veio do b96 HB - yellow veio do b96 e verde veio do b94 priori likelihood multiplication posteriori ----------------------------------------------------------------------------------------- A .5 .2 * .2 .02 .74 B .5 .14 * .1 .007 .26 the monty hall problem. eu estou na porta A; HA - o premio esta na porta A HB - o premio esta na porta B HC - o premio esta na porca C likelihood - probabilidade que o monty abra a porta B priori likelihood multiplication posteriori -------------------------------------------------------------------------------------------- A 1./3 .5 1.6666 .33333 B 1./3 0 0 0 C 1./3 1 .3333 .66666s """
28f596e27af04a2f169c503da854a79b8c2fe731
jan-2018-py1/douglas
/Python/listscompare.py
528
4.09375
4
list1 =['red','blue','green','yellow'] # set list 1 list2 =['red','blue','green','yellow'] # set list 2 list3 = set(list1) & set(list2) # compare list1 vs list2 creates a set of matches x=len(list1) #length of each list y=len(list2) z=len(list3) if x!=y: print "lists don't match" # if list 1 doesn't equal list 2 in length they can't match elif z==x and z==y: print "lists match" # if list1 does match list2 length then we compare list3 length to both x and y if those lengths match all is good.
462726970f110be433c3152286bf2d08c0f5791a
ilmoi/ATBS
/12_practice.py
3,780
3.71875
4
# Practice Questions # 1. Briefly describe the differences between the webbrowser, requests, bs4, and selenium modules. # webbrowser - opens websites, requests - gets data from websites, bs4 - scrapes websites to find specific data, selenium - lets you simulate a user using a browser (for testing or else!) # 2. What type of object is returned by requests.get()? How can you access the downloaded content as a string value? # <class 'requests.models.Response'> # access through .text # 3. What requests method checks that the download worked? # res.raise_for_status() # 4. How can you get the HTTP status code of a requests response? # res.status_code # 5. How do you save a requests response to a file? # with open() as f: for chunk in res.iter_content(100_000) f.write(chunk) # 6. What is the keyboard shortcut for opening a browser’s developer tools? # alt cmd i # 7. How can you view (in the developer tools) the HTML of a specific element on a web page? # right click > inspect element # bs4 questions # 8. What is the CSS selector string that would find the element with an id attribute of main? # ok so a selector is nothing more than a "style" that applies to some elements # selectors can target tag names (eg "body" or "head", "ul", "li ") # selectors can target classes (you can then assign a bunch of "ul"s to a class) - in css you can define classes like section.feature-box and subclasses like section.feature-box.sales, section.feature-box.marketing etc # selectors can target clases based on IDs. you can only have one of them per page soup.select('#main') # because ids are preceded with #!! # 9. What is the CSS selector string that would find the elements with a CSS class of highlight? soup.select('.highlight') # because classes in css defined with a dot # 10. What is the CSS selector string that would find all the <div> elements inside another <div> element? soup.select('div') # all divs soup.select('div span') # all spans within divs soup.select('div > span') # all spans DIRECTLY within divs # 11. What is the CSS selector string that would find the <button> element with a value attribute set to favorite? soup.select('favorite[type="button"]') # this would be one that selects all elements named favorite with a "name" attribute with any value soup.select('favorite[name]') # 12. Say you have a Beautiful Soup Tag object stored in the variable spam for the element <div>Hello, world!</div>. How could you get a string 'Hello, world!' from the Tag object? spam[0].getText() # 13. How would you store all the attributes of a Beautiful Soup Tag object in a variable named linkElem? linkElem = spam[0].attrs # # 14. Running import selenium doesn’t work. How do you properly import the selenium module? ## from selenium.webdriver.common.keys import Keys # from selenium import webdriver # 15. What’s the difference between the find_element_* and find_elements_* methods? # find element returns just one (first) object, elements returns all the objects it finds # # 16. What methods do Selenium’s WebElement objects have for simulating mouse clicks and keyboard keys? browser.get(url) linkElem = browser.find_element_by_link_text('Aamzon') linkElem.click() browser.get(url) htmlElem = browser.find_element_by_tag_name('html') htmlElem.send_keys(Keys.SPACE) # # 17. You could call send_keys(Keys.ENTER) on the Submit button’s WebElement object, but what is an easier way to submit a form with selenium? pwElem = browser.find_element_by_id('user_pass') pwElem.send_keys('1234') pwElem.send_keys(Keys.RETURN) # OR pwElem.submit() # there's a special submit method # # 18. How can you simulate clicking a browser’s Forward, Back, and Refresh buttons with selenium? browser.forward() browser.back() browser.quit() browser.refresh()
294531126bcf7fe82426370826776db1e53fef0b
Mahleat17/Module-4-Lab-Activity
/M4P5.py
1,082
4.375
4
# Calculating Grades (ok, let me think about this one) # Write a program that will average 3 numeric exam grades, return an average test score, a corresponding letter grade, and a message stating whether the student is passing. # Average Grade # 90+ A # 80-89 B # 70-79 C # 60-69 D # 0-59 F # Exams: 89, 90, 90 # Average: 90 # Grade: A # Student is passing. # Exams: 50, 51, 0 # Average: 33 # Grade: F # Student is failing. exam_one = int(input("Input exam grade one: ")) exam_two = int(input("Input exam grade two: ")) exam_three = int(input("Input exam grade three: ")) avg = (exam_one + exam_two + exam_three) / 3 if avg >= 90: letter_grade = "A" elif avg >= 80 and avg < 90: letter_grade = "B" elif avg >= 70 and avg < 80: letter_grade = "C" elif avg >= 60 and avg < 69: letter_grade = "D" else: letter_grade = "F" print("Average: " + str(avg)) print("Grade: " + letter_grade) if letter_grade == "F": print("Student is failing.") else: print("Student is passing.")
30f02fcf403ac6fc3a4723e9da536c2b04eee59c
johnsonlarryl/data_analyst_nano_degree
/project_1_explore_weather_trends/explore_weather_trends.py
5,225
3.671875
4
import argparse import matplotlib.pyplot as plt import numpy as np import pandas as pd from typing import Tuple def get_absolute_values(global_years: pd.Series, local_years: pd.Series) -> Tuple[int, int]: """ Returns the absolute minimum and maximum values for years between the two vectors Parameters: global_years: Vector of global years local_years: Vector of local years Returns: Minimum years to filter out Maximum year to filter out """ global_years_min = global_years.min() global_years_max = global_years.max() local_years_min = local_years.min() local_years_max = local_years.max() min_years = max(global_years_min, local_years_min) max_years = min(global_years_max, local_years_max) return min_years, max_years def get_aggregate_temperatures(weather: pd.Series) -> Tuple[float, float]: """ Returns the average temperature and average temperature differences based on a vector of weather data. Parameters: weather Returns: Average temperature Average temperature difference """ array = weather.to_numpy() avg_temp = np.mean(array) avg_temp_diff = np.mean(np.diff(array)) return round(avg_temp, 2), round(avg_temp_diff, 2) def plot_weather_trends(filtered_global_weather: pd.DataFrame, filtered_local_weather: pd.DataFrame, local_city_name: str, rolling_average: int, output: str) -> None: """ Plots the weather trends locally and globally on a line plot chart or graph. Parameters: filtered_global_weather filtered_local_weather local_city_name rolling_average Returns: None """ fig = plt.figure() fig.subplots_adjust(top=0.8) ax1 = fig.add_subplot(211) ax1.set_xlabel('Years') ax1.set_ylabel('Degrees (°C)') ax1.set_title('Exploration of Weather Trends') plt.plot(filtered_global_weather["year"], filtered_global_weather["avg_temp"].rolling(rolling_average).mean(), label="Global") plt.plot(filtered_local_weather["year"], filtered_local_weather["avg_temp"].rolling(rolling_average).mean(), label=local_city_name) plt.legend() plt.savefig(output) plt.show() def print_weather_trends(global_weather: pd.DataFrame, local_weather: pd.DataFrame) -> None: """ Prints weather trends locally and globally in text form. Parameters: global_weather local_weather Returns: None """ global_weather_avg_temp, global_weather_avg_temp_diff = get_aggregate_temperatures(global_weather["avg_temp"]) local_weather_avg_temp, local_weather_avg_temp_diff = get_aggregate_temperatures(local_weather["avg_temp"]) print(f"Global average temperature : {global_weather_avg_temp} degrees (°C)") print(f"Global average temperature differences : {global_weather_avg_temp_diff} degrees (°C)") print(f"Local average temperature : {local_weather_avg_temp} degrees (°C)") print(f"Local average temperature differences : {local_weather_avg_temp_diff} degrees (°C)") def main(global_weather_file: str, local_weather_file: str, local_city_name: str, rolling_average: str, output: str) -> None: """ Driver or main function that executes program with its associated command line arguments. Parameters: global_weather_file local_weather_file local_city_name rolling_averag Returns: None """ global_weather = pd.read_csv(global_weather_file) local_weather = pd.read_csv(local_weather_file) min_years, max_years = get_absolute_values(global_weather["year"], local_weather["year"]) filtered_global_weather = global_weather[(global_weather.year >= min_years) & (global_weather.year <= max_years)] filtered_local_weather = local_weather[(local_weather.year >= min_years) & (local_weather.year <= max_years)] print_weather_trends(filtered_global_weather, filtered_local_weather) plot_weather_trends(filtered_global_weather, filtered_local_weather, local_city_name, rolling_average, output) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Application that explores weather trends") parser.add_argument("--global_weather", help="Fully qualified file location of global weather trends", required=True) parser.add_argument("--local_weather", help="Fully qualified file location of local weather trends", required=True) parser.add_argument("--local_city", help="Local city name for local weather", required=True) parser.add_argument("--rolling_average", help="Number of years for rolling average", required=True, type=int) parser.add_argument("--output", help="Location of file to output", required=True) args = parser.parse_args() global_weather_file = args.global_weather local_weather_file = args.local_weather local_city_name = args.local_city rolling_average = args.rolling_average output = args.output main(global_weather_file, local_weather_file, local_city_name, rolling_average, output)
a584eb378ce69810347e90392649596e66455854
JingGY/Introduction_to_Software_Fundamentals
/LAB assessment/lab6 Sorting and Searching.py
5,787
3.921875
4
#2 ''' not efficent def bubble_row(data, index): i = 0 while i < index: if data[i] > data[i+1]: new_larger=data[i] new_smaller=data[i+1] data[i+1] = new_larger data[i] = new_smaller i += 1 else: i += 1 return data def bubble_row(data, index): for i in range(index-1): if data[i] > data[i+1]: data[i+1], data[i] = data[i], data[i+1] return data ''' def bubble_row2(data, index): for pass_num in range(index): for i in range(pass_num): if data[i] > data[i+1]: data[i], data[i+1] = data[i+1], data[i] letters = ['e', 'd', 'c', 'b', 'a'] def my_bubble_sort(data): for pass_num in range(len(data)-1): for i in range(0, len(data)-pass_num-1): if data[i] > data[i+1]: data[i], data[i+1] = data[i+1], data[i] return data ''' letters = ['m', 'v', 'o', 'd', 'h', 'l', 'y', 's', 'x', 'z'] letters2 = ['m', 'v', 'o', 'd', 'h', 'l', 'y', 's', 'x', 'z'] bubble_row(letters, 4) print(letters) bubble_row2(letters2, 4) print(letters) #note: forget to use else, so the run time is infinite ''' #3 def my_bubble_sort(data): for pass_num in range(len(data)-1): for i in range(0, len(data)-pass_num-1): if data[i] > data[i+1]: data[i], data[i+1] = data[i+1], data[i] return data ''' letters = ['e', 'd', 'c', 'b', 'a'] my_bubble_sort(letters) print(letters) def my_bubble_sort(data): for pass_num in range(len(data)-1, 0, -1): for ''' #5 def get_position_of_highest(data, index): max_letter = data[0] for i in range(index+1): if max_letter < data[i]: max_letter = data[i] return data.index(max_letter) ''' #test letters = ['e', 'd', 'c', 'b', 'a'] print(get_position_of_highest(letters, 4)) letters = ['g', 'y', 'd', 'h', 'w', 't', 'e', 'q', 'c', 'x', 'b', 'f', 'u', 'r', 'k', 'm'] print(get_position_of_highest(letters, 2)) #note: data.index isn't max_letter.index ''' #6 def selection_row(data, index): max_letter_index = get_position_of_highest(data, index) if data[max_letter_index] > data[index]: data[index], data[max_letter_index] = data[max_letter_index], data[index] ''' letters = ['e', 'd', 'c', 'b', 'a'] selection_row(letters, 4) print(letters) letters = ['b', 'f', 'u', 'r', 'k'] selection_row(letters, 3) print(letters) ''' #q7 def my_selection_sort(data): for i in range(len(data)-1, -1, -1): index_letter = data[i] max_letter_position = get_position_of_highest(data, i) max_letter = data[max_letter_position] if max_letter > index_letter: data[i], data[max_letter_position] = data[max_letter_position], data[i] return data ''' letters = ['e', 'd', 'c', 'b', 'a'] my_selection_sort(letters) print(letters) ''' #9 def shifting(data, index): item_to_check = data[index] i = index - 1 while i >= 0 and data[i] > item_to_check: data[i+1]=data[i] i -=1 return data ''' letters = ['a', 'c', 'f', 'b', 'g'] shifting(letters, 3) print(letters) #['a', 'c', 'c', 'f', 'g'] letters = ['b', 'c', 'k', 'a', 'z', 'n', 'j', 's'] shifting(letters, 3) #['b', 'b', 'c', 'k', 'z', 'n', 'j', 's'] print(letters) note: data[i+1], data[i]= data[i] ,data[i-1] incorrect ''' #10 def insertion_row(data, index): item_to_check = data[index] i = index - 1 while i >= 0 and data[i] > item_to_check: data[i+1]=data[i] i -=1 data[i+1] = item_to_check return data ''' letters = ['b', 'c', 'a', 'e', 'f'] #['a', 'b', 'c', 'e', 'f'] insertion_row(letters, 2) print(letters) letters = ['h', 't', 'w', 'e', 'q', 'c', 'x'] insertion_row(letters, 3) print(letters) #note: data[i+1] is not i-1 or i ''' #q11 def my_insertion_sort(data): for index in range(1, len(data)): item_to_check = data[index] i = index - 1 while i >= 0 and data[i] > item_to_check: data[i+1]=data[i] i -=1 data[i+1] = item_to_check return data letters = ['x', 'b', 'f', 'u', 'r', 'k'] my_insertion_sort(letters) print(letters) #q12 Binary Search import math def binary_search(numbers, value): max_index = len(numbers) - 1 min_index = 0 while (min_index <= max_index): mid_index = math.floor((max_index+min_index)/2) if numbers[mid_index] == value: return mid_index elif numbers[mid_index] < value: min_index = mid_index + 1 elif numbers[mid_index] > value: max_index=mid_index - 1 return -1 numbers = [10, 15, 20, 27, 41, 69] print(binary_search(numbers, 69)) numbers = [13, 18, 54, 61, 78, 93] print(binary_search(numbers, 7)) #note: 1. return mid_index rather than min_index be careful 2. mid_index = (lower + higher)/2 rahter than mins def binary_search(numbers, value): max_index = len(numbers) - 1 min_index = 0 while (min_index <= max_index): mid_index = math.floor((max_index+min_index)/2) if numbers[mid_index] == value: return mid_index elif numbers[mid_index] < value: min_index = mid_index + 1 elif numbers[mid_index] > value: max_index = mid_index - 1 return -1 numbers = [10, 15, 20, 27, 41, 69] print(binary_search(numbers, 69)) numbers = [13, 18, 54, 61, 78, 93] print(binary_search(numbers, 7))
b780fb649c65dec4953dd862634ccc7fd59d51c9
yeomko22/TIL
/algorithm/programmers/greedy/kruskal.py
646
3.609375
4
def find(cycle_table, x): if cycle_table[x] == x: return x return find(cycle_table, cycle_table[x]) def union(cycle_table, x, y): x = find(cycle_table, x) y = find(cycle_table, y) if x < y: cycle_table[y] = x else: cycle_table[x] = y def solution(n, costs): answer = 0 sorted_cost = sorted(costs, key=lambda x: x[2]) cycle_table = [i for i in range(n)] for cost in sorted_cost: x = find(cycle_table, cost[0]) y = find(cycle_table, cost[1]) if x==y: continue answer += cost[2] union(cycle_table, x, y) return answer
af93e702da8ac6329ab9059d03d056d975142775
munishstudy73/pythonstudy
/sourcecode/apress_bundle/python3.0/things.py
1,245
4.09375
4
#! /usr/bin/python3.0 class Thing: def __init__(self, price, strength, speed): self.price = price self.strength = strength self.speed = speed def __str__(self): stats = """\tPrice\tStr\tSpeed {price!s}\t{strength!s}\t{speed!s}\t""".format(**vars(self)) return stats def __repr__(self): stats = 'Thing({price!s}, {strength!s}\ , {speed!s})'.format(**vars(self)) return stats def __format__(self, formatcode): return str(self) class Weapon(Thing): def __init__(self, price, strength, speed): self.price = price self.strength = strength self.damage = strength self.speed = speed def __str__(self): stats = """\tPrice\tDamage\tSpeed {price!s}\t{damage!s}\t{speed!s}\t""".format(**vars(self)) return stats def __repr__(self): stats = 'Weapon({price!s}, {strength!s}\ , {speed!s})'.format(**vars(self)) return stats class Armour(Thing): def __repr__(self): stats = 'Armour({price!s}, {strength!s}\ , {speed!s})'.format(**vars(self)) return stats inventory = {"box":Thing(0, 1, 0), "axe":Weapon(75, 60, 50), "shield":Armour(60, 50, 23)} print("\n::Inventory::\n-------------") for key, item in inventory.items(): print("{0!s}:\t{1!s}\t{2!s}.".format(key, item, repr(item))) print()
97be7d29dcb7ec5b7aade3a909dce434fd7e6648
tomjjoy/MTA-extraction
/retrieve-MTA-turnstile-data-files.py
1,881
3.765625
4
''' This script retrieves the list of all available turnstile data files from the New York MTA web site, and saves the files to a local folder. The page where the files are listed is http://web.mta.info/developers/turnstile.html The file names from the page do not include the first two digits for the year, the missing digits are added to the file name when the file is saved. Didn't they live through Y2K? In their defense, the available files go back to 2010 (as I write this), so there is no risk of confusion. Note: I use the requests library instead of urllib2 because I prefer writing r = requests.get(myurl) instead of r = urllib2.urlopen(myurl) It saves me 3 characters. Otherwise functionality is the same for this simple case. ''' import requests from bs4 import BeautifulSoup as BS4 import re from timeit import default_timer as timer import humanfriendly # initialize URL and folder, record start time urlroot = r'http://web.mta.info/developers/' path = r'e:\python\MTAturnstile\turnstile_20' starttime = timer() # read the page html and use BeautifulSoup to extract the list of data files r = requests.get(urlroot + 'turnstile.html') soup = BS4(r.content, features = 'html.parser') files = soup.find('div', {'id': 'contentbox'}).find('div', {'class': 'container'}).find('div', {'class': 'span-84 last'}).findAll('a', attrs={'href': re.compile("^data/nyct/turnstile/")}) # iterate through the list of files, retrieve the data for each file, and save file to the local folder for file in files: print('Saving file turnstile_20' + str(file)[39:49]) datafile = requests.get(urlroot + str(file)[9:49]) with open(path + str(file)[39:49], 'w') as outf: for line in datafile.text: outf.writelines(line) # record completion time and display duration endtime = timer() print('Completed in ' + humanfriendly.format_timespan(endtime-starttime))
4f6c8cd536cf6910dd4f79e7e4acf0dce7b65230
DawnBee/01-Learning-Python-PY-Basics
/OOP Projects & Exercises/Exercise-3.py
461
4.15625
4
# OOP Exercise 3: Create a child class Bus that will inherit all of the variables and methods of the Vehicle class class Vehicle: def __init__(self,name,max_speed,mileage): self.name = name self.max_speed = max_speed self.mileage = mileage def vehicle_info(self): return f"Vehicle Name: {self.name} Speed: {self.max_speed} Mileage: {self.mileage} " class Bus(Vehicle): pass vehicle_1 = Bus('School Volvo',180,12) print(vehicle_1.vehicle_info())
e6a3002c1e67f0a021e0d8dce96b513fb8c48f77
chenzhiyuan0713/Leetcode
/Easy/Q47.py
749
3.625
4
""" 1748. 唯一元素的和 给你一个整数数组 nums 。数组中唯一元素是那些只出现 恰好一次 的元素。 请你返回 nums 中唯一元素的 和 。 示例 1: 输入:nums = [1,2,3,2] 输出:4 解释:唯一元素为 [1,3] ,和为 4 。 示例 2: 输入:nums = [1,1,1,1,1] 输出:0 解释:没有唯一元素,和为 0 。 示例 3 : 输入:nums = [1,2,3,4,5] 输出:15 解释:唯一元素为 [1,2,3,4,5] ,和为 15 。 """ class Solution: def sumOfUnique(self, nums: list) -> int: summm = 0 for each_num in nums: if nums.count(each_num) == 1: summm += each_num return summm answer = Solution() print(answer.sumOfUnique([1,2,3,2]))