blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
230b1f483b617e08823bdba20dbbf0272be5e8a7
esturniolo/iades2do
/paisan/2doCuatrimestre/Ej08-determinarGrupoEtareoEdad.py
328
4.0625
4
edad = int(input("Ingrese la edad del jugador: ")) if (edad <= 12): print("El jugador es categoria Menor") elif (edad > 13 and edad <= 18): print("El jugador es categoria Cadete") elif (edad > 18 and edad <= 26): print("El jugador es categoria Juvenil") elif (edad > 26): print("El jugador es categoria Mayor")
0f9e02966fd49346f3fcb8fe4ba68f6c3296b272
weekmo/master_python
/src/matrix2.py
1,298
3.796875
4
def matrix_get_submatrix(m,i,j): ''' >>> matrix_get_submatrix([[1,2,3,4],[5,6,7,8],[2,6,4,8],[3,1,1,2]],0,3) [[5, 6, 7], [2, 6, 4], [3, 1, 1]] ''' d=len(m) assert d>2 ks=[] for x in range(d): sub_matrix=[] for y in range(d): if x !=i and y!=j: sub_matrix.append(m[x][y]) if sub_matrix: ks.append(sub_matrix) return ks #Function to Get determinat def matrix_det2(m): ''' >>> matrix_det2([[1,2,3,4],[5,6,7,8],[2,6,4,8],[3,1,1,2]]) 72 >>> matrix_det2([[1,2,3,4],[5,7,9,6],[4,6,8,3],[2,5,1,5]]) 77 >>> matrix_det2([[1,2],[5,6]]) -4 ''' assert isinstance(m,list) if isinstance(m[0],list): assert len(m)==len(m[0]) matrix_len=len(m) if matrix_len<2: return m[0] elif matrix_len==2: return (m[0][0]*m[1][1])-(m[0][1]*m[1][0]) else: sign=1 x=0 for i in range(matrix_len): x += sign * m[0][i] * matrix_det2(matrix_get_submatrix(m,0,i)) sign *= -1 return x if __name__ == "__main__": import doctest doctest.testmod() print(matrix_det2([[1,2,3,4],[5,6,7,8],[2,6,4,8],[3,1,1,2]])) print(matrix_det2([2])) print(matrix_det2([[3,4,5],[2,1,6],[3,0,-2]]))
6d074668d3bfe4e71240b545ccd18e658200484b
MedAmine-SUDO/30daysofcode
/day25.py
515
4.03125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT #!/bin/python3 import math def is_prime(n): if n <= 1: return "Not prime" max_div = math.floor(math.sqrt(n)) for i in range(2, 1 + max_div): if n % i == 0: return "Not prime" return "Prime" if __name__ == '__main__': T=int(input()) container_nbr = [] for i in range(T): n = float(input()) container_nbr.append(n) for i in container_nbr: print(is_prime(i))
f0183d69b60938418e9dded92f44fda3e822d1c8
Kuehar/LeetCode
/Search Insert Position.py
602
3.890625
4
class Solution: def searchInsert(self, nums: List[int], target: int) -> int: left,right = 0,len(nums)-1 mid = 0 while right >= left: mid = (left+right)//2 if nums[mid] == target: return mid if nums[mid] > target: right = mid-1 elif nums[mid] < target: left = mid+1 return left # Runtime: 90 ms, faster than 10.73% of Python3 online submissions for Search Insert Position. # Memory Usage: 15 MB, less than 81.54% of Python3 online submissions for Search Insert Position.
5b2bf6685ec246bc8ed40068aa4b69ddc0a7044f
simonaDemo/python
/python_palindrome.py
269
4.375
4
word = input ("Please, enter a word: ") word = str(word) rvs = word[::-1] #from the beginning to the end of a word go backwards if word == rvs: print ("This word is a palindrome") else: print ("This word is not a palindrome")
b9681d0d1df29d15f3786e04846e426dc23287a1
testautomation8/Learn_Python
/Python Exercises/Exercise_9.py
888
4.40625
4
"""Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right Extras: Keep the game going until the user types โ€œexitโ€ Keep track of how many guesses the user has taken, and when the game ends, print this out""" import random choice = "Y" cnt = 1 while choice.strip() == "Y": usrNumber = int(input("Please guess the number between 1 to 9: ")) rndNumber = random.randint(1, 9) if usrNumber == rndNumber: print("You have guessed exactly right!!") break elif usrNumber > rndNumber: print("You have guessed too high!!") cnt = cnt + 1 else: print("You have guessed too low!!") cnt = cnt + 1 choice = input("Would you like to continue(Y/N):") print("You have taken " + str(cnt) + " chances to guess right")
23a1fcabced8677153cfe7b957d3abfbf542a1b0
andres823/Ejercicios-spydr-20211
/Ejercicio_129_18_03_2021_1_F_P.py
358
3.828125
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 19 01:26:51 2021 @author: Andres Giron """ def multiplicar(lista,va): for x in range(len(lista)): multi=lista[x]*va print(multi) # bloque principal lista=[3, 7, 8, 10, 2] print("Lista original:",lista) print("Lista multiplicando cada elemento por 3") multiplicar(lista,3)
fd0804916d888393f863820b637e69c63503657a
lipikumari/python_learning
/math.py
604
3.859375
4
#Python math #Built-in math function a=min(5,7,9) b=max(5,7,9) print(a) print(b) #abs() function return absolute value a=abs(-49.66) print(a) #pow(a,b) function returns x to the power of y a=pow(7,8) print(a) #math.sqrt() method returns the square root of a number import math a=int(math.sqrt(225)) print(a) #math.ceil() method rounds a number upwards to its nearest integer, and the math.floor() method rounds a number downwards to its nearest integer. import math a=math.ceil(7.5) b=math.floor(7.5) print(a) print(b) #math.pi return value of pi import math c=math.pi print(c)
b2cca85663c814e36962a52613953b1bcc7646bd
arivolispark/datastructuresandalgorithms
/leetcode/leetcode_question_bank/problems/20_valid_parentheses/valid_parentheses.py
2,315
3.9375
4
""" Problem #: 20 Title: Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: 1) Open brackets must be closed by the same type of brackets. 2) Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1: Input: "()" Output: true Example 2: Input: "()[]{}" Output: true Example 3: Input: "(]" Output: false Example 4: Input: "([)]" Output: false Example 5: Input: "{[]}" Output: true """ from collections import deque class Solution: def isValid(self, s: str) -> bool: if s: q = deque() for i in range(len(s)): if s[i] == "(" or s[i] == "{" or s[i] == "[": q.append(s[i]) elif s[i] == ")": #print(len(q)) if len(q) == 0: return False elif q[-1] == "(": q.pop() else: q.append(s[i]) elif s[i] == "}": #print(len(q)) if len(q) == 0: return False elif q[-1] == "{": q.pop() else: q.append(s[i]) elif s[i] == "]": #print(len(q)) if len(q) == 0: return False elif q[-1] == "[": q.pop() else: q.append(s[i]) if len(q) == 0: return True else: return False return True def test(got, expected): if got == expected: prefix = ' OK ' else: prefix = ' X ' print('{} got: {} expected: {}'.format(prefix, repr(got), repr(expected))) if __name__ == "__main__": solution = Solution() test(solution.isValid("()"), True) test(solution.isValid("()[]{}"), True) test(solution.isValid("(]"), False) test(solution.isValid("([)]"), False) test(solution.isValid("{[]}"), True) test(solution.isValid("]"), False) test(solution.isValid("(])"), False)
88b848a42fa96cfd9db61375963aaede558df4df
golfnut1400/kalacademy
/Hwk1_1.3 Dispaly a pattern FUN.py
1,360
4.0625
4
# Introduction to Programming # Homework 1 # Created by: Stan Corpuz # Jan 16, 2018 #1.13 Display a Pattern - FUN ''' I needed help on this. After an exhaustive search how I would join each characters, I reached out to the Community in StackOverflow See https://stackoverflow.com/questions/48276660/print-pattern-fun-using-python ''' # create a 'F' function. Use '.join' string method inside of a list [ ] def pattern_f(): return [ ''.join([ 'F' if (col == 0 or col == 1 or row == 0 or row ==2) else ' ' for col in range(7)]) for row in range(5) ] # create a 'U' function def pattern_u(): return [ ''.join([ 'U' if ((col==0 or col==6) and row<3) or (row==3 and (col==1 or col==5)) or (row==4 and col>1 and col<5) else ' ' for col in range(7)]) for row in range(5) ] # create a 'N' function def pattern_n(): return [ ''.join([ 'N' if (col==0 or col==1 or col==6 or col==7) or (row==col-1) else ' ' for col in range(8)]) for row in range(5) ] ##separate printing: for string in pattern_f(): print(string) print() for string in pattern_u(): print(string) print() for string in pattern_n(): print(string) print() ##combining. calling functions above for f,u,n in zip(pattern_f(), pattern_u(), pattern_n()): print(f,u,n)
01fe4e0679f132781193f522614a069ebcacf21b
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_116/433.py
1,572
3.546875
4
# -*- coding: utf-8 -*- def who_win(board): for player in ['X', 'O']: for i in xrange(0, 4): line = board[i] line_processed = [c for c in line if c == player or c == 'T'] if len(line_processed) == 4: return player for i in xrange(0, 4): column = [line[i] for line in board] column_processed = [c for c in column if c == player or c == 'T'] if len(column_processed) == 4: return player for i in [0, -3]: diagonal = [] for line in board: diagonal.append(line[abs(i)]) i += 1 diagonal_processed = [c for c in diagonal if c == player or c == 'T'] if len(diagonal_processed) == 4: return player return 0 n = int(input()) board_set = [] for i in xrange(0, n): current_board = [] for j in xrange(0, 4): current_board.append(list(raw_input())) if i != n-1: blank_line = raw_input() board_set.append(current_board) i = 1 for board in board_set: if who_win(board) == 'X': print "Case #" + str(i) + ": X won" elif who_win(board) == 'O': print "Case #" + str(i) + ": O won" else: united_board = [] for line in board: united_board += line is_finish = False if '.' in united_board else True if is_finish: print "Case #" + str(i) + ": Draw" else: print "Case #" + str(i) + ": Game has not completed" i += 1
337a204762cf53674e10225b86750a0fc17ce62b
anieshchawla/algorithms
/checksum.py
2,832
3.6875
4
'''This is the file to calculating the ip header checksum it assumes that 2 bytes checksum value is (0,0) before it calculates the checksum and then outputs the resultant ip header''' class csum_ip(): def __init__(self,header_list): self.header_list = header_list def calc_checksum(self,header_hex): '''this function is the one which actually calculates the checksum''' _check_sum = 0 header_hex = header_hex.split(",") for hex_byte in header_hex: _check_sum +=int(hex_byte,16) _present_csum = hex(_check_sum)[2:] _present_csum = _present_csum[len(_present_csum)-4:] _present_csum=int(_present_csum,16) print "csum before while ",_present_csum _carry_over =_check_sum>>16 while(_carry_over>0): _present_csum +=_carry_over _carry_over = _present_csum>>16 _present_csum = hex(_present_csum)[2:] _present_csum = _present_csum[len(_present_csum)-4:] _present_csum=int(_present_csum,16) print _present_csum _check_sum=_present_csum&0xFFFF ^ 0xFFFF #we are flipping the bits and then trimming it to 16bits values _check_sum= hex(_check_sum)[2:] _checksum1 = _check_sum[:len(_check_sum)-2] _checksum2=_check_sum[len(_check_sum)-2:] _checksum1=int(_checksum1,16) _checksum2=int(_checksum2,16) _checksum=(_checksum1,_checksum2) return _checksum def header_csum(self): header_list=self.header_list _header_in_hex=",".join(format(header_list[_iter-1],'02x')+ format(header_list[_iter],'02x') for _iter in xrange(1,(len(header_list)),2)) print _header_in_hex _checksum_tuple = self.calc_checksum(_header_in_hex) return _checksum_tuple length_of_ip_header = (69,) #in hex it is 45, 4 ---> 1st 4 bits of this represent version, next 4 bits represent # => (45): 4--> version i.e. IPv4 and # 5 -->lenght of header , mininum is 5(RFC 791) which means 5x32=160bits = 20bytes of header ecn_field = (0,) #this is set to 1 if you want explicit congestion notification length_of_ip_data = (1,211) packet_id = (236, 246) flag_for_offset = (0,) offset_field = (0,) time_to_live = (64,) protocol_type = (17,) #Protocol type 17=UDP ip_header_check_sum = (0,0) #intializing it to (0,0) so that we can calucate the checksum and then add the value at this position, value should be(6, 153) src_ip_field = (192, 68, 2, 1) dest_ip_field = (192, 68, 3, 1) #pkt = 69, 0, 1, 211, 236, 246, 0, 0, 64, 17, 6, 153, 192, 68, 2, 1, 192, 68, 3, 1 ip_header = length_of_ip_header+ecn_field+length_of_ip_data+packet_id+flag_for_offset+offset_field+time_to_live+protocol_type+ip_header_check_sum+src_ip_field+dest_ip_field checksum=csum_ip(ip_header) print checksum.header_csum()
c9c696e55a500b38ab082f7ec1d339e01eb4370c
asmagulzar/Python
/Assignment/SubstringInString.py
132
4.15625
4
str = input("Enter String:") substr = input("Enter SubString:") if (str.find(substr) == -1): print("NO") else: print("YES")
97064c6a556e315f7e747a54df9318ddd40d5469
icerovski/Python_Fundamentals
/Unit_04/Exercise_Dicts_05.py
438
3.8125
4
# 05. Mixed Phones phone_book = {} while True: line = input() if line == "Over": break else: new_line = line.split(' : ') if new_line[0].isdigit(): name = new_line[1] phone = new_line[0] else: name = new_line[0] phone = new_line[1] phone_book[name] = phone for key, value in sorted(phone_book.items()): print(f'{key} -> {value}')
7b3a459b85b3fccc72d2b3f231dada2e3219ab6a
jsimkoff/DataStructures
/Module6/set_range_sum/set_range_sum.py
9,687
3.59375
4
# python3 from sys import stdin import sys, threading sys.setrecursionlimit(10**7) # max depth of recursion threading.stack_size(2**27) # new thread will get stack of such size # Splay tree implementation # Vertex of a splay tree class Vertex: def __init__(self, key, sum, left, right, parent): (self.key, self.sum, self.left, self.right, self.parent) = (key, sum, left, right, parent) def update(v): # print("updating") if v == None: return # update sums on v, and parent pointers on its children v.sum = v.key + (v.left.sum if v.left != None else 0) + (v.right.sum if v.right != None else 0) if v.left != None: v.left.parent = v if v.right != None: v.right.parent = v def smallRotation(v): parent = v.parent if parent == None: return grandparent = v.parent.parent if parent.left == v: # rotate to the right; so the previous right child of v is now the left child # of v's parent (which is now v's right child) m = v.right v.right = parent parent.left = m else: # similarly, rotate v to the left; so now its parent becomes its left child # and any left child of v becomes the former parent's right child m = v.left v.left = parent parent.right = m update(parent) update(v) v.parent = grandparent if grandparent != None: if grandparent.left == parent: grandparent.left = v else: grandparent.right = v def bigRotation(v): # if "straight" up either left or right, zig-zig if v.parent.left == v and v.parent.parent.left == v.parent: # Zig-zig smallRotation(v.parent) smallRotation(v) elif v.parent.right == v and v.parent.parent.right == v.parent: # Zig-zig smallRotation(v.parent) smallRotation(v) # otherwise zig-zag -- see slides for pictures else: # Zig-zag smallRotation(v) smallRotation(v) # Makes splay of the given vertex and makes # it the new root. def splay(v): if v == None: return None while v.parent != None: # as long as grandparent exists, bigRotation is always called # -- small rotation gets called once at the end, followed by loop break if v.parent.parent == None: smallRotation(v) break bigRotation(v) # return the new root node after splay return v # Searches for the given key in the tree with the given root # and calls splay for the deepest visited node after that. # Returns pair of the result and the new root. # If found, result is a pointer to the node with the given key. # Otherwise, result is a pointer to the node with the smallest # bigger key (next value in the order). # If the key is bigger than all keys in the tree, # then result is None. def find(root, key): v = root last = root next = None while v != None: # if still above the key value, and a smaller value is encountered, update # next with this tighter upper bound node if v.key >= key and (next == None or v.key < next.key): next = v # last is the pointer to the current node last = v if v.key == key: break # binary search tree property still holds for these even if they aren't AVL trees if v.key < key: v = v.right else: v = v.left # after the loop terminates (either because we found the key and broke, or because # v == None so no value found), splay the final visited node root = splay(last) # if the key is found, result and root will be the same # if not, and if there is a bigger value in the tree, they may or may not be the # same # if no such value exists, next is None and root is just the last visited node return (next, root) def split(root, key): (result, root) = find(root, key) # if find returned result = None, there are no nodes in the tree with keys above # the given key, so just return the root node for the single tree and do no # updates if result == None: return (root, None) # otherwise, splay the next bigger node and set right new tree node to that node right = splay(result) # left is a temp var for the child to the left of the splayed node left = right.left # then set right.left = None to split the trees effectively right.left = None # and ensure that left is now root node for its own tree too if left != None: left.parent = None # update the values on these two nodes update(left) update(right) # return pointers to the root nodes for two new trees return (left, right) def merge(left, right): # if either of the nodes don't exist, just return the one that does if left == None: return right if right == None: return left while right.left != None: right = right.left # splay the leftmost node on the "right" tree being merged -- so, the smallest # value on the bigger tree is now root right = splay(right) # the right side of the right tree is still good, need to set its left side to # be the left tree right.left = left # update the whole tree (this will take care of sum and settings its chidlrens # parent pointers) and return update(right) return right # Code that uses splay tree to solve the problem root = None def pre_order(): # print pre-order tree traversal for debugging def _pre_order(r): if r is None: return key_result.append(r.key) sum_result.append(r.sum) _pre_order(r.left) _pre_order(r.right) return global root key_result = [] sum_result = [] _pre_order(root) return key_result, sum_result def insert(x): # print("inserting value: %f" % x) global root # split the tree starting at root for value x (left, right) = split(root, x) new_vertex = None # if x is bigger than the whole tree, or if the right tree doesn't happen to have # key=x, need to create a new vertex with key (and current sum) of x if right == None or right.key != x: new_vertex = Vertex(x, x, None, None, None) # then merge left with the new_vertex if it was created, then merge again with right # -- NOTE, this means that if right.key == x aobve, you just merge the two trees # without creating a new vertex root = merge(merge(left, new_vertex), right) def erase(x): # print("***ERASING***: %f" % x) global root this, root = find(root, x) if (this is None) or (this.key != x): # print("condition 0") return next, root = find(root, x+1) if next is None: splay(this) if this.left is None: # if node with key x was only node in the tree # print("condition 1") root = None return # if x was largest key in the tree # print("condition 2") newroot = this.left # print(newroot.key) newroot.parent = None root = splay(newroot) # root.right = None return else: # print("condition 3") splay(next) splay(this) next.parent = None if this.left is not None: next.left = this.left this.left.parent = next root = next return def search(x): # print("searching for %f" % x) global root (result, root) = find(root, x) if (result is not None) and (result.key == x): return True else: return False return def sum(fr, to): # print("sum from %f to %f" % (fr, to)) global root (left, middle) = split(root, fr) if middle is None: # print("all values are smaller than fr") root = merge(left, middle) return 0 (middle, right) = split(middle, to + 1) if middle is None: # print("all values are smaller than to") root = (merge(left, right)) return 0 # print("there is a sum value") ans = middle.sum root = merge(left, merge(middle, right)) return ans # if __name__ == "__main__": def main(): # f = open('out.log', 'w+') MODULO = 1000000001 n = int(stdin.readline()) last_sum_result = 0 for i in range(n): # print(i) line = stdin.readline().split() if line[0] == '+': x = int(line[1]) insert((x + last_sum_result) % MODULO) # keys, sums = pre_order() # print(keys) # print(sums) elif line[0] == '-': x = int(line[1]) erase((x + last_sum_result) % MODULO) # keys, sums = pre_order() # print("keys after erase:") # print(keys) # print(sums) elif line[0] == '?': x = int(line[1]) print('Found' if search((x + last_sum_result) % MODULO) else 'Not found') # f.write('Found \t %d \n' % op_ct if search((x + last_sum_result) % MODULO) else 'Not found \t %d \n' % op_ct) # keys, sums = pre_order() # print(keys) # print(sums) elif line[0] == 's': l = int(line[1]) r = int(line[2]) res = sum((l + last_sum_result) % MODULO, (r + last_sum_result) % MODULO) print(res) # f.write('%d \t %d \n' % (res, op_ct)) last_sum_result = res % MODULO # keys, sums = pre_order() # print(keys) # if root is not None: # print("root plus left / right after sum") # print(root.key) # print(root.left) # print(root.right) # print(sums) # print(keys) # f.close() threading.Thread(target=main).start()
bc6a1f6d2f89418119d719f1a16240d66c5ccf09
PranavM98/Poker-Simulation
/evaluate.py
9,981
3.65625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 28 15:08:03 2020 @author: pranavmanjunath """ from card import Card, card_from_num from deck import Deck # finds flush suit def find_flush(hand): d_suit={} for card in hand.cards: if card.suit in d_suit: d_suit[card.suit] += 1 else: d_suit[card.suit] =1 #print(d_suit) for i,a in d_suit.items(): if a>=5: return i return None # makes dictionary of cards values to count of their occurances def count_values(hand): d_value={} for card in hand.cards: if card.value in d_value: d_value[card.value] += 1 else: d_value[card.value] =1 d_value=dict(sorted(d_value.items(), key=lambda x: x[1], reverse=True)) # #print(d_value) return d_value pass # uses counts dict and returns a tuple (value with most n of a kind, n) def get_max_count(hand, counts): lst=[] for k,v in counts.items(): max_v=v break for k,v in counts.items(): if max_v ==v: lst.append(k) max_k=max(lst) m=(max_k,max_v) return m pass # finds index of second pair or returns -1 for no sec pair def find_secondary_pair(hand, counts, val): sec_val=-1 for k,v in counts.items(): if k!=val: if v>=2: sec_val=k if sec_val==-1: return -1 else: for i in range(len(hand.cards)): if hand.cards[i].value ==sec_val: return i # get first index of value in hand def get_kind_index(hand, value): for i in range(len(hand.cards)): if value==hand.cards[i].value: return i pass # build hand with n of a kind starting at ind def build_of_a_kind(hand, n, ind): d=Deck() for i in range(ind,ind+n): d.add_card(hand.cards[i]) for i in range(len(hand.cards)): if hand.cards[i].value!=d.cards[0].value: d.add_card(hand.cards[i]) if len(d.cards)==5: break return d pass # adds secondary pair (for full house or two pair) def add_pair(hand,ind_s, ans_deck, ind_a): #print("INSIDE") #Full House if ind_a == 3: for i in range(ind_s,ind_s+2): for j in range(ind_a,ind_a+2): ans_deck.cards[j]=hand.cards[i] ind_a += 1 break if ind_a ==2: for i in range(ind_s,ind_s+2): for j in range(ind_a,ind_a+2): ans_deck.cards[j]=hand.cards[i] ind_a += 1 break for i in range(len(hand.cards)): if hand.cards[i].value != ans_deck.cards[0].value and hand.cards[i].value != ans_deck.cards[2].value: ans_deck.cards[len(ans_deck.cards)-1]=hand.cards[i] break #print(ans_deck) return ans_deck pass # helper for is_straight_at def is_n_length_straight_at(hand, ind, fs, n): pass # helper for is_straight_at def is_ace_low_straight_at(hand, ind, fs): pass # if fs = None, look for any straight # if fs = suit, look for straight in suit # returns -1 for ace-low, 1 for straight, 0 for no straight def is_straight_at(hand, ind, s): lst=[] if s is None: start=hand.cards[ind].value count=1 for i in range(ind+1,len(hand.cards)): if hand.cards[i].value != start: if hand.cards[i].value == start-1: count += 1 start=hand.cards[i].value #print(count) #straight if count==5: return 1 #ace low straight elif count==4: lst=[] for i in hand.cards: lst.append(i.value) if 14 in lst and 2 in lst and 3 in lst and 4 in lst and 5 in lst: return -1 else: return 0 else: return 0 else: start=hand.cards[ind].value start_s=hand.cards[ind].suit count=1 for i in range(ind+1,len(hand.cards)): if hand.cards[i].value != start: if hand.cards[i].value == start-1 and hand.cards[i].suit == start_s: count += 1 start=hand.cards[i].value #print("VALUE OF COUNT",str(count)) if count ==5: return 1 elif count == 4: lst=[] #ACE if hand.cards[0].suit==s: for i in hand.cards: lst.append(i.value) if 14 in lst and 2 in lst and 3 in lst and 4 in lst and 5 in lst: return -1 else: return 0 else: return 0 pass # provided def copy_straight(hand, ind, fs, ace_low=False): ans = Deck() last_card = None target_len = 5 #print("INDEX",str(ind)) #print("hand",hand) assert not fs or hand.cards[ind].suit == fs if ace_low: assert hand.cards[0].value == 14 last_card = hand.cards[0] target_len = 4 to_find = 5 #ind += 1 pass else: # regular straight to_find = hand.cards[ind].value pass while len(ans.cards) < target_len: #print(ind) if ind==len(hand.cards): break assert ind < len(hand.cards) if hand.cards[ind].value == to_find: if not fs or hand.cards[ind].suit == fs: ans.add_card(hand.cards[ind]) to_find -= 1 pass pass ind += 1 pass #print(ans) if last_card is not None: ans.add_card(last_card) pass assert len(ans.cards) == 5 #print("ANS") #print(ans) return ans # provided # looks for a straight (or straight flush if fs is not None) # calls the student's is_straight_at for each index # if found, copy_straight returns cards used for straight def find_straight(hand, fs): for i in range(0, len(hand.cards) - 4): is_straight = is_straight_at(hand, i, fs) if is_straight == 1: # straight #print("INDEX:",str(i)) return copy_straight(hand, i, fs) pass for i in range(0, len(hand.cards) - 3): is_straight = is_straight_at(hand, i, fs) if is_straight == -1: #print("-1") # ace-low straight return copy_straight(hand, i, fs, True) pass return None # provided # builds hand with flush suit fs def build_flush(hand, fs): ans = Deck() i = 0 while len(ans.cards) < 5: assert i < len(hand.cards) if hand.cards[i].suit == fs: ans.add_card(hand.cards[i]) pass i += 1 pass return ans # provided def evaluate_hand(hand): # straight flush fs = find_flush(hand) #print(fs) straight = find_straight(hand, fs) #print(straight) if fs and straight: return straight, 'straight flush' # four of a kind val_counts = count_values(hand) v, n = get_max_count(hand, val_counts) #print(v,n) assert n <= 4 ind = get_kind_index(hand, v) #ind =5 if n == 4: #print(n) return build_of_a_kind(hand, 4, ind), 'four of a kind' # full house sec_pair = find_secondary_pair(hand, val_counts, v) if n == 3 and sec_pair >= 0: ans = build_of_a_kind(hand, 3, ind) ans = add_pair(hand, sec_pair, ans, 3) return ans, 'full house' # flush if fs: return build_flush(hand, fs), 'flush' # straight if straight: return straight, 'straight' # three of a kind if n == 3: return build_of_a_kind(hand, 3, ind), 'three of a kind' # two pair if n == 2 and sec_pair >=0: ans = build_of_a_kind(hand, 2, ind) ans = add_pair(hand, sec_pair, ans, 2) return ans, 'two pair' # pair if n == 2: return build_of_a_kind(hand, 2, ind), 'pair' # high card ans = Deck() ans.cards = hand.cards[0:5] return ans, 'high card' def num_from_rank(r): ranks = ['high card', 'pair', 'two pair', 'three of a kind', \ 'straight', 'flush', 'full house', \ 'four of a kind', 'straight flush'] return ranks.index(r) # returns positive if hand1 > hand2, # 0 for tie, or # negative for hand2 > hand1 def compare_hands(hand1,hand2): hand1.sort() hand2.sort() #print(hand1) #print(hand2) t1=evaluate_hand(hand1) t2=evaluate_hand(hand2) r1=num_from_rank(t1[1]) r2=num_from_rank(t2[1]) #print("RANK 1:",str(r1)) #print("RANK 2:",str(r2)) #print("ANS 1",t1[0]) if r1>r2: #print("hand 1 is better") return +1 elif r1<r2: #print("hand 2 is better") return -1 else: #high card a1=t1[0] a2=t2[0] teq=0 for i in range(len(a1.cards)): if a1.cards[i].value==a2.cards[i].value: teq += 1 elif a1.cards[i].value>a2.cards[i].value: #print("A1") return 1 else: #print("A2") return -1 if teq==5: #print("TIE") return 0 ''' d=Deck() d.add_card(Card('0','s')) d.add_card(Card('8','c')) d.add_card(Card('7','c')) d.add_card(Card('6','c')) d.add_card(Card('5','c')) d.add_card(Card('4','c')) d.add_card(Card('2','c')) d1=Deck() d1.add_card(Card('J','s')) d1.add_card(Card('0','c')) d1.add_card(Card('8','s')) d1.add_card(Card('7','c')) d1.add_card(Card('6','s')) d1.add_card(Card('5','h')) d1.add_card(Card('4','d')) ap=compare_hands(d,d1) print(ap) '''
7325fab2c63ab51785b543a9da9f0943daf7897f
MadJangE00/Algoritom_py
/chap06/binary_insort.py
650
3.921875
4
# ์ด์ง„ ์‚ฝ์ž… ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ตฌํ˜„ํ•˜๊ธฐ from typing import MutableSequence import bisect def binary_insertion_sort(a: MutableSequence) -> None: """ ์ด์ง„ ์‚ฝ์ž… ์ •๋ ฌ(bisect.insort ์‚ฌ์šฉ) """ for i in range(1, len(a)): bisect.insort(a, a.pop(i), 0, i) if __name__ == "__main__": print("์ด์ง„ ์‚ฝ์ž… ์ •๋ ฌ์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค.") num = int(input("์›์†Œ ์ˆ˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”.: ")) x = [None] * num for i in range(num): x[i] = int(input(f"x[{i}]")) binary_insertion_sort(x) print("์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ–ˆ์Šต๋‹ˆ๋‹ค.") for i in range(num): print(f"x[{i}] = {x[i]}")
ffa4c7acc3e2c8ba324859e2c6d23bc24b28d985
kju2/euler
/problem004.py
702
4.1875
4
""" A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99. Find the largest palindrome made from the product of two 3-digit numbers. """ from euler import is_palindromic def main(): """ >>> main() 906609 """ max_palindrom_number = 0 for multiplier in range(100, 1000): for multiplicand in range(multiplier, 1000): product = multiplier * multiplicand if is_palindromic(product) and product > max_palindrom_number: max_palindrom_number = product print(max_palindrom_number) if __name__ == "__main__": import doctest doctest.testmod()
575da21a38ff2e09c6ed5cf34348c92a1dfaa5e7
HBinhCT/Q-project
/hackerrank/Algorithms/Matrix Layer Rotation/solution.py
1,763
3.546875
4
#!/bin/python3 # Complete the matrixRotation function below. def matrixRotation(matrix, r): height = len(matrix) width = len(matrix[0]) for i in range(min(height // 2, width // 2)): state = [] # top-left to top-right for j in range(i, width - i): state.append(matrix[i][j]) # top-right to bottom-right for j in range(i + 1, height - 1 - i): # in Python, a[len(a) - 1 - i] = a[-1 - i] state.append(matrix[j][-1 - i]) # bottom-right to bottom-left for j in range(width - 1 - i, i - 1, -1): state.append(matrix[-1 - i][j]) # left-bottom to left-top for j in range(height - 2 - i, i, -1): state.append(matrix[j][i]) # rotate by R # no. of nodes no = 2 * (height - 2 * i) + 2 * (width - (2 * i + 2)) k = r % no state = state[k:] + state[:k] # populate A with rotated matrix same as above flag = 0 for j in range(i, width - i): matrix[i][j] = state[flag] flag += 1 for j in range(i + 1, height - 1 - i): matrix[j][-1 - i] = state[flag] flag += 1 for j in range(width - 1 - i, i - 1, -1): matrix[-1 - i][j] = state[flag] flag += 1 for j in range(height - 2 - i, i, -1): matrix[j][i] = state[flag] flag += 1 for row in matrix: print(*row, end=' ') print('') if __name__ == '__main__': mnr = input().rstrip().split() m = int(mnr[0]) n = int(mnr[1]) r = int(mnr[2]) matrix = [] for _ in range(m): matrix.append(list(map(int, input().rstrip().split()))) matrixRotation(matrix, r)
2b9b46e43510c0f42db08e01dd70d1d87af6e1bd
mccornet/leetcode_challenges
/Python/0448.py
1,322
3.5625
4
""" # 448. Find All Numbers Disappeared in an Array - https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ - Classification: Array ## Challenge Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums. ## Solution 1 See problem 442! First pass: mark the numbers visited, just like in p 422. Second pass: use list comprehension to return the mising numbers. ## Solution 2 Using a set instead of a mark negative pass, using more space """ class Solution: # Solution 1 def findDisappearedNumbers(self, nums: list[int]) -> list[int]: for n in nums: n_abs = abs(n) if nums[n_abs-1] > 0: nums[n_abs-1] *= -1 return [i+1 for i, n in enumerate(nums) if n>0] # Solution 2 def findDisappearedNumbers(self, nums: list[int]) -> list[int]: nums_set = set(nums) missing = [] for i in range(1, len(nums+1)): if i not in nums_set: missing.append(i) return missing # Solution 2.1 def findDisappearedNumbers(self, nums: list[int]) -> list[int]: nums_set = set(nums) return [i for i in range(1, len(nums)+1) if i not in nums_set]
31ec846065806b104d2c4802ea1cc1960fccee09
yangjiahao106/LeetCode
/Python3/513_ๆ‰พๆ ‘ๅทฆไธ‹่ง’็š„ๅ€ผ.py
1,186
3.875
4
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def __init__(self): self.max_depth = 0 self.res = 0 def findBottomLeftValue(self, root: TreeNode) -> int: """ ๆทฑๅบฆไผ˜ๅ…ˆ้ๅކ""" self.helper(1, root) return self.res def helper(self, depth, root: TreeNode): if root is None: return if depth > self.max_depth: self.max_depth = depth self.res = root.val self.helper(depth + 1, root.left) self.helper(depth + 1, root.right) from collections import deque class Solution2: def findBottomLeftValue(self, root: TreeNode) -> int: """ ๅนฟๅบฆไผ˜ๅ…ˆ้ๅކ ไปŽๅณ่พนๅพ€ๅทฆ้ๅކ """ if root is None: return q = deque([root]) q.append(root) node = root while len(q) > 0: node = q.popleft() if node.right: q.append(node.right) if node.left: q.append(node.left) return node.val
7bd38c348bbce4902dfd68272ae8aac992b28e6c
yannyappi/python_projects
/EchoBot.py
255
3.734375
4
print("Hi and welcome to EchoBot.") username = input("What is your name?") print("Hi "+username+". This chatbot will repeat what you will say.") stuff_to_echo = input("Please enter something to repeat") print("You said: "+stuff_to_echo) print("Bye bye.")
6295c9940fd60326123783b68e8dc7ef2f2e211a
muyurainy/interview
/bishi_code/tenxun_0405/tx_2.py
710
3.65625
4
def solution(): '''ๆถˆ้™ค็›ธ้‚ปไธๅŒ็š„ๅญ—็ฌฆ ่พ“ๅ…ฅ: 4 1100 Notes ----- ็›ดๆŽฅไปŽๅทฆๅˆฐๅณๅพช็ŽฏๅŽปๅˆคๆ–ญ ''' _, string = int(input()), input() old_length = 0 new_str = "" while old_length != len(string) and len(string) >= 2: index = 0 while index < len(string): if index == len(string) - 1: new_str += string[index] break if string[index] == string[index+1]: new_str += string[index] index += 1 else: index += 2 old_length = len(string) string = new_str new_str = "" print (len(string)) solution()
3096b4b5b19c4d80d73c49b2350c41a1f5edf72e
jos-h/Python_Exercises
/CSV_Excel_File_openpyxl.py
1,536
3.9375
4
from openpyxl import Workbook from openpyxl.utils import get_column_letter import csv def csv_Excel_conversion(csv_input_file): workbook = Workbook() # new workbook created with atleast one Worksheet worksheet = workbook.worksheets[0] worksheet.title = "a demo " # a variable to separate csv based on ',' csv_separator = ',' ''' register dialect as comma it can be anything ex:- :,|,# etc ''' csv.register_dialect('comma', delimiter=',') ''' itertating throughout the csv file and opening the file in read mode ''' with open(csv_input_file,"r") as csv_file: ''' will iterate through the csv file and return a string it's next() method is executed ''' reader = csv.reader(csv_file, dialect='comma') ''' enumerate returns value in tuple form (a,b) ''' for row_index, rows in enumerate(reader): for c, cols in enumerate(rows): for index, values in enumerate(cols.split(csv_separator)): ''' ws.cell() gets us the content from the specified cells ''' cell = worksheet.cell(row = row_index + 1, column = c + 1) cell.value = values index += 1 ''' OR #for column_index, cell in enumerate(rows): #column_letter = get_column_letter((column_index + 1 )) #worksheet.cell('%s%s'%(column_letter, (row_index + 1))).value = cell ''' workbook.save("D://macrocodesrequired//sample.xlsx") def main(): csv_Excel_conversion("D://macrocodesrequired//SampleCSVFile_119kb.csv") if __name__ == '__main__': main()
0589d11a523e8e118e953d8078136e0648932295
bazhenov4job/Algorithms_and_structures
/Lesson_09/homework/Task_02.py
1,515
3.828125
4
""" 2. ะ—ะฐะบะพะดะธั€ัƒะนั‚ะต ะปัŽะฑัƒัŽ ัั‚ั€ะพะบัƒ ะฟะพ ะฐะปะณะพั€ะธั‚ะผัƒ ะฅะฐั„ั„ะผะฐะฝะฐ. """ from collections import Counter, OrderedDict from binarytree import Node from copy import deepcopy def tree_search(tree, symbol, path=''): print(symbol, path, tree.value) if tree.value == symbol: print('ะฝะฐัˆั‘ะป', path) return path if tree.value == 0: path += '0' tree_search(tree.left, symbol, path) if tree.left != 0 and tree.left != symbol: path += '1' return tree_search(tree.right, symbol, path) def haffman_encode(string): counted_chars = Counter(string) ordered_chars = OrderedDict(sorted(counted_chars.items(), key=lambda x: x[1])) while len(ordered_chars) > 1: left_value = ordered_chars.popitem(last=False) right_value = ordered_chars.popitem(last=False) char_tree = Node(0) if type(left_value[0]) == str: char_tree.left = Node(ord(left_value[0])) else: char_tree.left = left_value[0] if type(right_value[0]) == str: char_tree.right = Node(ord(right_value[0])) else: char_tree.right = right_value[0] ordered_chars[deepcopy(char_tree)] = left_value[1] + right_value[1] my_tree = ordered_chars.popitem()[0] print(my_tree) symbols = counted_chars.keys() # binary_dict = {} path = tree_search(my_tree, 98) print(path) return 0 print(haffman_encode('abrakadabra'))
953d8db68446a752f138d7277015e63efe1b0f6b
BoomerLives/RabitHole
/Trivial_Python_Practice/Trivial/celsius_to_fahrenheit_Calderon.py
669
4.5
4
# Author: Nathan Calderon # File Name: celsius_to_fahrenheit_Calderon.py # This program converts a temperature entered in Celsius # to Fahrenheit. # User enters a temperature in Celsius. celsius_temp = float(input("Enter the temperature in \ Celsius and press enter: ")) # Celsius temperature converted to Fahrenheit calculation. fahrenheit_temp = (9/5)*celsius_temp+32 # Display the results entered and calculated. # Results displayed with one significant digits. print("The Celsius temperature of", celsius_temp, "is", \ format(fahrenheit_temp, ",.1f"), "Fahrenheit") input("Press enter to continue...") # Imputs used: 21, 0, -12 # Outputs respectively: 69.8, 32, 10.4
26e3014ab03ebc0e1dd369d5e31f76e07bd8413e
cittie/Leetcode---Python
/048. Rotate Image.py
709
3.609375
4
class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ n = len(matrix) for row in range(n >> 1): for column in range(row, n - row - 1): # swap each two nearby points queue = [(column, row), (row, n - 1 - column), (n - 1 - column, n - 1 - row), (n - 1 - row, column)] first = queue.pop() while queue: second = queue.pop() matrix[first[1]][first[0]], matrix[second[1]][second[0]] = matrix[second[1]][second[0]], matrix[first[1]][first[0]]
db7b4f62d86f8370b124cc29d50a965c03c3a98d
SURAJTHEGREAT/vector_udacity_khan_python
/Linear_Algebra/vector_product.py
3,014
4.09375
4
"""http://interactivepython.org/courselib/static/pythonds/Introduction/ObjectOrientedProgramminginPythonDefiningClasses.html - to know more about str and eq ... str is used to know what needs to be done when print method is called and _eq_ is to find equal to and http://stackoverflow.com/questions/16548584/adding-two-tuples-elementwise for add - i have used izip since sub is not supported using map and operator """ #from itertools import izip from operator import add,sub,mul import math """https://www.tutorialspoint.com/python/number_pow.htm - for computing square""" class Vector(object): def __init__(self, coordinates): try: if not coordinates: raise ValueError self.coordinates = tuple(coordinates) self.dimension = len(coordinates) except ValueError: raise ValueError('The coordinates must be nonempty') except TypeError: raise TypeError('The coordinates must be an iterable') def __str__(self): return 'Vector: {}'.format(self.coordinates) def __eq__(self, v): return self.coordinates == v.coordinates def __add__(self,other): a=self.coordinates b=other.coordinates c=(map(add,a,b)) return Vector(c) def __sub__(self,other): a=self.coordinates b=other.coordinates c=(map(sub,a,b)) return Vector(c) """ This is multipication of vector function """ def multiply(self,Y): c=(sum(a*b for a,b in zip(self.coordinates,Y.coordinates))) return c def scalar_mul(self,other): c=[other*x for x in self.coordinates] return Vector(c) def magnitude(self): c=math.sqrt(sum(math.pow(x,2) for x in self.coordinates)) return c def normalized(self): d=self.magnitude() e=self.scalar_mul(1/d) return e def angle(self,Y): a=self.multiply(Y) d=self.magnitude() e=Y.magnitude() f=a/(d*e) g=math.acos(f) return g my_vector_prod_1 = Vector([7.887,4.138]) my_vector_prod_2 = Vector([-8.802,6.776]) my_vector_prod_3 = Vector([-5.955,-4.904,-1.874]) my_vector_prod_4 = Vector([-4.496,-8.755,7.103]) my_vector_ang_1 = Vector([3.183,-7.627]) my_vector_ang_2 = Vector([-2.668,5.319]) my_vector_ang_3 = Vector([7.35,0.221,5.188]) my_vector_ang_4 = Vector([2.751,8.259,3.985]) my_vector_test=Vector([1,2,3]) dot_product1=my_vector_prod_1.multiply(my_vector_prod_2) print dot_product1 dot_product2=my_vector_prod_3.multiply(my_vector_prod_4) print dot_product2 angle1=my_vector_ang_1.angle(my_vector_ang_2) print angle1 angle2=my_vector_ang_3.angle(my_vector_ang_4) angle_degree=math.degrees(angle2) print angle_degree dot_product_zero=my_vector_test.multiply(my_vector_test) print dot_product_zero angle2=my_vector_test.angle(my_vector_test) angle_degree=math.degrees(angle2) print angle_degree
1b7412e75bd42b0c7fa4004b605b82f2b482a48b
PriyathamRaj/MITx-6.00.2x-Introduction-to-Computational-Thinking-and-Data-Science
/Midterm/max_contig_sum.py
572
4
4
# -*- coding: utf-8 -*- """ Created on Mon Apr 17 16:28:00 2017 @author: Priyatham """ def max_contig_sum(L): """ L, a list of integers, at least one positive Returns the maximum sum of a contiguous subsequence in L """ max_so_far = 0 sub_sum = 0 for i in range(len(L)): sub_sum += L[i] if sub_sum > max_so_far: max_so_far = sub_sum elif sub_sum < 0: sub_sum = 0 return max_so_far L = [-2,-3,4,-1,-2,1,5,-3] print(max_contig_sum(L))
2260580e977d51549f7081574acc29cf56253f6a
kamiruizdiaz/Projeto-Pedra-papel-e-tesoura
/jokenpo.py
1,163
3.71875
4
import random print("JOGO PEDRA PAPEL E TESOURA \nOpรงรตes:\n0-Pedra \n1-Papel\n2-Tesoura") opcoes = ['pedra', 'papel', 'tesoura'] jogada_computador = random.choice(opcoes) jogadaUsuario=int(input("Digite a sua jogada: ")) if jogada_computador == "pedra": print("O computador escolheu: Pedra") if jogadaUsuario == 0: print("Empatou!") elif jogadaUsuario == 1: print("Uhull!! Vocรช ganhou!") elif jogadaUsuario == 2: print("Vocรช perdeu!") else: print("Nรบmero invalido") elif jogada_computador == "papel": print("O computador escolheu: Papel") if jogadaUsuario == 0: print("Vocรช perdeu!") elif jogadaUsuario == 1: print("Empate!") elif jogadaUsuario == 2: print("Uhull!! Vocรช ganhou!") else: print("Nรบmero invalido") elif jogada_computador == "tesoura": print("O computador escolheu: Tesoura") if jogadaUsuario == 0: print("Uhull!! Vocรช ganhou!") elif jogadaUsuario == 1: print("Vocรช perdeu!") elif jogadaUsuario == 2: print("Empate!") else: print("Nรบmero invalido") else: print("Nรบmero invalido")
b319b3b87021bc4cf08a8c45151177273f9ac2c3
wellqin/USTC
/PythonBasic/base_pkg/python-06-stdlib-review/chapter-05-Mathematics/5.3-random/py_02_randomGenerate.py
624
3.5
4
import sys, random sys.path.append('.') from pkg.breaker import addBreaker @addBreaker def random_randomm(): for _ in range(5): print('%04.3f' % random.random(), end=' ') return @addBreaker def random_uniform(): for _ in range(5): print('%04.3f' % random.uniform(1, 100), end=' ') return if __name__ == "__main__": # using random.random() if wanted float numbers 0<= n <1. normal distribution random_randomm() # using random.uniform() if wanted float numbers in x< n <y. # ! random.uniform() implementation formula `min + (max - min) * random.random()` random_uniform()
a334d55ff91c7b12d218ccc8bc7d6cc4f47d7f7b
gutpdn/2D
/Data-Structure/Graph/Traversals.py
1,916
3.515625
4
class Graph: def __init__(self, graphList): self.weight = dict() for node in graphList: self.weight[node] = [] def edge(self, prede, suc, weight = 1): if suc not in self.weight[prede]: self.weight[prede].append(suc) self.weight[suc].append(prede) def graphInArray(self): print(f' ', end = '') for node in self.weight: print(node, end = ' ') print() for node in self.weight: i = 0 print(f"{node} : ", end = '') for check in self.weight: found = False for item in self.weight[node]: if item is check: found = True break i += 1 if found == True: print('1', end = '') else: print('0', end = '') if i < len(self.weight): print(', ', end='') print() def dfs(self, vertex, visited = []): if vertex not in visited: print(vertex, end = ' ') visited.append(vertex) for node in self.weight[vertex]: if node not in visited: self.dfs(node, visited) def bfs(self): visited = [] for vertex in self.weight: if vertex not in visited: print(vertex, end = ' ') visited.append(vertex) for s in self.weight[vertex]: if s not in visited: print(s, end = ' ') visited.append(s) lst = input("Enter : ").split(',') vertex_lst = [] for data in lst: src, dest = data.split() if src not in vertex_lst: vertex_lst.append(src) if dest not in vertex_lst: vertex_lst.append(dest) vertex_lst = sorted(vertex_lst) g = Graph(vertex_lst) for data in lst: src, dest = data.split() g.edge(src, dest) print('Depth First Traversals : ',end = '') for i in vertex_lst: g.dfs(i) print('\nBredth First Traversals : ',end = '') g.bfs()
62774e4d3b2617638c114b267a2af0773b246c47
CaesarWattsHall/TurtleGraphics4
/Turtle Design.py
310
3.890625
4
# Python program to draw # Rainbow Benzene # using Turtle Programming import turtle colors = ['#05668d', '#028090', '#00a896', '#02c39a', '#f0f3bd', '#FFFFFF'] t = turtle.Pen() turtle.bgcolor('#000000') for x in range(360): t.pencolor(colors[x%6]) t.width(x/100 + 1) t.forward(x) t.left(59)
a15c60d402cbbaed63e20e48365fc8b32fb9bcf6
MDGSF/JustCoding
/python-leetcode/69.01.py
172
3.5625
4
class Solution: # ็‰›้กฟ่ฟญไปฃๆณ• def mySqrt(self, x: int) -> int: if x <= 1: return x r = x while r * r > x: r = (r + x // r) // 2 return int(r)
3aceefcd3b461521b4b0f5f28c07808be05a72e3
wulfebw/algorithms
/scripts/recursion/power_set.py
481
3.890625
4
def power_set(s): ''' the idea is that you either include each item in the set or you do not and for both options you have to collect all future sets O(2^n) ''' if len(s) == 0: return [''] else: suffixes = power_set(s[1:]) sets = suffixes sets += [s[0] + suf for suf in suffixes] return sets if __name__ == '__main__': inputs = [ 'asdfghj' ] for i in inputs: print(power_set(i))
6572067870582b31d37413649cd5632d07906768
Boy0211/dataprocessing
/week6/data/convertCSV2JSON.py
1,130
3.515625
4
import pandas as pd import copy filename_IN = "RPOP_15122018150449599.csv" filename_OUT = "data_final.csv" def open_data(filename): df = pd.read_csv(filename, sep=',') return df def process_data(df): countrys = [] years = [] genders = [] population = [] print(df) for i in range(len(df)): if df.loc[i]["Gender"] == "Total males+females": countrys.append(df.loc[i]["Country"]) years.append(df.loc[i]["Year"]) genders.append(df.loc[i]["Gender"]) population.append(df.loc[i]["Value"]) new_df = pd.DataFrame( {'country': countrys, 'year': years, 'population': population }) # new_df = new_df.drop(index='Males', level=1) # new_df = new_df.drop(index='Females', level=1) # df = df.set_index("country") print(new_df) return new_df def write_JSON(df): print(df) df.to_csv(filename_OUT, index=False) if __name__ == '__main__': df = open_data(filename_IN) df = process_data(df) write_JSON(df)
06ccf17e2d704e35ae7824739cbfeeb2cdb486ad
sahiljajodia01/Competitive-Programming
/leet_code/container_with_most_water.py
612
3.53125
4
# https://leetcode.com/explore/interview/card/top-interview-questions-hard/116/array-and-strings/830/ ###### Two pointer approach ####### class Solution: def maxArea(self, height: List[int]) -> int: count1 = 0 count2 = len(height)-1 max_ = 0 while count1 < count2: area = (min(height[count1], height[count2]) * (count2 - count1)) if area > max_: max_ = area if height[count1] <= height[count2]: count1 += 1 else: count2 -= 1 return max_
4d060835ff653a6a2262ed47b5a4146325583935
brjatoba92/exercicios
/salarios.py
1,436
4.03125
4
#Desconto salario_bruto = float(input('Digite o salario:')) sindicato = 0.03 fgts = 0.11 inss = 0.1 valor_sindicato = salario_bruto valor_fgts = salario_bruto * fgts valor_inss = salario_bruto * inss #descontos_primarios = valor_fgts + valor_inss + valor_sindicato """ IR = 900 ==> ISENTO 1500 ==> -5% 2500 ==> -10% ACIMA DE 2500 ==> -20% """ if salario_bruto <= 900: #ir = salario_bruto * 0.05 descontos = valor_inss salario_liquido = salario_bruto - (descontos) elif salario_bruto > 900 and salario_bruto <= 1500: ir = 0.05 valor_ir = salario_bruto * ir descontos = valor_inss + valor_ir salario_liquido = salario_bruto - descontos elif salario_bruto > 1500 and salario_bruto <= 2500: ir = 0.1 valor_ir = salario_bruto * ir descontos = valor_fgts + valor_inss + valor_sindicato + valor_ir salario_liquido = salario_bruto - descontos else: ir = 0.20 valor_ir = salario_bruto * ir descontos = valor_inss + valor_ir salario_liquido = salario_bruto - descontos print('Salario bruto: ') print(salario_bruto) if salario_bruto <= 900: pass else: print('Imposto de Renda: ') print(valor_ir) print('FGTS: ') print(valor_fgts) print('INSS') print(valor_inss) print('Descontos: ') print(descontos) print('Salario Liquido: ') print(salario_liquido) print('Custo do empregador:') custo_empregador = salario_bruto + valor_fgts print(custo_empregador)
1febad598012f7d273a8c0112937e3083a334882
qwrrty/adventofcode2019
/adv14.py
3,198
3.984375
4
#! /usr/bin/env python3 import math # A reaction is expressed as: # - Reaction.chemical (the output chemical) # - Reaction.quantity (the output quantity) # - Reaction.ingredients (a hash of chemicals and quantities # that go into this reaction) class Reaction(object): def __init__(self, chemical, quantity, ingredients): self.chemical = chemical self.quantity = quantity self.ingredients = ingredients def __repr__(self): return "<Reaction {} quantity={} ingredients={}>".format( self.chemical, self.quantity, self.ingredients) class ReactionChart(object): def __init__(self, text): chart = {} for line in text.split("\n"): if not line: continue requirement, result = line.split(" => ") chemical, amt = ReactionChart.parse_reactant(result) ingredients = {} for s in requirement.split(", "): c, q = ReactionChart.parse_reactant(s) ingredients[c] = q chart[chemical] = Reaction(chemical, amt, ingredients) self.chart = chart def from_file(filename="adv14_input.txt"): with open(filename, "r") as f: return ReactionChart(f.read()) def parse_reactant(s): amt, chem = s.split(" ") return chem, int(amt) def calculate_requirements(chart, target_chemical="FUEL", target_quantity=1): orders = [] orders.append((target_chemical, target_quantity)) supply = {} # Leftover chemicals from previous reactions ore = 0 while orders: chem, quantity = orders.pop(0) if chem == "ORE": ore += quantity continue reaction = chart.chart[chem] # If we have any of this chem on hand, reduce it appropriately if chem in supply: supply_amt = supply[chem] if supply_amt >= quantity: # We have enough on hand to satisfy this order supply[chem] -= quantity if supply_amt == quantity: del supply[chem] continue elif supply_amt < quantity: quantity -= supply_amt del supply[chem] # How many times must this reaction be run to obtain the necessary quantity? multiple = math.ceil(quantity / reaction.quantity) # How much chemical will be left over after it runs? leftover = (reaction.quantity * multiple) - quantity # Place orders for the new ingredients, adjusting supply on hand as necessary for ingredient_chem, ingredient_amt in reaction.ingredients.items(): orders.append((ingredient_chem, ingredient_amt * multiple)) # Record any excess of this chemical after this order is fulfilled if leftover: supply[chem] = leftover return ore def part1(): chart = ReactionChart.from_file() print(calculate_requirements(chart)) def part2(): chart = ReactionChart.from_file() print(calculate_requirements(chart, target_quantity=2521844))
813b557d9c022089db2a8a8bb9402ad2dfa62539
khaledmohamed00/Deeplearning.ai_specialization_coursera
/deeplearning.ai_specialization_coursera/ANN/untitled0.py
4,281
3.671875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 3 10:19:15 2019 @author: khaled """ import numpy as np import matplotlib.pyplot as plt from gradient_checking import gradient_checking def sigmoid_prime(z): """Derivative of the sigmoid function.""" return sigmoid(z)*(1-sigmoid(z)) def relu(x): s = np.maximum(0,x) return s def sigmoid(x): return 1/(1+np.exp(-x)) def sigmoid_der(x): return sigmoid(x) *(1-sigmoid (x)) def softmax(A): expA = np.exp(A) return expA / expA.sum(axis=1, keepdims=True) def init_weights(network): weights={} biases={} for l in range(len(network)-1): weights['w'+str(l+1)]=np.random.randn(network[l],network[l+1])*np.sqrt(2 / network[l]) biases['b'+str(l+1)]=np.random.randn(1,network[l+1])*0.01 return weights,biases def forward_prop(X,weights,biases,activation_function='sigmoid'): L=len(weights) a=X activations=[] Zs=[] activations.append(a) for l in range(L-1): z=np.dot(a,weights['w'+str(l+1)])+biases['b'+str(l+1)] if activation_function=='relu': a=relu(z) elif activation_function=='sigmoid': a=sigmoid(z) activations.append(a) Zs.append(z) z=np.dot(a,weights['w'+str(L)])+biases['b'+str(L)] a=softmax(z) activations.append(a) Zs.append(z) return activations,Zs def cost_function(a,y): m=a.shape[0] return (1.0*np.sum(-y * np.log(a)))/m def back_prop(weights,activations,Zs,y,m,activation_function='sigmoid'): grad={} L=len(weights) dz = activations[-1] - y dw= (1./m)*np.dot(activations[-2].T, dz) db= (1./m)*np.sum(dz,axis=0,keepdims = True) grad['w'+str(L)]=dw grad['b'+str(L)]=db for i in reversed(range(1,L)): da= np.dot(weights['w'+str(i+1)], dz.T) dz = np.multiply(da.T, np.int64(activations[i] > 0)) if activation_function =='relu': dz = np.multiply(da.T, np.int64(activations[i] > 0)) elif activation_function =='sigmoid': dz =np.multiply(da.T,sigmoid_prime(Zs[i-1])) dw = 1./m *np.dot(activations[i-1].T,dz) db = 1./m *np.sum(dz, axis=0, keepdims = True) grad['w'+str(i)]=dw grad['b'+str(i)]=db return grad def update_params(weights,biases,grad,learning_rate): L=len(weights) for l in range(L): weights['w'+str(l+1)] -= learning_rate * grad['w'+str(l+1)] biases['b'+str(l+1)] -= learning_rate * grad['b'+str(l+1)]#.sum(axis=0) N = 100 # number of points per class D = 2 # dimensionality K = 3 # number of classes X = np.zeros((N*K,D)) # data matrix (each row = single example) y = np.zeros(N*K, dtype='uint8') # class labels for j in range(K): ix = range(N*j,N*(j+1)) r = np.linspace(0.0,1,N) # radius t = np.linspace(j*4,(j+1)*4,N) + np.random.randn(N)*0.2 # theta X[ix] = np.c_[r*np.sin(t), r*np.cos(t)] y[ix] = j y=y.reshape(X.shape[0],1) m = X.shape[0] input_dim = X.shape[1] hidden_nodes = 4 output_labels = 3 network=[input_dim,50,20,3] lr = 0.01 weights,biases=init_weights(network) np.random.seed(0) m=X.shape[0] shuffled_indx=[np.random.permutation(m)] X=X[shuffled_indx,:].reshape(m,-1) y=y[shuffled_indx,:].reshape(m,-1) y_hot=np.zeros([m,K]) for i in range(m): y_hot[i][y[i]]=1 #feature_set=X one_hot_labels=y_hot ''' error_cost = [] for epoch in range(5000): activations,Zs=forward_prop(X,weights,biases) grad=back_prop(weights,activations,Zs,y_hot,m) update_params(weights,biases,grad,lr) if epoch % 200 == 0: loss = cost_function(activations[-1],one_hot_labels)#np.sum(-one_hot_labels * np.log(activations[-1])) print('Loss function value: ', loss) error_cost.append(loss) plt.plot(error_cost) #Show the plot plt.show() scores,zs = forward_prop(X,weights,biases) predicted_class = np.argmax(scores[-1], axis=1) print ('training accuracy: %.2f' % (np.mean(predicted_class.reshape(y.shape) == y))) ''' activations,Zs=forward_prop(X,weights,biases) grad=back_prop(weights,activations,Zs,y_hot,m) gradient_checking(weights,biases,network, grad, X, y_hot,forward_prop,cost_function,epsilon=1e-7)
414c90484032eb0395f0f16fc6d2e5ce381ae550
justcallmelarry/advent-of-code-2019
/03/a.py
1,677
3.71875
4
import os from collections import * from utils import get_actual from utils import * def calc(x, y, grid): grid[f"{x}:{y}"] = i if grid.get(f"{x}:{y}") in (None, i) else True if __name__ == "__main__": day = os.path.dirname(os.path.abspath(__file__)).rsplit("/", 1)[-1] _input = get_actual(day=int(day), year=2019).splitlines() table = [] middle = (0, 0) for row in _input: table.append(row.split(",")) grid = {} for i, row in enumerate(table): x, y = middle grid[f"{x}:{y}"] = "o" for cell in row: if "U" in cell: for _ in range(int(cell[1:])): x += 1 calc(x, y, grid) if "D" in cell: for _ in range(int(cell[1:])): x -= 1 calc(x, y, grid) if "R" in cell: for _ in range(int(cell[1:])): y += 1 calc(x, y, grid) if "L" in cell: for _ in range(int(cell[1:])): y -= 1 calc(x, y, grid) shortest = -1 shortest_coords = "0:0" crossings = set() for k, v in grid.items(): if v is True: crossings.add(k) if shortest < 0: shortest = manhattan_dist(middle, ints(k)) shortest_coords = k continue dist = manhattan_dist(middle, ints(k)) if dist < shortest: shortest = dist shortest_coords = k print(crossings) # print to use in the next puzzle print(shortest_coords, shortest)
f8548e3bd4c1c0cbde60e03c84bbe4a0bc17b69e
uvsq22004753/l1-python_2020_2021
/exercises/TD3_fonctions/TD3.py
6,145
3.53125
4
import sys import time def tempsEnSeconde(temps): """ Renvoie la valeur en seconde du temps donnรฉ comme \ (jours, heures, minutes, secondes).""" return 86400 * temps[0] + 3600 * temps[1] + 60 * temps[2] + temps[3] def secondeEnTemps(seconde): """on donne un temps en seconde et la fonction renvoie un tuple \ (jours, heures, minutes, secondes)""" vraies_secondes = seconde % 60 minutes = seconde // 60 vraies_minutes = minutes % 60 heures = minutes // 60 vraies_heures = heures % 24 vraies_jours = heures // 24 return (vraies_jours, vraies_heures, vraies_minutes, vraies_secondes) print(secondeEnTemps(1000000000)) def afficheTemps(temps): """" renvoie le tuple sous la forme d'une chaรฎne de caractรจre""" valeurs = ["jour", "heure", "minute", "seconde"] affichage = " " for i, j in zip(temps, valeurs): if i == 1: affichage = affichage + str(i) + " " + j + " " elif i > 1: affichage = affichage + str(i) + " " + j + 's' + " " print(affichage) def demandeTemps(): """ demande ร  l'utilisateur de rentrer un temps et sort un tuple \ (jours, heures, minutes, secondes). Si les valeurs sont mal rentrรฉes, \ renvoie d'un message d'erreur""" donnees = [] demande = 0 consigne = ("jours", "heures", "minutes", "secondes") for i, j in zip(range(0, 4), consigne): phrase_consigne = "entrer un nombre de" + " " + j demande = int(input(phrase_consigne)) if (i == 0 and demande >= 0) or (i == 1 and 0 <= demande < 24) \ or (i == 2 and 0 <= demande < 60) \ or (i == 3 and 0 <= demande < 60): donnees += [demande] else: sys.exit("erreur de saisie") return tuple(donnees) def demandeTemps2(): """ demande ร  l'utilisateur de rentrer un temps et sort un tuple\ (jours, heures, minutes, secondes). Si les valeurs sont mal rentrรฉes, \ redemande ร  l'utilisateur de les rentrer""" donnees = [] demande = 0 consigne = ("jours", "heures", "minutes", "secondes") for i, j in zip(range(0, 4), consigne): phrase_consigne = "entrer un nombre de" + " " + j demande = int(input(phrase_consigne)) while not ((i == 0 and demande >= 0) or (i == 1 and 0 <= demande < 24)\ or (i == 2 and 0 <= demande < 60) \ or (i == 3 and 0 <= demande < 60)): demande = int(input(phrase_consigne)) donnees += [demande] return tuple(donnees) def sommeTemps(temps1, temps2): """ additionne deux temps et renvoie un tuple""" somme_temps = tempsEnSeconde(temps1) + tempsEnSeconde(temps2) return secondeEnTemps(somme_temps) def proportionTemps(temps, proportion): """ renvoie la proportion d'un temps sous la forme d'un tuple""" temps_seconde = tempsEnSeconde(temps) temps_proportionnรฉ_seconde = temps_seconde * proportion return secondeEnTemps(temps_proportionnรฉ_seconde) def tempsEnDate(temps): """ donne la date sous la forme \ (annรฉe, jours, heures, minutes, secondes)""" annee = temps[0] // 365 jours = temps[0] % 365 return (1970 + annee, jours + 1, temps[1], temps[2], temps[3]) def afficheDate(date): """affiche la date selon ce modรจle : jours mois annรฉes \ heures minutes secondes""" mois = ["janvier", "fรฉvrier", "mars", "avril", "mai", "juin", "juillet",\ "aoรปt", "septembre", "octobre", "novembre", "dรฉcembre"] jours_mois = [31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365] valeurs = ["heure", "minute", "seconde"] affichage = " " for i in range(0, len(jours_mois) + 1): if i == 0 and date[1] <= jours_mois[1]: affichage = affichage + str(date[1]) + " " + mois[i] + " " + str(date[0]) + " " elif i > 0 and jours_mois[i - 1] < date[1] <= jours_mois[i]: affichage = affichage + str(date[1]-jours_mois[i-1]) + " " + mois[i] + " " + str(date[0]) + " " for i, j in zip(date[2:], valeurs): if i == 1: affichage = affichage + str(i) + " " + j + " " elif i > 1: affichage = affichage + str(i) + " " + j + 's' + " " print(affichage) def bisextile(jours): """affiche toutes les annรฉes bissextiles entre 1970 et \ 1970 plus un nombre de jours donnรฉ""" annee = 1970 + (jours // 365) annee_bisextile = [] for i in range(1970, annee + 1): if (int(i) % 4 == 0) and (int(i) % 100 != 0 or (int(i) % 100 == 0 and int(i) % 400 == 0)): annee_bisextile += [i] return annee_bisextile def nombreBisextile(jour): """compte le nombre d'annรฉes bissextiles""" return len(bisextile(jour)) def tempsEnDateBisextile(temps): """ donne la date sous la forme (annรฉe, jours, heures, minutes, secondes)\ en prenant en compte les annรฉes bissextiles """ annee = (temps[0] - nombreBisextile(temps[0])) // 365 jours = (temps[0] - nombreBisextile(temps[0])) % 365 return (1970 + annee, jours + 1, temps[1], temps[2], temps[3]) def afficheDate2(date=tempsEnDateBisextile(secondeEnTemps(int(time.time())))): """affiche la date en temps rรฉel selon ce modรจle :\ jours mois annรฉes heures minutes secondes""" mois = ["janvier", "fรฉvrier", "mars", "avril", "mai", "juin", "juillet",\ "aoรปt", "septembre", "octobre", "novembre", "dรฉcembre"] jours_mois = [31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365] valeurs = ["heure", "minute", "seconde"] affichage = " " for i in range(0, len(jours_mois) + 1): if i == 0 and date[1] <= jours_mois[1]: affichage = affichage + str(date[1]) + " " + mois[i] + " " + str(date[0]) + " " elif i > 0 and jours_mois[i - 1] < date[1] <= jours_mois[i]: affichage = affichage + str(date[1]-jours_mois[i-1]) + " " + mois[i] + " " + str(date[0]) + " " for i, j in zip(date[2:], valeurs): if i == 1: affichage = affichage + str(i) + " " + j + " " elif i > 1: affichage = affichage + str(i) + " " + j + 's' + " " print(affichage)
53c826707335e8eb20e99f915de7cc5aaf202dfb
logriffith/CS0
/notes/notes.py
3,499
3.890625
4
### Notes From CSCI 110 class #### """ a=10 print(float(a)) b='10' print(a*float(b)) 3 in binary is 11. 1(2)^1+2^0=3 round(area, 4) rounds area to 4 decimal points def getData(): s1=input("What is the first number") s2=input("What is the second number") s3=input("What is the thrid number") # does it form a triangle # if it does return s1,s2,s3 def main(): s1,s2,s3=getData() #find perimeter #find area #display results while True: main() ans=input('Want to test more? [y/n]: ') if ans!='y': break ## for loops for val in range of values: # loop body print(list(range(1,11,2))) 2 is th step size first parameter is the start:1 second parameter is the stop:11 thrid parameter is the step size:2 for i in range(1,11): print(i,"Hello World") # this will output 1 Hello World for num in range(20): print(num) output is print 0 print 1 . . . print 19 for num in range(20): print(num, end=' ') output is 0 1 ... 19 for i in range(1,11): #range 1...10 if i%2==0: continue #continue means to go to the next i print(i) output is 1 3 5 7 9 i.e. if i is odd, then the conditional is not met and i is printed for i in range(1,11): continue print(i) output is nothing for i in range(10): if i==5: #same output if i>4 break print(i) print('done') output is 0 1 2 3 4 done ## break ends the loop local variables are only inside functions, otherwise global for i in range(5): print(i) if i==2 break else: print('end!') output is 0 1 2 else is part of the for loop like if and elif go together n=97 for i in range(2,n//2+1): if n%i==0: print(n, 'is not prime') break else: print(n, 'is prime') output is '107 is prime' python has only while loops and for-loops i+=1 means i=i+1 randint ##needs random library ################################# import time import os def ClearScreen(): if os.name=='nt': os.system('cls') else: os.system('clear') print(count) for i in range(10,0,-1): print(i) time.sleep(1) ClearScreen() ClearScreen() print('Blast off!') ################################ Write a program that prints numbers betweeen 1 and 100 with the following requirements. If the number is divisible by 3, print "Fizz". If the number is divisible by 5, print "Buzz". If the number is divisible by both 3 and 5, print "FizzBuzz". for i in range(1,101): if i%3==0 and i%5==0: print('FizzBuzz') elif i%3==0: print('Fizz') elif i%5==0: print('Buzz') else: print(i) def fizzbuzz(i): if i%3==0 and i%5==0: return 'FizzBuzz' elif i%3==0: return 'Fizz' elif i%5==0: return 'Buzz' else: return i for num in range (1,101): print(fizzbuzz(num)) def test(): assert fizzbuzz(1)==1 assert fizzbuzz(100)=='Buzz' assert fizzbuzz(15)=='FizzBuzz' assert fizzbuzz(3)=='Fizz' print("all test cases passed!") ########################### for ## if break in for-loop is executed, then else is not executed else for c in 'hello': print(c, end=' ') outputs h e l l o def answer(num): if num%2==0: return f'{num} is even' else: return f'{num} is odd' answer(-10) will output '-10 is even' Lists def getData(): pieces = int(input()) values =[] for i in range(pieces): values.append(float(input())) return values """
70cf595883fe72b65200c246a37dc881c29556c8
Djerys/logy
/interpreter.py
4,935
3.578125
4
import sys import cmd import boolean_lexer as blex from boolean_parser import parse from calculation import BooleanCalculator, ConstantError class CalculatorInterpreter(cmd.Cmd): def __init__(self): cmd.Cmd.__init__(self) self.calculator = None self.prompt = '> ' self.intro = ('-----------*-----------Logy-----------*-----------\n\n' 'Logy is a boolean calculator with console interface.\n' 'Use the command "help" to learn more:\n' ' ***\n') self.doc_leader = ('Logy allows such boolean operations as:\n' '=======================================\n' f'NOT {blex.NOT}\n' f'AND {blex.AND}\n' f'OR {blex.OR}\n' f'NAND {blex.NAND}\n' f'NOR {blex.NOR}\n' f'EQ {blex.EQ}\n' f'IMPLY {blex.IMPLY}\n' 'Some expressions for example:\n' '=============================\n' '-(a + b) -> c\n' 'a + b * c ^ 1 <-> 0\n' 'a / b ! c / a\n\n' 'You can use the help command to learn what other\n' 'commands are doing.\n' 'For example:\n' '============\n' '> table a + b * c -> -d\n' '> help load\n' '> load a + b * c -> -d\n' '> table') self.doc_header = 'Commands you can use:' def do_load(self, expression): """# Loads function and allows write commands without arguments.""" try: self.calculator = get_calculator(expression) except ValueError: print('! Expression is not correct') else: print('# Function loaded successfully.') def do_loaded(self, empty): """# Returns loaded function or warning message.""" if self.calculator: print(self.calculator.function) else: print('! No loaded function.') def do_table(self, expression): """# Builds truth table for function.""" self._handle_optional_command( expression, lambda: print_table(get_calculator(expression).build_truth_table()), lambda: print_table(self.calculator.build_truth_table())) def do_fdnf(self, expression): """# Casts function to FCNF (full conjunctive normal form).""" self._handle_optional_command( expression, lambda: print(get_calculator(expression).cast_to_fdnf()), lambda: print(self.calculator.cast_to_fdnf())) def do_fcnf(self, expression): """# Casts function to FDNF (full disjunctive normal form).""" self._handle_optional_command( expression, lambda: print(get_calculator(expression).cast_to_fcnf()), lambda: print(self.calculator.cast_to_fcnf())) def do_poly(self, expression): """# Casts function to Zhegalkin polynomial.""" self._handle_optional_command( expression, lambda: print(get_calculator(expression).cast_to_zhegalkin()), lambda: print(self.calculator.cast_to_zhegalkin())) def do_min(self, expression): """# Minimizes function using Quineโ€“McCluskey algorithm.""" self._handle_optional_command( expression, lambda: print(get_calculator(expression).minimize()), lambda: print(self.calculator.minimize()) ) def do_close(self, empty): """# Closes Logy.""" sys.exit() def default(self, line): print('! Unknown command.') def _handle_optional_command(self, expression, standard_option, loaded_option): try: if expression: try: standard_option() except ValueError: print('! Expression is not correct') elif self.calculator: loaded_option() else: print('! No arguments and no loaded function.') except ConstantError as error: print(f'! Function always takes one value: {error.args[-1]}.') def get_calculator(expression): tokens = blex.lex(expression) function = parse(tokens) return BooleanCalculator(function) def print_table(table): for variable in table[0]: print(variable, end='\t') print() for row in table: for variable in row: separator = ' ' * (len(variable) // 2) print(separator, row[variable], end='\t', sep='') print()
76a1c118aca42e1f388fc34fa86f73947a09f119
zuikaru/2110101_Com_Prog_2018_2
/12/12_P2.py
752
3.546875
4
class ComplexNum: def __init__(self,re,im): self.re = re self.im = im def __str__(self): if self.im >= 0: return str(self.re) + '+' + str(self.im) + 'i' return str(self.re) + str(self.im) + 'i' def absolute(self): ab = (self.re**2+self.im**2)**0.5 return round(ab,2) def add(self,other): return ComplexNum(self.re+other.re,self.im+other.im) def conjugate(self): return ComplexNum(self.re,-1*self.im) a,b,c,d = [int(e) for e in input().strip().split()] complex1 = ComplexNum(a, b) complex2 = ComplexNum(c, d) print(complex1, complex1.conjugate(), complex1.absolute()) print(complex2, complex2.conjugate(), complex2.absolute()) print(complex1.add(complex2))
10cd8e81e95d122853e62d0a60118b3ff0366f1c
JaySutcliffe/Group-Project
/Control/s.py
1,340
3.515625
4
import socket # run on pi # HOST = '10.42.0.1' #USB interface to EV3 HOST = '192.168.137.1' # HOST = 'localhost' PORT = 65432 class Server: # Sets up server socket and accepts connection def __init__(self, host, port): print("Attempting to connect to Robot arm") self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.s.bind((host, port)) self.s.listen() self.conn, self.addr = self.s.accept() print('Connected to', self.addr) # closes socket at end of session def __del__(self): print("Socket closed") self.s.shutdown(socket.SHUT_RDWR) self.s.close() ''' Motor commands consist of motor: a string specifying the port the motor is connected to A - D position: an int, where each position increment is a one degree change in angle ''' def send_pos(self, motor, position): msg = motor + str(max(position, 0)) + ";" self.conn.sendall(bytes(msg, 'utf-8')) # print(msg) def receive(self): return self.conn.recv(1024) def main(): s = Server(HOST, PORT) for i in range(5): s.send_pos('A', i * 360) # time.sleep(5) s.send_pos('A', 0) if __name__ == "__main__": main()
7329e011796290b118a9dc81424a0b1db5c0d79b
Empythy/Algorithms-and-data-structures
/ๆŽ’ๅบ/้€‰ๆ‹ฉๆŽ’ๅบ.py
1,073
3.734375
4
def selection_sort(arr): for i in range(len(arr) - 1): min_index = i for j in range(i + 1, len(arr)): if arr[j] < arr[min_index]: min_index = j arr[min_index], arr[i] = arr[i], arr[min_index] return arr """ ้€‰ๆ‹ฉๆŽ’ๅบๅ’Œๅ†’ๆณกๆŽ’ๅบๅพˆ็ฑปไผผ๏ผŒไฝ†ๆ˜ฏ้€‰ๆ‹ฉๆŽ’ๅบๆฏ่ฝฎๆฏ”่พƒๅชไผšๆœ‰ไธ€ๆฌกไบคๆข๏ผŒ ่€Œๅ†’ๆณกๆŽ’ๅบไผšๆœ‰ๅคšๆฌกไบคๆข๏ผŒไบคๆขๆฌกๆ•ฐๆฏ”ๅ†’ๆณกๆŽ’ๅบๅฐ‘๏ผŒๅฐฑๅ‡ๅฐ‘cpu็š„ๆถˆ่€—๏ผŒ ๆ‰€ไปฅๅœจๆ•ฐๆฎ้‡ๅฐ็š„ๆ—ถๅ€™ๅฏไปฅ็”จ้€‰ๆ‹ฉๆŽ’ๅบ๏ผŒๅฎž้™…้€‚็”จ็š„ๅœบๅˆ้žๅธธๅฐ‘ใ€‚ ๆฏ”่พƒๆ€ง๏ผšๅ› ไธบๆŽ’ๅบๆ—ถๅ…ƒ็ด ไน‹้—ด้œ€่ฆๆฏ”่พƒ๏ผŒๆ‰€ไปฅๆ˜ฏๆฏ”่พƒๆŽ’ๅบ ็จณๅฎšๆ€ง๏ผšๅ› ไธบๅญ˜ๅœจไปปๆ„ไฝ็ฝฎ็š„ไธคไธชๅ…ƒ็ด ไบคๆข๏ผŒๆฏ”ๅฆ‚[5, 8, 5, 2]๏ผŒ็ฌฌไธ€ไธช5ไผšๅ’Œ2ไบคๆขไฝ็ฝฎ๏ผŒๆ‰€ไปฅๆ”นๅ˜ไบ†ไธคไธช5ๅŽŸๆฅ็š„็›ธๅฏน้กบๅบ๏ผŒๆ‰€ไปฅไธบไธ็จณๅฎšๆŽ’ๅบใ€‚ ๆ—ถ้—ดๅคๆ‚ๅบฆ๏ผšๆˆ‘ไปฌ็œ‹ๅˆฐ้€‰ๆ‹ฉๆŽ’ๅบๅŒๆ ทๆ˜ฏๅŒๅฑ‚ๅพช็Žฏn*(n-1))๏ผŒๆ‰€ไปฅๆ—ถ้—ดๅคๆ‚ๅบฆไนŸไธบ๏ผšO(n^2) ็ฉบ้—ดๅคๆ‚ๅบฆ๏ผšๅช้œ€่ฆๅธธๆ•ฐไธช่พ…ๅŠฉๅ•ๅ…ƒ๏ผŒๆ‰€ไปฅ็ฉบ้—ดๅคๆ‚ๅบฆไนŸไธบO(1) ่ฎฐๅฟ†ๆ–นๆณ•๏ผš้€‰ๆ‹ฉๅฏน่ฑก่ฆๅ…ˆ้€‰ๆœ€ๅฐ็š„๏ผŒๅ› ไธบๅซฉ๏ผŒๅ“ˆๅ“ˆ """
e740658f81b2fa3a0a2253bc1fe31fe2c9e21ed2
waltman/advent-of-code-2020
/day23/crab_cups2.py
1,672
3.6875
4
#!/usr/bin/env python3 from sys import argv N = 1_000_000 MOVES = 10_000_000 class LinkedList: def __init__(self, val): self.val = val self.next_node = None def create_circle_list(cups): d = {} arr = [int(c) for c in cups] for i in arr: d[i] = LinkedList(i) for i in range(10,N+1): d[i] = LinkedList(i) for i in range(len(arr)-1): d[arr[i]].next_node = d[arr[(i+1) % len(arr)]] d[arr[8]].next_node = d[10] for i in range(10, N): d[i].next_node = d[i+1] d[N].next_node = d[arr[0]] return d[arr[0]], d def do_move(clist, d): # bypass the next 3 nodes front = clist.next_node back = front.next_node.next_node clist.next_node = back.next_node # which vals were just picked? picked = [front.val, front.next_node.val, front.next_node.next_node.val] # find the destination node num dest = clist.val - 1 if dest == 0: dest = N while dest in picked: dest = dest - 1 if dest == 0: dest = N # find the destination node p = d[dest] # insert the picked nodes at p back.next_node = p.next_node p.next_node = front def compute_score(clist): s = '' # find 1 while clist.val != 1: clist = clist.next_node # find the next 2 vals x = clist.next_node.val y = clist.next_node.next_node.val print(f'{x=} {y=}') return x * y clist, d = create_circle_list(argv[1]) for move in range(MOVES): if move % 100_000 == 0: print(f'{move=}') do_move(clist, d) clist = clist.next_node # compute score print('Part 2:', compute_score(clist))
97e049c04f90a90c0857bddafee417171533a547
guillermoojeda/CodingChallenges
/python/queens_in_board.py
543
3.703125
4
# You have an N by N board. Write a function that, given N, returns the number of possible arrangements of the board # where N queens can be placed on the board without threatening each other, i.e. no two queens share the same row, # column, or diagonal. N = 5 myBoard = [] #Creating board for i in range(N): myRow = [] for i in range(N): myRow.append(" ") myBoard.append(myRow) #moves list for queen dir1 = [] dir2 = [] dir3 = [] dir4 = [] for i in range(-(N-1), N): dir1.append([i, 0]) dir2.append([i, i])
70f484cc8fd9504bb6e6e8788de69baa8b60927b
Vedvyas-Kalupnath/Python-projects
/ASCII.py
217
4.28125
4
print("Find Value of a specific character in ASCII") print("") a = str(input("Enter a single character: ")) # print the ASCII value of assigned character in c print("The ASCII value of '" + a + "' is", ord(a))
816f6df2b305daf2d682a2fcd52a1befc0b7ab41
carlotamburin/Metode-optimizacije-Python
/Vjezba2/Zad2.py
1,485
3.625
4
import random def kamenSkarePapir(): bodoviIgrac = 0 bodoviRacunalo = 0 rezultat = [(1, 2), (3, 1), (2, 3)] while bodoviIgrac <= 5 or bodoviRacunalo <= 5: print("1. Kamen") print("2. Skare") print("3. Papir") odabirIgrac = int( input("odaberite broj pokraj predmeta kojeg zelite igrati")) odabirRacunalo = random.randint(1, 3) print("\n") for i in range(0, len(rezultat)): if (odabirIgrac in rezultat[i]) and (odabirRacunalo in rezultat[i]): for j in range(0, len(rezultat[i])): if (odabirIgrac == rezultat[i][0]) and (odabirIgrac != odabirRacunalo): bodoviIgrac += 1 break elif (odabirRacunalo == rezultat[i][0]) and (odabirIgrac != odabirRacunalo): bodoviRacunalo += 1 break elif (odabirIgrac == odabirRacunalo): break print("Igrac je odabrao {0}".format(odabirIgrac)) print("Racunalo je odabralo {0}".format(odabirRacunalo)) print("[Igrac {0} bodova]".format(bodoviIgrac)) print("[Racunalo {0} bodova]".format(bodoviRacunalo)) print("\n") if bodoviIgrac == 5: print("Igrac je pobijedio") break elif bodoviRacunalo == 5: print("Racunalo je pobijedilo") break kamenSkarePapir()
eab6f1e56129e768a3a2afe00be4e206992944ef
greatabel/puzzle_I_cracked
/3ProjectEuler/i26_50/i32Pandigital products.py
1,986
3.734375
4
# Pandigital products # Problem 32 # We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. # The product 7254 is unusual, as the identity, 39 ร— 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital. # Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital. # HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum. import time import math def isPandigital(string): thelen = len(string) # print(string,'thelen=', thelen) for i in range(1, thelen+1): # print('str(i)=', str(i)) if str(i) not in string: return False if thelen > 9: return False return True # ๆ•ฐA*ๆ•ฐB=ๆ•ฐC,ๅ…ฑ่ฎก9ไฝ๏ผŒ # ๅชๅฏ่ƒฝๆ˜ฏ 1ไฝ*4ไฝ=4ไฝ๏ผŒ 2ไฝ*3ไฝ=4ไฝ def find_allmatches(numbers): results = [] for i in range(1, 10): for j in range(int(math.pow(10, 3)) , int(math.pow(10,4))): combine = str(i) + str(j) + str(i * j) if isPandigital(combine): if i * j not in results: results.append(i * j) print(str(i) , str(j) ,str(i * j)) for i in range(10, 100): for j in range(100,1000): combine = str(i) + str(j) + str(i * j) if isPandigital(combine): if i * j not in results: results.append(i * j) print(str(i) , str(j) ,str(i * j)) return sum(results) if __name__ == "__main__": tic = time.clock() # for i in range(0,20): # print(i,fib(i),len(str(fib(i)))) # find_allpowers(5,5) # find_allpowers(10000,4) results = find_allmatches(list(range(1,10))) print('#', results) toc = time.clock() print("time=",toc - tic)
643f8d654bc07c7fd01c67edbc088124f0139db2
ahmetselimakbalik/pythonProjectlast
/edabit/01-very-easy/return-the-sum-of-two-numbers.py
589
4.4375
4
""" Return the Sum of Two Numbers Create a function that takes two numbers as arguments and return their sum. Examples addition(3, 2) โžž 5 addition(-3, -6) โžž -9 addition(7, 3) โžž 10 Notes Don't forget to return the result. If you get stuck on a challenge, find help in the Resources tab. If you're really stuck, unlock solutions in the Solutions tab. """ from edabit.Test import Test def addition(a, b): return a + b if __name__ == '__main__': Test.assert_equals(addition(2, 3), 5) Test.assert_equals(addition(-3, -6), -9) Test.assert_equals(addition(7, 3), 10)
c42eef898cf2b9aa7c3d51d5ca2b7439046808de
mradulpandya/contact_management_system-PYTHON
/main.py
1,369
3.65625
4
from dbhelper import db def main(): DB = db() while True: print("**********WELCOME**********") print() print("Press 1 to Insert new user") print("Press 2 to Display all user") print("Press 3 to Delete user") print("Press 4 to update User") print("Press 5 to Exit") print() try: choice=int(input()) if(choice==1): uid = int(input("Enter user Id: ")) uname = input("Enter user Name: ") uphone = input("Enter user Phone: ") DB.insert_user(uid, uname, uphone) elif choice==2: DB.fetch_all() elif choice==3: uid = int(input("Enter USer id to which you want delete: ")) DB.delete_user(uid) elif choice==4: uid = int(input("Enter user Id to update: ")) uname = input("Enter new user Name: ") uphone = input("Enter new user Phone: ") DB.update_user(uid, uname, uphone) elif choice==5: break else: print("Invalid choice : Try again") except exception as e: print(e) print("Invalid detail") if __name__ == "__main__": main()
7ab98282a5ca91d6777653f75899b86cb56eb292
python101ldn/exercises
/Session_4/4b_input_solution.py
365
4.25
4
# Get the below code to run in a while loop until the user enters 'EXIT' # users_name = input('What is your name? ') # print('Hello, ' + users_name + '!') loop = True while loop: users_name = input('What is your name? ') if users_name.upper() != 'EXIT': print('Hello, ' + users_name + '!') else: print('Goodbye!') loop = False
700ab9b75023f007f7c9b0925aa7b3539284ee16
zadacka/python_morsels
/11_point/point.py
772
3.90625
4
class Point(object): def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __eq__(self, other): return (self.x, self.y, self.z) == (other.x, other.y, other.z) def __repr__(self): return f"Point({self.x}, {self.y}, {self.z})" def __mul__(self, multiplier): return Point(self.x * multiplier, self.y * multiplier, self.z * multiplier) def __rmul__(self, multiplier): return self.__mul__(multiplier) def __add__(self, other): return Point(self.x + other.x, self.y + other.y, self.z + other.z) def __sub__(self, other): return Point(self.x - other.x, self.y - other.y, self.z - other.z) def __iter__(self): return iter([self.x, self.y, self.z])
c883365709f2d45080849dc039f22ee1a187128c
miguel-uribe/BRT-Simulation
/stationC.py
4,191
3.5
4
# -*- coding: utf-8 -*- """ Created on Thu Mar 16 06:50:22 2017 @author: miguelurla """ from __future__ import division import parameters # Importiung the anim parameter anim=parameters.anim # If anim, import the vpython module if anim: from vpython import * class stationC: "This class contains all information about the stations of the system" n=0 #number of stations # This is the constructor def __init__(self,name,x): self.name=name # Station name self.x=x # The x position of the station self.ID=stationC.n # The station ID stationC.n=stationC.n+1 # The station counter is updated self.wagons=parameters.Nw # By default all stations have three wagons self.boxes=None # Memory for the graphical representation self.lineIDs=[] # The ID's of the lines self.lineTimes={} # A dictionary storing all times a line reaches a station # This function overrides the representation def __repr__(self): output="%d: %s; x=%d; %d wagons; lines:"%(self.ID,self.name,self.x, self.wagons) for line in self.lineIDs: output=output+" %d"%line return output def addline(self,lineID): self.lineIDs.append(lineID) print("Added line") # This function updates the wagon number def updatewagons(Stations,stationIDs,stops): for i in range(len(stationIDs)): for j in range(len(Stations)): if Stations[j].ID==stationIDs[i]: if stops[i]>Stations[j].wagons: Stations[j].wagons=stops[i] # defining the function # defining the function if anim: def setrepr(Stations): # Setting the wagon representation for station in Stations: if station.boxes is None: station.boxes=[] station.streets=[] station.liasons=[] # The street between the wagons posst=vector(station.x+0.5*parameters.DS,-14,-1) station.streets.append(box(pos=posst, length=parameters.DS, width=1,height=6, color=color.gray(0.8) )) for i in range(station.wagons): posv=vector(station.x+0.5*parameters.Dw+i*(parameters.Ds),0,0) station.boxes.append(box(pos=posv, length=parameters.Dw, width=1,height=10, color=color.blue)) posst=vector(station.x+parameters.Dw+i*(parameters.Ds),-11,-1) station.streets.append(box(pos=posst, length=2*parameters.Dw, width=1,height=12, color=color.gray(0.8) )) if i+1<station.wagons: posv=vector(station.x+parameters.Dw+0.5*(parameters.Ds-parameters.Dw)+i*(parameters.Ds),0,0) station.liasons.append(box(pos=posv, length=parameters.Dw, width=1,height=6, color=color.blue)) if i==0: posst=vector(station.x-0.5*parameters.Dw,-11,-1) station.streets.append(box(pos=posst, length=parameters.Dw, width=1,height=12, color=color.gray(0.8))) # This function retrieves the complete station length def getstationlength(Stations,stationID): for station in Stations: if station.ID==stationID: size=(station.wagons-1)*parameters.Ds+parameters.Db break return size # This function retrieves the station index from the ID def getstationindexbyID(Stations,ID): for i in range(len(Stations)): if Stations[i].ID==ID: return i print("The given line ID has not been found in the Stations list") # Get station from ID def getstationbyID(Stations,ID): for station in Stations: if station.ID==ID: return station print("The given line ID has not been found in the Stations list") return None # Remove a station from list def removestation(Stations,ID): Stations.remove(getstationbyID(Stations,ID))
7be298dfda59c2f8eb567387e15de04b32a20129
consmith/Password_Generator
/Password_Generator.py
1,417
4.0625
4
#Password Generator import random def HowManyPasswords(): PasswordAmount = raw_input('how many passwords do you want to generate? ') Amount = ErrorChecking(PasswordAmount,'Amount') return Amount def ErrorChecking(String_Input,Which_One): bad_word = False for i in range(0,len(String_Input)): if bad_word == True: pass if (ord(String_Input[i]) > 57 or ord(String_Input[i]) < 48): print 'The inputted amount was not a number. \n 1 password will be printed' bad_word = True Result = 1 if bad_word == False: Result = int(String_Input) if Which_One == 'Length': if Result > 50 or Result < 0: print('The length can not be greater than 50 or less than 0') print('The length was set to 10') Result = 10 return Result def WhatLength(): print('inputting a 0 or below will use the default length 10') Length_Input = raw_input('What length would you like your password to be? ') Length = ErrorChecking(Length_Input,'Length') return Length def GeneratePasswords(Amount,Length): for i in range(0,Amount): password = random.sample("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",Length) print i+1,':',''.join(password) if __name__ == '__main__': Amount = HowManyPasswords() Length = WhatLength() GeneratePasswords(Amount, Length)
539cd0d77d07c5413e25ce7426ff7f240b55210b
Cassie07/Leetcode_2020
/Arrays/35. SearchInsertPosition.py
238
3.515625
4
class Solution: def searchInsert(self, nums: List[int], target: int) -> int: if target in nums: return nums.index(target) c = 0 for i in nums: if i < target: c += 1 return c
d84402bff68f1fc055a32f1e0f8bb9a239a60ef8
jyameo/machine-learning
/svm/svm_author_id.py
1,281
3.53125
4
#!/usr/bin/python """ This is the code to accompany the Lesson 2 (SVM) mini-project. Use a SVM to identify emails from the Enron corpus by their authors: Sara has label 0 Chris has label 1 """ import sys from time import time sys.path.append("/root/projects/machine_learning/ud120-projects/tools/") from email_preprocess import preprocess from sklearn.svm import SVC from sklearn.metrics import accuracy_score ### features_train and features_test are the features for the training ### and testing datasets, respectively ### labels_train and labels_test are the corresponding item labels features_train, features_test, labels_train, labels_test = preprocess() features_train = features_train[:len(features_train)/100] labels_train = labels_train[:len(labels_train)/100] ######################################################### ### your code goes here ### clf = SVC(kernel='rbf', C=10000.0) t0 = time() clf.fit(features_train, labels_train) print "Training time:",round(time() - t0,3),"s" t0 = time() pred = clf.predict(features_test) print "Prediction time:",round(time() - t0,3),"s" print "Accuracy:", accuracy_score(pred, labels_test) chris = [x for x in pred if x == 1] print len(chris) #########################################################
03e460bcd4eb343494ea29933b3ed00fe66030ca
bb2qqq/tech_notes
/THEORIES/algorithm/leetcode/HN_4_Irregular_Probability_Variation.py
2,120
4.125
4
""" Design a function, which returns True or False in a random way. Which requires: 1. The total distribution of True&False is irregular and unpredicatable(Won't fixed on a ratio even after a huge number of tests. 2. Run this function two times with same parameters will get totally different results. """ # The average Dice Probs decides the total distributions. # So we Requires The Average Dice Probs changes in an uncontrollable way. # We made distribution shift to True, then shift to False in a mild or drastic way. # Chaos is what comes to my mind # I need to reread <An introduction to Complexity> import random import math def toss_coin(times, true_times=0, count=0, seed=random.random(), switch_num=random.random(), vary_rate=random.random()/100): while count < times: if seed >= 1 or seed <= 0.01: seed = random.random() switch_num = random.random() vary_rate = random.random() / 100 count += 1 judge_num = random.random() if switch_num >= 0.5 and judge_num < seed: true_times += 1 if switch_num < 0.5 and judge_num > seed: true_times += 1 seed = seed * (1 + vary_rate) false_times = times - true_times status = true_times >= false_times return true_times, false_times, status, (times, count, seed, switch_num, vary_rate) def continue_running(info, continue_running_times): true_times, false_times, status, param_tuple = info old_times, count, seed, switch_num, vary_rate = param_tuple times = old_times + continue_running_times new_info = toss_coin(times, true_times=true_times, count=count, seed=seed, switch_num=switch_num, vary_rate=vary_rate) return new_info def test_toss(base, times): more_true_times = 0 more_false_times = 0 for i in xrange(times): true_times, false_times, status, param_tuple = toss_coin(base) if status: more_true_times += 1 else: more_false_times += 1 trend = more_true_times >= more_false_times return more_true_times, more_false_times, trend
2bdac3723b23d38e051fab241d703e95261fb91d
mobishift2011/My-100-Days-Of-ML
/1/code.py
1,695
3.859375
4
"""ๆ•ฐๆฎ้ข„ๅค„็†""" # Step 1: Importing libraries from sklearn.impute import SimpleImputer from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler import numpy as np import pandas as pd import os # Step 2: Importing dataset file_path = os.path.join(os.path.relpath( os.path.dirname(__file__)), 'Data.csv') dataset = pd.read_csv(file_path) X = dataset.iloc[:, :-1].values Y = dataset.iloc[:, -1].values print("Step 2: Importing dataset") print("X") print(X) print("Y") print(Y) # Step 3: Handling the missing data imputer = SimpleImputer() X[:, 1:3] = imputer.fit_transform(X[:, 1:3]) print("---------------------") print("Step 3: Handling the missing data") print("step2") print("X") print(X) # Step 4: Encoding categorical data label_encoder = LabelEncoder() X[:, 0] = label_encoder.fit_transform(X[:, 0]) X = OneHotEncoder(categories='auto').fit_transform(X).toarray() Y = label_encoder.fit_transform(Y) print("---------------------") print("Step 4: Encoding categorical data") print("X") print(X) print("Y") print(Y) # Step 5: Splitting the datasets into training sets and test sets x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.2) print("---------------------") print("Step 5: Splitting the datasets into training sets and Test sets") print("X_train") print(x_train) print("X_test") print(x_test) print("Y_train") print(y_train) print("Y_test") print(y_test) # Step 6. Feature scaling sc = StandardScaler() sc.fit_transform(x_train) sc.transform(x_test) print("---------------------") print("Step 6: Feature Scaling") print("X_train") print(x_train) print("X_test") print(x_test)
f17665afaae3c576dfc47cc09d86bacffcd90e05
liwaya29/python
/1_variable_types.py
229
3.5
4
# variable declaration # variable_name assignment_operator value x = 1 print(x) y = 2 print(y) # variable types print(type(x)) print(type(y)) name = "liwaya" print(name) print(type(name)) z = 3.9 print(z) print(type(z))
5e4ca3db42ad683fc71bfdbe0080dc1232b0284b
abhishekzambre/Python_Programs
/EPI/set.py
147
3.625
4
x = set("A Python Tutorial") print(x) y = set(["A", "B", "C"]) print(y) z = set("ABCcC") print(z) l = ["a","b","b","c"] s = set(l) print(s)
e14ef6b662d4a9225c3eda49d596e6c87cfacaa6
iboros1/PTP
/pr2.py
2,113
3.625
4
# P2. Merge 2 objects with any depth (including contained dictionaries, lists, sets, strings, integers, floats). # Type mismatches should yield a tuple with the two elements. Examples: # a = {'x': [1,2,3], 'y': 1, 'z': set([1,2,3]), 'w': 'qweqwe', 't': {'a': [1, 2]}, 'm': [1]} # b = {'x': [4,5,6], 'y': 4, 'z': set([4,2,3]), 'w': 'asdf', 't': {'a': [3, 2]}, 'm': "wer"} # Expected result: # {'x': [1,2,3,4,5,6], 'y': 5, 'z': set([1,2,3,4]), 'w': 'qweqweasdf', 't': {'a': [1, 2, 3, 2]}, 'm': ([1], "wer")} a = {'x': [1, 2, 3], 'y': 1, 'z': set([1, 2, 3]), 'w': 'qweqwe', 't': {'a': [1, 2]}, 'm': [1]} b = {'x': [4, 5, 6], 'y': 4, 'z': set([4, 2, 3]), 'w': 'asdf', 't': {'a': [3, 2]}, 'm': "wer"} def anyw(a, b): for elem in a: if type(a[elem]) == list: listb(b, a, elem) elif type(a[elem]) == int: intb(b, a, elem) elif type(a[elem]) == str: strb(b, a, elem) if type(a[elem]) == set: setb(b, a, elem) if type(a[elem]) == dict: dictb(b, a, elem) return elem def listb(b, a, elem): for item in b: if elem == item: if type(a[elem]) == type(b[item]): a[elem].extend(b[item]) else: a[elem] = a[elem], (b[item]) print(a) def intb(b, a, elem): for item in b: if elem == item: if type(a[elem]) == type(b[item]): a[elem] = b[item] + a[elem] print(a) def strb(b, a, elem): for item in b: if elem == item: if type(a[elem]) == type(b[item]): a[elem] = str(b[item]) + str(a[elem]) print(a) def setb(b, a, elem): for item in b: if elem == item: if type(a[elem]) == type(b[item]): a[elem] = a[elem].union(b[item]) # WIP add proper formating print(a) def dictb(b, a, elem): for item in b: if elem == item: if type(a[elem]) == type(b[item]): a[elem]["a"] = a[elem]["a"] +b[item]["a"] print(a) anyw(a, b)
25e2af3b9061bc47bc76f845cc3998d8e8d92c44
rrdesai/dsp
/python/q8_parsing.py
840
4.1875
4
# -*- coding: utf-8 -*- # The football.csv file contains the results from the English Premier League. # The columns labeled โ€˜Goalsโ€™ and โ€˜Goals Allowedโ€™ contain the total number of # goals scored for and against each team in that season (so Arsenal scored 79 goals # against opponents, and had 36 goals scored against them). Write a program to read the file, # then print the name of the team with the smallest difference in โ€˜forโ€™ and โ€˜againstโ€™ goals. # this assumes that smallest means that we're looking for the lowest positive difference import pandas df = pandas.read_csv('football.csv') df_new = pandas.concat([df, df['Goals'] - df['Goals Allowed']], axis = 1) low = 99999 for i in df_new[0]: if i > 0: if i < low: low = i print df_new[df_new[0] == low]['Team'].to_string().split(' ')[-1]
483136ce7c7aa923b1dd3f0cd4731a17a18c9ad6
Pawls/Coding-Challenges
/CtCI/python/Ch 2 Linked Lists (missing intersection)/LinkedList.py
7,270
3.78125
4
class Node: total = 0 def __init__(self, data): self.data = data self.next = None Node.total += 1 #print('Nodes:', Node.total) def __del__(self): Node.total -= 1 #print('Nodes:', Node.total) class LinkedList: def __init__(self): # Define aliases self.addBack = self.append = self.add self.addHead = self.push = self.addFront # Member variables self.head = None self.tail = None def __len__(self): size = 0 for _ in self: size += 1 return size def __str__(self): ptr = self.head nodes = '' while ptr: nodes += str(ptr.data) if ptr.next: nodes += ' -> ' ptr = ptr.next return nodes def __iter__(self): ptr = self.head while ptr: yield ptr ptr = ptr.next def delete(self): self.head = self.tail = None del self def get(self, index): if index < 0 or len(self) <= index: raise IndexError('list index out of range') ptr = self.head for _ in range(index): ptr = ptr.next return ptr.data def pop(self): result = self.head.data self.head = self.head.next return result def set(self, index, data): if index < 0 or len(self) <= index: raise IndexError('list index out of range') ptr = self.head for _ in range(index): ptr = ptr.next ptr.data = data def copy(self): new_ll = LinkedList() ptr = self.head while ptr: new_ll.add(ptr.data) ptr = ptr.next return new_ll def insert(self, index, data): size = len(self) if index < 0 or size < index: raise IndexError('list index out of range') if index == 0: self.addFront(data) elif index == size: self.add(data) else: ptr = self.head prev = None for _ in range(index): prev = ptr ptr = ptr.next if ptr: new_node = Node(data) new_node.next = ptr prev.next = new_node return True def add(self, *data): for ele in data: if not self.head: self.tail = self.head = Node(ele) else: self.tail.next = Node(ele) self.tail = self.tail.next def addFront(self, *data): for ele in data: if not self.head: self.tail = self.head = Node(ele) else: new_node = Node(ele) new_node.next = self.head self.head = new_node def indexOf(self, data): ptr = self.head index = 0 while ptr: if ptr.data == data: return index ptr = ptr.next index += 1 return -1 def discard(self, data): ptr = self.head prev = None while ptr: if ptr.data == data: if not prev: self.head = self.head.next elif not ptr.next: self.tail = prev self.tail.next = None else: prev.next = ptr.next return True prev = ptr ptr = ptr.next return False def discardAll(self, data): ptr = self.head prev = None while ptr: if ptr.data == data: if not prev: ptr = self.head = self.head.next elif not ptr.next: self.tail = prev self.tail.next = None return else: prev.next = ptr.next prev = ptr ptr = ptr.next else: prev = ptr ptr = ptr.next def remove(self, data): ptr = self.head prev = None while ptr: if ptr.data == data: if not prev: self.head = self.head.next elif not ptr.next: self.tail = prev self.tail.next = None else: prev.next = ptr.next return True prev = ptr ptr = ptr.next raise KeyError(data) def clear(self): self.__init__() if __name__ == '__main__': print('Building Linked List now...') ll = LinkedList() ll.add(1,2) ll.addBack(3) ll.add(4,5) ll.addFront(0) print('Length:', len(ll)) print(ll) print() print('Discarding 1 now...') ll.discard(1) print('Length:', len(ll)) print(ll) print() print('Discarding 0 now...') ll.discard(0) print('Length:', len(ll)) print(ll) print() print('Discarding 5 now...') ll.discard(5) print('Length:', len(ll)) print(ll) print() print('Inserting 0 now...') ll.insert(0,0) print('Length:', len(ll)) print(ll) print() print('Inserting 1 now...') ll.insert(1,1) print('Length:', len(ll)) print(ll) print() print('Inserting 5 now...') ll.insert(5,5) print('Length:', len(ll)) print(ll) ''' print() print('Inserting at negative index now...') ll.insert(-1,5) print() print('Inserting out of bounds now...') ll.insert(7,5) print(ll) print('Length:', len(ll)) print() print('Removing 12 now...') ll.remove(12) print('Length:', len(ll)) print(ll) ''' print() print('Clearing now...') ll.clear() print('Length:', len(ll)) print(ll) print() print('Building again...') ll.add(1) ll.add(2) ll.addBack(3) ll.add(4) ll.add(5) ll.addFront(0) print('Length:', len(ll)) print(ll) print() print('Copying now...') ll2 = ll.copy() print('Length:', len(ll2)) print(ll2.head.data, ll2, ll2.tail.data) print('Removing ll2...') ll2.delete() print() print('Getting data at index 0,1,5 now...') print(ll.get(0),ll.get(1),ll.get(5)) print() print('Setting data at 0,1,5 to a,b,c') ll.set(0,'a') ll.set(1,'b') ll.set(5,'c') print(ll) print() print('Push -1 now...') ll.push(-1) print('Length:', len(ll)) print(ll) print() print('Pop now...') print(ll.pop()) print('Length:', len(ll)) print(ll) print() print("Index of 'c'...") print(ll.indexOf('c')) print() print('Pushing 9,8,9,9, then discardAll 9s') ll.push(9) ll.push(8) ll.push(9) ll.push(9) print(ll) ll.discardAll(9) print(ll) print() print('Adding 9,8,9,9, using single line') ll.add(9,8,9,9) print(ll) print() print('Testing Iter') seq = '' for ele in ll: seq += str(ele.data) + '<|>' print(seq)
c517d3b144014b9477b744191468f495184a3ce7
ai2-education-fiep-turma-2/05-python
/solucoes/TiagoPedrosa/listabash/exerciciocidades.py
364
3.53125
4
def analisaCidades(): arquivo = open("cidades.txt") linhas = [i.strip().lower() for i in arquivo.readlines()] unique = set(linhas) for i in unique: frequencia = linhas.count(i) print("A frequรชncia de", i.upper(), "รฉ", frequencia) print("Cidades total:", len(linhas), ", Cidades unicas: ", len(unique)) analisaCidades()
3ebc3d0ed8429b9b867c2168d57164d7258e8b3c
ibogdanova/homework
/array.py
241
3.671875
4
array = [0, 1, 2, 3, 4, 5] sum = 0 number = 1 if len(array) <= 0: print(0) else: for number in range(len(array)): if number % 2 != 0: sum = sum + array[number] result = sum * array[-1] print(result)
d1da9a2a27c82118e3793b59ecd5641e13492a28
Fatimaliras/Analytics
/arvore b/arvore_oficial.py
5,699
4.1875
4
# Programaรงรฃo Dinรขmica - Estruturas de Dados # Implementaรงรฃo de รrvores e seus algoritmos - by hallpaz # https://youtube.com/programacaodinamica from queue import Queue ROOT = "root" # Implementando uma รrvore Binรกria: https://youtu.be/6E169kShoNU class Node: def __init__(self, data): self.data = data self.left = None self.right = None def __str__(self): return str(self.data) class BinaryTree: def __init__(self, data=None, node=None): if node: self.root = node elif data: node = Node(data) self.root = node else: self.root = None # Percurso em ordem simรฉtrica (o correto รฉ "inorder" em inglรชs) def simetric_traversal(self, node=None): if node is None: node = self.root if node.left: # parรชnteses sรฃo especรญficos para o nosso exemplo, # um percurso em ordem simรฉtrica nรฃo precisa deles print('(', end='') self.simetric_traversal(node.left) print(node, end='') if node.right: self.simetric_traversal(node.right) print(')', end='') # Percurso em Pร“S ORDEM em รRVORE BINรRIA: https://youtu.be/QC8oiQnlYos def postorder_traversal(self, node=None): if node is None: node = self.root if node.left: self.postorder_traversal(node.left) if node.right: self.postorder_traversal(node.right) print(node) def height(self, node=None): if node is None: node = self.root hleft = 0 hright = 0 if node.left: hleft = self.height(node.left) if node.right: hright = self.height(node.right) if hright > hleft: return hright + 1 return hleft + 1 def inorder_traversal(self, node=None): if node is None: node = self.root if node.left: self.inorder_traversal(node.left) print(node, end=' ') if node.right: self.inorder_traversal(node.right) # Percurso em Nรญvel em รrvore Binรกria: https://youtu.be/UOK7nS2E9xM def levelorder_traversal(self, node=ROOT): if node == ROOT: node = self.root queue = Queue() queue.push(node) while len(queue): node = queue.pop() if node.left: queue.push(node.left) if node.right: queue.push(node.right) print(node, end=" ") # รrvore Binรกria de Busca: https://youtu.be/rviJVdt_icw class BinarySearchTree(BinaryTree): def insert(self, value): parent = None x = self.root while(x): parent = x if value < x.data: x = x.left else: x = x.right if parent is None: self.root = Node(value) elif value < parent.data: parent.left = Node(value) else: parent.right = Node(value) def search(self, value): return self._search(value, self.root) def _search(self, value, node): if node is None: return node if node.data == value: return BinarySearchTree(node) if value < node.data: return self._search(value, node.left) return self._search(value, node.right) # Encontrando o MAIOR e o MENOR elemento numa รRVORE Binaฬria de Busca: https://youtu.be/Q9s_XyJpHTI def min(self, node=ROOT): if node == ROOT: node = self.root while node.left: node = node.left return node.data def max(self, node=ROOT): if node == ROOT: node = self.root while node.right: node = node.right return node.data # REMOVENDO da รrvore Binรกria de Busca: https://youtu.be/dyLwOXBA3Ws def remove(self, value, node=ROOT): # Se for o valor padrรฃo, executa a partir da raiz if node == ROOT: node = self.root # Se desceu atรฉ um ramo nulo, nรฃo hรก nada a fazer if node is None: return node # Se o valor for menor, desce ร  esquerda if value < node.data: node.left = self.remove(value, node.left) # Se o valor for maior, desce ร  direita elif value > node.data: node.right = self.remove(value, node.right) # Se nรฃo for nem menor, nem maior, encontramos! Vamos remover... else: if node.left is None: return node.right elif node.right is None: return node.left else: # Substituto รฉ o sucessor do valor a ser removido substitute = self.min(node.right) # Ao invรฉs de trocar a posiรงรฃo dos nรณs, troca o valor node.data = substitute # Depois, remove o substituto da subรกrvore ร  direita node.right = self.remove(substitute, node.right) return node # def search(self, value, node=ROOT): # if node == ROOT: # node = self.root # if node is None or node.data == value: # return BinarySearchTree(node) # if value < node.data: # return self.search(value, node.left) # return self.search(value, node.right) if __name__ == "__main__": tree = BinaryTree(7) tree.root.left = Node(18) tree.root.right = Node(14) print(tree.root) print(tree.root.right) print(tree.root.left)
5db852dde5395ad4153e5f73e008ac062d0ea5de
gistable/gistable
/dockerized-gists/1935894/snippet.py
711
4.5625
5
"""Simple example showing why using super(self.__class__, self) is a BAD IDEA (tm)""" class A(object): def x(self): print "A.x" class B(A): def x(self): print "B.x" super(B, self).x() class C(B): def x(self): print "C.x" super(C, self).x() class X(object): def x(self): print "X.x" class Y(X): def x(self): print "Y.x" super(self.__class__, self).x() # <- this is WRONG don't do it! class Z(Y): def x(self): print "Z.x" super(self.__class__, self).x() # <- this is WRONG don't do it! if __name__ == '__main__': C().x() Z().x() # will cause 'RuntimeError: maximum recursion depth exceeded'
5f7d093a66e28a9a0d84502b91dc0178b9381d7e
mehdizit/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/12-roman_to_int.py
604
3.53125
4
#!/usr/bin/python3 def roman_to_int(roman_string): if isinstance(roman_string, str): total = 0 nums = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1} list_n = [nums.get(char) for char in roman_string] len_l = len(list_n) if len_l == 1: total = list_n[0] return total for i in range(len_l - 1): if list_n[i] < list_n[i + 1]: total -= list_n[i] else: total += list_n[i] total += list_n[i + 1] return total return 0
a838b15d296e5774b1b97c259398b15aa62c0632
kookou/study
/Algorithm/์นด์นด์˜ค2020์ฝ”ํ…Œ2๋ฒˆ.py
1,035
3.734375
4
orders = ["XYZ", "XWY", "WXA"] course = [2,3,4] from itertools import combinations as cb def solution(orders, course): answer = [] for count in course: # ๊ฐ ์ฝ”์Šค ๋งˆ๋‹ค sum_combo = [] # ์ฝ”์Šค ๋ณ„ ์ „์ฒด ์ฝค๋ณด ๋ฆฌ์ŠคํŠธ for i, order in enumerate(orders): # ๊ฐ ์˜ค๋” ๋งˆ๋‹ค order = ''.join(sorted(order)) # ์˜ค๋”๋ฅผ ์•ŒํŒŒ๋ฒณ ์ˆœ์œผ๋กœ ์ •๋ ฌ print(order) combo = list(cb(order, count)) for j, c in enumerate(combo): combo[j] = ''.join(c) sum_combo += combo top_combo = 2 # ๊ฐ€์žฅ ๋งŽ์€ ์ฝค๋ณด ์ˆ˜ _answer = [] print(sum_combo) for combo in set(sum_combo): if sum_combo.count(combo) > top_combo: _answer = [combo] top_combo = sum_combo.count(combo) elif sum_combo.count(combo) == top_combo: _answer.append(combo) answer += _answer answer.sort() return answer print(solution(orders, course))
7e10bccaa6ec4759eb2ec7155a6cd1cb2af4d492
PiotrStankiewicz/codebrainers2019
/dni/04_dzien/funkcjefinbonacci.py
222
3.84375
4
def fibonacci(m): lista = [0,1] for i in range(2, m+1): # lista[i] = lista[i-1] + lista[i-2] lista.append(lista[i-1] + lista[i-2]) return lista[-1] wartosc = fibonacci(10) print(wartosc)
4b61af7a5144cb8ceb4a28782efc3f7bf380dc47
Hemie143/realpython2
/chp04_database_programming/04_072_sql-search.py
596
4.125
4
import sqlite3 prompt = ''' Select the operation you want to perform (1-5): 1. Average 2. Max 3. Min 4. Sum 5. Exit ''' operation = {'1': 'AVG', '2': 'MAX', '3': 'MIN', '4': 'SUM'} with sqlite3.connect("newnum.db") as connection: c = connection.cursor() while True: choice = input(prompt) if choice in ['1', '2', '3', '4']: c.execute(f"SELECT {operation[choice]}(num) from numbers") result = c.fetchone() print(f'Result: {result[01]}') elif choice == '5': break else: print('Invalid choice.')
7b017f3ebb0176c42a0ac1e44bf669cb5e2dd694
tianwei1992/Python_oop_leaning
/advanced/staticmethod_and_classmethod/classmethod_demo.py
700
3.71875
4
class Spam: numInstances = 0 def __init__(self): Spam.numInstances += 1 def printNumInstances(cls): print("Number of instances:", cls.numInstances) printNumInstances = classmethod(printNumInstances) if __name__ == "__main__": a,b = Spam(), Spam() a.printNumInstances() Spam.printNumInstances() print() class Sub(Spam): def printNumInstances(cls): print("Extra stuff...", cls) Spam.printNumInstances() printNumInstances = classmethod(printNumInstances) if __name__ == "__main__": x, y = Sub(), Spam() x.printNumInstances() y.printNumInstances() Sub.printNumInstances() print() class Other(Spam): pass if __name__ == "__main__": z = Other() z.printNumInstances()
0cc99e80b71f68b0803caaf0e7b86ba346da3513
hayatbayramolsa/pandas
/main.py
2,841
3.828125
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 26 11:00:20 2020 @author: Hp 840 """ import pandas as pd sozluk = {"NAME": ["Ali", "Ahmet", "AyลŸe", "Mustafa", "Sinan", "Zeynep", "BรผลŸra", "Esra"], "AGE": [15, 17, 22, 27, 18, 20, 32, 21], "MAAS": [100, 150, 130, 220, 350, 120, 250, 180]} dataFrame1 = pd.DataFrame(sozluk) head = dataFrame1.head() tail = dataFrame1.tail() head = dataFrame1.head(6) # %% Pandas Basic Methods dataFrame1.columns dataFrame1.info() dataFrame1.dtypes dataFrame1.describe() # numeric columns # %% Indexing and Slicing dataFrame1["NAME"] dataFrame1.AGE dataFrame1["yeni feature"] = [-1, -2, -3, -4, -5, -6, -7, -8] dataFrame1.yeni Feature dataFrame1["yeni feature"] dataFrame1.loc[:, "AGE"] dataFrame1.loc[:3, "AGE"] dataFrame1.loc[:3, "AGE" : "MAAS"] dataFrame1.loc[:3, ["AGE", "NAME"]] dataFrame1.iloc[:, 2] # %% Filtering # maaลŸฤฑ 200'den fazla olanlar filtre1 = dataFrame1.MAAS > 200 type(filtre1) filtrelenmis_data = dataFrame1[filtre1] # hem o hem de yaลŸฤฑ 20'den kรผรงรผk olanlar filtre2 = dataFrame1.AGE < 20 dataFrame1[filtre1 & filtre2] # yaลŸฤฑ 30'un รผstรผnde olanlar dataFrame1[dataFrame1.AGE > 30] # adฤฑ Mustafa olan dataFrame1[dataFrame1.NAME == "Mustafa"] # mustafa veya bรผลŸra olan dataFrame1[(dataFrame1.NAME == "Mustafa") | (dataFrame1.NAME == "BรผลŸra")] # %% List Comprehension # ortalama maaลŸ dataFrame1.MAAS ortalama_maas = dataFrame1.MAAS.mean() # numpy ile bulma import numpy as np ortalama_maas_np = np.mean(dataFrame1.MAAS) # seviyelerine gรถre string ekleme for i in dataFrame1.MAAS: print(i) for i in dataFrame1.MAAS: if(i > ortalama_maas): print("yรผksek") else: print("dรผลŸรผk") dataFrame1["seviye"] = ["yรผksek" if i > ortalama_maas else "dรผลŸรผk" for i in dataFrame1.MAAS] # sรผtunlarฤฑ kรผรงรผk harfe รงevirme dataFrame1.columns "ENES".lower() dataFrame1.columns = [i.lower() for i in dataFrame1.columns] # boลŸluklarฤฑ yok etme len("yapay zeka".split()) dataFrame1.columns = [i.split()[0] + "_" + i.split()[1] if(len(i.split())) > 1 else i for i in dataFrame1.columns] # %% drop and concatenating dataFrame1.drop(["yeni feature"], axis=1, inplace=True) # concatenate data1 = dataFrame1.head() data2 = dataFrame1.tail() # vertical data_concat = pd.concat([data1, data2], axis=0) # horizontal maas = dataFrame1.maas yas = dataFrame1.age h_concat = pd.concat([maas, yas], axis=1) # %% transforming data dataFrame1["list_comp"] = [i*2 for i in dataFrame1.age] # apply yรถntemi def multiply(age): return age*2 dataFrame1["apply_metodu"] = dataFrame1.age.apply(multiply)
e10ea3d2f156f15eeb2e2f3926c72739fb235556
Yurun-LI/CodeEx
/MaximumSubArray.py
342
3.671875
4
from typing import List class Solution: def maximumSubArray(self,nums:List[int])-> int: pre = 0 max_ans = nums[0] for i in range(0,len(nums)): pre = max(pre+nums[i],nums[i]) max_ans = max(max_ans, pre) return max_ans nums = [-1,-2,1] print(Solution().maximumSubArray(nums))
7542a0c434c1d91d7b4966055e6db050affd0e38
vamsi12619/IntroToPyOrg
/lists/lists.py
542
4.25
4
birds = ['aquatic warbler', 'arctic skua', 'avocet', 'goose', 'owl'] # list of birds, lists are defined by square brakets. bird = birds[0] #This defines 'bird' as the first entry in the list known as 'birds'. The variable 'bird' could be anything (i.e. 'i' or 'n') print(bird.title()) #We know this, it prints the variable 'bird' n = birds[1] #defining 'n' as the second bird in the series print(n.title()) # Prints 'n', which is the second item in the list bird = birds[-1] # Will always access last item in list. print(bird.title())
2870963be304c38afbaaa64c65cb6c73901329bc
ityrpak/Minijuegos-con-Python
/paroimpar.py
600
3.703125
4
# Minijuego Par o Impar class ParOImpar: @staticmethod def jugar_juego(): print(f"\nPar o Impar") try: x = float(input("Ingresa un Numero: ")) except: ParOImpar.jugar_juego() if x % 2 == 0: print("Es un numero par.") else: print("Es un numero impar.") if ParOImpar.pregunta_jugar_denuevo(): ParOImpar.jugar_juego() @staticmethod def pregunta_jugar_denuevo(): answer = input(f"\nPresiona 1 para jugar de nuevo. Presiona cualquier tecla para regresar al menu.") if answer == "1": return True
630aa17a945a8b526c0cdc0f5cd64b5c37a13719
petertia/kaggle
/genderclassmodelpy.py
4,371
3.515625
4
import csv as csv import numpy as np csv_file_object = csv.reader(open('C:/Users/Peter/Documents/Kaggle/Titanic/train.csv','rt')) header = next(csv_file_object) data = [] for row in csv_file_object: data.append(row) data = np.array(data) # Creating bins for gender, class, fare fare_ceiling = 40 data[data[0::,9].astype(np.float) >= fare_ceiling, 9] = fare_ceiling-1.0 fare_bracket_size = 10 number_of_price_brackets = fare_ceiling / fare_bracket_size number_of_classes = 3 number_of_price_brackets = int(number_of_price_brackets) #Define survival table survival_table = np.zeros([2, number_of_classes, number_of_price_brackets]) for i in range(number_of_classes): for j in range(number_of_price_brackets): # sets the data for each range to a vector and finds the mean # then enters the data into the survival table and repeats the for loop women_only_stats = (data[(data[0::,4] == "female") \ # which is a female &(data[0::,2].astype(np.float)== i+1) \ # and was ith class &(data[0:,9].astype(np.float) >= j*fare_bracket_size) \ #and was greater than this bin &(data[0:,9].astype(np.float) < (j+1)*fare_bracket_size), 1]) \ #and less than the next bin in the 1st col men_only_stats = (data[(data[0::,4] != "female") \ # which is a male &(data[0::,2].astype(np.float) == i+1) \ # and was ith class &(data[0:,9].astype(np.float) >= j*fare_bracket_size) \ #and was greater than this bin &(data[0:,9].astype(np.float) < (j+1) * fare_bracket_size), 1]) \ #and less than the next bin in the 1st col if len(women_only_stats) > 0: survival_table[0,i,j] = np.mean(women_only_stats.astype(np.float)) #women stats if len(men_only_stats) > 0: survival_table[1,i,j] = np.mean(men_only_stats.astype(np.float)) #men stats survival_table[survival_table != survival_table] = 0 survival_table[survival_table < 0.5] = 0 survival_table[survival_table >= 0.5] = 1 with open('C:/Users/Peter/Documents/Kaggle/Titanic/test.csv', newline='') as csvTestfile: test_file_object = csv.reader(csvTestfile, dialect='excel') header = next(test_file_object) with open('C:/Users/Peter/Documents/Kaggle/Titanic/genderclassmodelpy.csv', 'w', newline='') as csvWriterfile: open_file_object = csv.writer(csvWriterfile, dialect='excel') open_file_object.writerow(["PassengerId", "Survived"]) for row in test_file_object: #loop through each passenger in the test file for j in range(number_of_price_brackets): #for each passenger do try: #try to make the numbers a float row[8] = float(row[8]) except: #if there's no number set the bin according to class bin_fare = 3-float(row[1]) break if row[8] > fare_ceiling: bin_fare = number_of_price_brackets-1 break if row[8] >= j*fare_bracket_size and row[8] < (j+1)*fare_bracket_size: bin_fare = j break if row[3] == 'female': row.insert(1, int(survival_table[0,float(row[1])-1, bin_fare])) open_file_object.writerow((row[0],row[1])) else: row.insert(1, int(survival_table[1,float(row[1])-1,bin_fare])) open_file_object.writerow((row[0],row[1]))
a702ad406b371729655c39acc3f711d8b1658813
haochen208/Python
/pyyyy/07 ๅพช็Žฏ่ฏญๅฅใ€whileๅพช็Žฏ/01whileๅพช็Žฏ.py
680
3.90625
4
# print("ๅฆˆๅฆˆๆˆ‘้”™ไบ†") # print("ๅฆˆๅฆˆๆˆ‘้”™ไบ†") # print("ๅฆˆๅฆˆๆˆ‘้”™ไบ†") # print("ๅฆˆๅฆˆๆˆ‘้”™ไบ†") # print("ๅฆˆๅฆˆๆˆ‘้”™ไบ†") # while ๆกไปถ๏ผš # ๆ‰ง่กŒ่ฏญๅฅ # i = 0 # while i < 10000: # print("ๅฆˆๅฆˆๆˆ‘้”™ไบ†") # print("่ฏทๅŽŸ่ฐ…ๆˆ‘") # i += 1 # i = 0 # while i < 10: # print("ๅฝ“ๅ‰ๆ˜ฏ็ฌฌ%dๆฌกๅพช็Žฏ" % (i+1)) # print("ๆญคๆ—ถi=%d" % i) # i += 1 # โ˜…โ˜…โ˜…โ˜…โ˜…โ˜…โ˜…โ˜…โ˜…โ˜…ๆ‰“ๅฐไธ€่กŒๅๅˆ—ๆ˜Ÿๆ˜Ÿ # i = 0 # while i < 10: # print("โ˜…",end="") # print่‡ชๅธฆๆข่กŒ,end=""ๅฏไปฅๅ…ณ้—ญๆข่กŒ # i += 1 # ่ฎก็ฎ—1-100็š„ๅ’Œ i = 1 sum = 0 while i <= 100: sum += i i += 1 print(sum)
6523c81b3c78db3aba188aa50fd2e65c890eb0d9
Tnoriaki/pyintro
/chap04/4.6.py
246
3.53125
4
# coding: utf-8 nameHandle = open('kids', 'w') for i in range(2): name = raw_input('Enter name: ') nameHandle.write(name + '\n') nameHandle.close() nameHndle = open('kids', 'r') for line in nameHandle: print line nameHandle.close()
950ce41ac11162d097c70ee30c78bdb0480965d6
AnneMay/DESS-bioinfo
/INF8212/Agenda_tel/agenda.py
3,402
3.9375
4
#! bin/bash/python3 ###Introduction au programme print(#Prรฉsentation du programme """ Agenda tรฉlephonique รฉphรฉmรจre Auteur: Anne-Marie Roy Date: automne 2019 """ ) ###Package/import #import csv ###Variables choix = 0 ###Fontions ##Charger le carnet de Contact def charger_contact(agenda): file = open(agenda, "r") list_agenda = [] next(file) for each in file: valeur = each.split(sep = ",") contact = {"nom":valeur[0], "prenom":valeur[1], "num_tel":valeur[2]} list_agenda += [contact] return list_agenda ##Menu def afficher_menu(): print(#Menu de sรฉlection """ 1- Ajouter un contact 2- Afficher le rรฉpertoire complet 3- Rechercher un contact dans le rรฉpertoire 4- Supprimer un contact 5- Quitter le programme """ ) ##validation def valider_entier(entier): while True: #validation de l'input try: entier = int(input("Faites votre sรฉlection: ")) break except ValueError: print("Oops! Choisissez un nombre entre 1 et 5") return entier ##Ajout def ajout(agenda) : print("ajout") nom = input("Nom du contact: ") prenom = input("Prรฉnom du contact: ") tel = input("Numรฉro de tรฉlรฉphone du contact: ") contact = {"nom":nom, "prenom":prenom, "num_tel":tel} agenda += [contact] print("Contact ", nom,", ", prenom, " ajoutรฉ.", sep = "") ##Affichage def affichage(agenda): print("affichage") print("Contenu du rรฉpertoire: ") print("\tindex", "\tnom", "\tprรฉnom", "\tnumรฉro_tel") for i in range(len(agenda)): print("\t", i+1, end = "- ") for key,value in agenda[i].items(): print("\t", value, end = "; ") print("") print("\nFin du rรฉpertoire.") ##Recherhe def recherche(agenda): print("Recherhe") motif = input("Recherche: ") for i in range(0, len(agenda)+1): for j in agenda[i]: if motif in agenda[i][j]: for key,value in agenda[i].items(): print(value, end = "; ") print("") print("\nFin de la recherhce.") ##suppression def suppression(agenda): print("Supression") idx = int(input("Entrez l'index du contact ร  supprimer: ")) - 1 #Rรฉpertoire en base 1 if idx < len(agenda) and idx >= 0: del agenda[idx] print("Le contact avec l'index :", idx+1, "a รฉtรฉ supprimรฉ.") else: print("La suppresion du contact a รฉchouรฉ, vรฉrifiez l'index.") affichage(agenda) ##Quitter def sauver_quit(agenda, output): print("Merci d'avoir utilisรฉ ce programme") output = open(output, 'w') print("Nom, Prenom, telephone", file = output) for i in range(len(agenda)): for key, val in agenda[i].items(): print(val, file = output, end = ", ") print(file = output) quit() ###Programme carnet = charger_contact("agenda.txt") #carnet = [] while choix >= 0: afficher_menu() choix = valider_entier(choix) print if choix == 1: #Ajout de contact ajout(carnet) elif choix == 2: #Affichage du rรฉpertoire affichage(carnet) elif choix == 3: #Recherche recherche(carnet) elif choix == 4: #Supression suppression(carnet) elif choix == 5: #Sortir sauver_quit(carnet, "agenda.txt") else: print("Choisissez un nombre entre 1 et 5") choix = 0
5153f7ad44f468c974d5ec8c1e6dbbd8f3842f1a
ThompsonNJ/CSC231-Introduction-to-Data-Structures
/Lab 7/in_order_list.py
1,915
4.15625
4
# Add item to a_list in the appropriate slot. Items must be in ascending order. def add_in_order(a_list, item): i = 0 while i < len(a_list) and a_list[i] < item: i += 1 a_list.insert(i, item) # Add item to a_list in the appropriate slot. Items must be in ascending order. # item is a string of the form '<priority>_<first name> <last_name>', e.g., '5_James Joyce' # items with a higher number before the underscore _ must appear closer to index len(a_list-1) # items with the same priority appear in the order they are added with the most recently added closer to index 0 def add_in_order_from_string(a_list, item): temp_item = int(''.join(x for x in item if x.isdigit())) i = 0 while i < len(a_list): temp_a_list = int(''.join(y for y in a_list[i] if y.isdigit())) if temp_a_list > temp_item: break i += 1 a_list.insert(i, item) # Part 1: Finish implementing add_in_order() so that sorted_nums is sorted when it is printed nums = [7, 1, 5, 6, 5, 8, 4, 2, 2, 9] sorted_nums = [] for num in nums: add_in_order(sorted_nums, num) print(sorted_nums) # Part 2: Finish implementing add_in_order_from_string() so that sorted_names is sorted when it is printed names = ['7_Roland Purkett', '1_Harold Flaum', '5_Andree Gateley', '6_Palma Fergerson', '5_Nichole Rudzik', '8_Blake Goos', '4_Jennell Maese', '2_Mallory Blaich', '2_Laverne Gowens', '9_Sanjuanita Petramale'] sorted_names = [] for name in names: add_in_order_from_string(sorted_names, name) print(sorted_names) sorted_names = [] # Part 3: Write code below this space to read names from priority_customers.txt (same format as Part 2) and add them to # a list in order using the add_in_order_srom_string() function with open('priority_customers.txt', 'r') as file: names = [] for line in file: print(line) add_in_order_from_string(names, line.strip()) print(names)
bc0875307df470cff44da37aa7c38a59dea8ece0
palcode/opencv_python_tutorials
/core_operations/arithmetics_operations_on_images/demo_image_arithmetics.py
733
3.5
4
# -*- coding: utf-8 -*- """ Created on Thu May 21 15:57:02 2015 @author: Johnny """ #%% import cv2 import numpy as np #%% # mage Addition # There is a difference between OpenCV addition and Numpy addition. # - OpenCV addition is a saturated operation (clamped between min and max) # - Numpy addition is a modulo operation. (number gets recycle after hitting min / max) # Note: uint8 type contains 2**8 = 256 integers. Ranging between 0 and 255. #%% x = np.uint8([250]) x #%% y = np.uint8([10]) y #%% #%% # cv2 addition is clamped between min and max (think color scale) print cv2.add(x,y) # 250+10 = 260 => 255 (max) #%% # NumPy addition is modulo - like a clock. print x+y # 250+10 = 260 % 256 = 4 (255 + 4 = 260)
f5710dbf01ff3f6ef09822d09df8d850b5186edc
hsi-tzu/-numerical-analysis-project
/ๅ‰ฏ็จ‹ๅผ/ๅนณๆ–นๆ น็‰›้ “ๆณ•.py
423
3.96875
4
#Q3.13 #a=float(input('่ผธๅ…ฅa,(aไธๅฏๅฐๆ–ผ0)=')) #่ผธๅ…ฅa def square_root(a): es=(0.5*10**(2-16))/100 #es็š„ๅ€ผ x=1 #x0็š„ไฝ็ฝฎ๏ผŒๅฏๅกซไปปๆ„ๆ•ธๅญ—๏ผŒ้€™่ฃกๅกซ1 while True: #็„ก้™่ฟดๅœˆ xold=x #xๅ›žๅ‚ณ่‡ณxold๏ผŒ้€™ๆจฃๆ‰ๅฏ่จˆ็ฎ—ea x=(x+(a/x))/2 #่ฟญไปฃๅ…ฌๅผ print('a็š„ๅนณๆ–นๆ น=',x) ea=((x-xold)/x) #ea็š„ๅ€ผ print('ea=',ea) if abs(ea)<es: #ea็š„็ต•ๅฐๅ€ผๅฐๆ–ผesๅฐฑ่ทณๅ‡บ่ฟดๅœˆ break
9328a625c5e2f01e73b8cf730ee0ae9ccc080621
childe/leetcode
/3sum/solution.py
1,979
3.671875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ https://leetcode.com/problems/3sum/ Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: Elements in a triplet (a,b,c) must be in non-descending order. (ie, a โ‰ค b โ‰ค c) The solution set must not contain duplicate triplets. For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2) """ import unittest class Solution(object): def _threeSum(self, nums, n, s): """ :type nums: List[int] :type n: int, how much num :type s: int, sum :rtype: List[List[int]] """ if nums == []: return [] if n == 1: if s in nums: return [[s]] return [] rst = [] for i, e in enumerate(nums): if i > 0 and e == nums[i-1]: continue for r in self._threeSum(nums[i+1:], n-1, s-e): rst.append([e]+r) return rst def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() return self._threeSum(nums, 3, 0) class TestSolution(unittest.TestCase): def test_threeSum(self): s = Solution() nums = [] self.assertEqual([],s.threeSum(nums)) nums = [1,2,3,4] self.assertEqual([],s.threeSum(nums)) nums = [-1, 0, 1, 2, -1, -4] answer = [[-1, 0, 1], [-1, -1, 2]] for e in answer: self.assertTrue(e in s.threeSum(nums)) import random nums = [random.randint(-100, 100) for e in range(random.randint(0, 100))] my_answer = s.threeSum(nums) for e in my_answer: self.assertEqual(0, sum(e)) self.assertEqual(3, len(e)) if __name__ == '__main__': unittest.main()
99a5328bc0b8ecb1baa151f2dcb5570b7b35875a
LazyAssassin445/pibox
/wooddesign/dimensions.py
2,139
3.90625
4
#!/usr/bin/python3 import math as maths thickness = int(input("How thick is your wood in millimetres? ")) overhang = int(input("How much do you want the top plank to overhang in millimetres? ")) #work out bird section dimensions birdfr1 = 200+thickness birdfr2 = 150 birdba1 = 200+thickness birdba2 = 150 birdbo1 = 150 birdbo2 = 150 birdto1 = 150+20+(thickness*3) birdto2 = 150 #work out side dimensions si1 = 440 si2 = 150+20+(thickness*3) #work out main dimensions fr1 = 222+thickness fr2 = 150 ba1 = 538+thickness ba2 = 150+(2*thickness) bo1 = 150+20+(2*thickness) bo2 = 150 to1 = round(maths.sqrt(2*(si2*si2)), 0)+overhang to2 = 150+20+(thickness*4) print("\nBIRD SECTION\n") print("Front = ", birdfr1, " X ", birdfr2) print("Back = ", birdba1, " X ", birdba2) print("Bottom = ", birdbo1, " X ", birdbo2) print("Top = ", birdto1, " X ", birdto2) print("\nMAIN SECTION\n") print("Front = ", fr1, " X ", fr2) print("Back = ", ba1, " X ", ba2) print("Bottom = ", bo1, " X ", bo2) print("Top = ", to1, " X ", to2) print("\nSIDE SECTION\n") print("Left = ", si1, " X ", si2) print("Right = ", si1, " X ", si2) print("\n\n With these side panels you must cut a 45 degree angle from the top corner to ", fr1, "off the bottom as shown below!\n") print(" |\\") print(" | \\") print(" | \\") print(" | \\") print(" | \\") print(" | \\") print(" | \\") print(" | \\") print(" | \\") print(" | \\") print(" | \\") print(" 440 mm | |") print(" | |") print(" | |") print(" | |") print(" | |") print(" | | ", fr1, "mm") print(" | |") print(" | |") print(" | |") print(" | |") print(" ________________________") print(" ", si2, "mm")
371f7250db3db5a1ed091f2cfa2d49854ae3ca24
NeilWangziyu/Leetcode_py
/findDuplicates.py
724
3.53125
4
class Solution: def findDuplicates(self, nums): """ :type nums: List[int] :rtype: List[int] """ dict = {} for each in nums: if each not in dict: dict[each] = 1 else: dict[each] += 1 res = [] for each in dict.keys(): if dict[each] == 2: res.append(each) return res def findDuplicates2(self, nums): """ :type nums: List[int] :rtype: List[int] """ a = [] b = set() for each in nums: if each in b: a.append(each) else: b.add(each) return a
84de19c1446d7ec7ab6f717427d232ebd282151c
dinka14/project-2
/english_latin_dict.py
571
3.59375
4
from collections import defaultdict lines = int(input()) english_dict = {} for i in range(lines): line = input() word = line[:line.index(' - ')] english_dict[word] = line[len(' - ') + line.index(' - '):].split(', ') latin_words_dict = defaultdict(list) latin_dict = {} for key in english_dict: for word in english_dict[key]: var = latin_words_dict[word] var_append = var.append(key) latin_dict.update({word: var}) print(len(latin_dict)) for key in sorted(latin_dict): print(key + ' - ' + ', '.join(sorted(latin_dict[key])))
04a89847418bd7865670ba1ebdc1435bc64627b8
Amruta-Pendse/Python_Exercises
/Functions/NumberSquare.py
190
4.21875
4
#Program to print square of numbers between 1 and 30 def num_sq(): l=[] n=0 i=1 while (i<=30): n=i*i l.insert(i-1,n) i+=1 print(l) num_sq()
2ade32ffe404bbd9054740a40ff926584579a485
mredig/CS-Sprint2-Guided-Projects
/bubbleSort.py
672
4.125
4
import random myList = [8, 6, 2, 3, 7, 9, 5, 0, 1, 4] def bubbleSort(items): # iterate over the array # compare each element to neighbor, swap if the item on right is lower # track if there were any swaps or not # if there aren't, sorting done swapped = True while swapped: swapped = False print(items) for index, value in enumerate(items): if index == 0: continue if value < items[index - 1]: items[index - 1], items[index] = items[index], items[index - 1] swapped = True return items random.shuffle(myList) bubbleSort(myList) print(myList)
02d7cfc2acef5ebe52b507794df5cd43497a106f
kgukevin/tjhsst
/Artificial Intelligence I & II (2018-19)/Labs/Lab03 Informed_Search/15Puzzles.py
20,393
3.578125
4
import collections import time import random import cProfile import math import sys from heapq import heappop, heappush # global variables goal = "012345678" size = 3 def goal_test(state): # returns goal test if state is equal to goal if state[-1] == goal: return True return False def swap_tiles(state, char1, char2): # used to swap the values from get_children() to make the actual new children state = state.replace(char2, "\"") state = state.replace(char1, char2) state = state.replace("\"", char1) return state def parity_check(startstate): # check if solvable for all sizes inversions = 0 size = int(math.sqrt(len(startstate))) empty = startstate.index("0") if size % 2 == 1: # checks for parity in odd size puzzles startstate = startstate.replace("0", "") for x in range(0, len(startstate)): # calculates # of inversions for y in range(0, x): if (startstate[x] < startstate[y]): inversions += 1 if (inversions % 2 == 1): return 1 else: return 0 elif (size % 2 == 0): # checks for parity in even size puzzles startstate = startstate.replace("0", "") for x in range(0, len(startstate)): # calculates # of inversions for y in range(0, x): if startstate[x] < startstate[y]: inversions += 1 if empty // size % 2 == 0: # checks which line empty is in. if inversions % 2 == 1: return 1 else: return 0 else: if inversions % 2 == 0: return 1 else: return 0 def get_children2(states): # returns list of children by checking both 1 and 3 indexes away from "0" empty = states[-1].index("0") state = states[-1] previous = states[0] # in order to add all previous states to the next child children = [] if ((empty % size != size - 1)): child1 = swap_tiles(state, state[empty], state[empty + 1]) temp = previous + 'r' # child includes all previous states as a list children.append((temp, child1)) if ((empty % size != 0)): child2 = swap_tiles(state, state[empty], state[empty - 1]) temp = previous + "l" children.append((temp, child2)) if (empty < len(state) - (size)): child3 = swap_tiles(state, state[empty], state[empty + size]) temp = previous + 'd' children.append((temp, child3)) if (empty > (size - 1)): child4 = swap_tiles(state, state[empty], state[empty - size]) temp = previous + 'u' children.append((temp, child4)) return children def get_children3(states): # returns list of children by checking both 1 and 3 indexes away from "0" empty = states[-1].index("0") state = states[-1] previous = states[0] # in order to add all previous states to the next child children = [] if (empty < len(state) - (size)): child3 = swap_tiles(state, state[empty], state[empty + size]) temp = previous + 'd' children.append((temp, states[1], states[2], child3)) if (empty > (size - 1)): child4 = swap_tiles(state, state[empty], state[empty - size]) temp = previous + 'u' children.append((temp, states[1], states[2], child4)) if ((empty % size != size - 1)): child1 = swap_tiles(state, state[empty], state[empty + 1]) temp = previous + 'r' # child includes all previous states as a list children.append((temp, states[1], states[2], child1)) if ((empty % size != 0)): child2 = swap_tiles(state, state[empty], state[empty - 1]) temp = previous + "l" children.append((temp, states[1], states[2], child2)) return children def BFS_edited(startstate, goals, sizes): global goal # edit global variables goal = goals global size size = sizes count = 0 # print(startstate) next = collections.deque([('', startstate)]) # BFS algorithm from class of a list of states visited = {startstate} start = time.process_time() if (parity_check(startstate) != parity_check(goals)): end = time.process_time() print("No Solution." + " seconds to run: %s" % (end - start) + ".") return False, visited, 0, end - start while len(next) != 0: v = next.popleft() count += 1 if (goal_test(v)): end = time.process_time() # print("path length: " + str(len(v[0])) + ". seconds to run: %s" % (end - start) + "."+v[0]) return True, visited, len(v[0]), end - start, count for child in get_children2(v): if not child[-1] in visited: visited.add(child[-1]) # add just new state, not whole child next.append(child) end = time.process_time() print("No Solution." + " seconds to run: %s" % (end - start) + ".") return False, visited, 0, end - start, count def kDFS2(startstate, goals, sizes, depth): global goal # edit global variables goal = goals global size size = sizes startdepth = 0 count = 0 visited = {startstate} next = [('', startdepth, visited, startstate)] # BFS algorithm from class of a list of states start = time.process_time() if (parity_check(startstate) != parity_check(goals)): end = time.process_time() #print("No Solution." + " seconds to run: %s" % (end - start) + ".") return None, count while len(next) != 0: v = next.pop() count += 1 if goal_test(v): end = time.process_time() return True, visited, len(v[0]), end - start, count if v[1] < depth: for c in get_children3(v): if c[-1] not in v[2]: visit = set() for strs in v[2]: visit.add(strs) visit.add(c[3]) c = (c[0], v[1] + 1, visit, c[3]) next.append(c) return None, count def get_childrenA2(states): # returns list of children by checking both 1 and 3 indexes away from "0" empty = states[-1].index("0") state = states[-1] previous = states[2] # in order to add all previous states to the next child children = [] if (empty < len(state) - (size)): child3 = swap_tiles(state, state[empty], state[empty + size]) temp = previous + 'd' children.append((temp, child3)) if (empty > (size - 1)): child4 = swap_tiles(state, state[empty], state[empty - size]) temp = previous + 'u' children.append((temp, child4)) if ((empty % size != size - 1)): child1 = swap_tiles(state, state[empty], state[empty + 1]) temp = previous + 'r' # child includes all previous states as a list children.append((temp, child1)) if ((empty % size != 0)): child2 = swap_tiles(state, state[empty], state[empty - 1]) temp = previous + "l" children.append((temp, child2)) return children def Astar4(startstate, goals, sizes, m): #the god of all Astar jk Astar with implementation of the required explorations global goal # edit global variables goal = goals global size size = sizes next = [(manhattan(startstate, size, goal), random.random(), '', startstate)] # BFS algorithm from class of a list of states visited = set() start = time.process_time() if (parity_check(startstate) != parity_check(goals)): end = time.process_time() #print("No Solution." + " seconds to run: %s" % (end - start) + ".") return False, visited, 0, end - start while len(next) != 0: v = heappop(next) '''heuris = m * (len(v[1]) + 1) + manhattan(v, size, goal) if (str(heuris)+v[-1]) in visited: continue visited.add((str(heuris)+v[-1]))''' if (goal_test(v)): end = time.process_time() #print("path length: " + str(len(v[2])) + ". seconds to run: %s" % (end - start) + "." + v[2]) return True, visited, len(v[2]), end - start for child in get_childrenA2(v): heuris = m * (len(v[2]) + 1) + manhattan(child[-1], size, goal) if not (str(heuris) + child[-1]) in visited: visited.add((str(heuris) + child[-1])) heappush(next, (heuris, random.random(), child[0], child[-1])) end = time.process_time() #print("No Solution." + " seconds to run: %s" % (end - start) + ".") return False, visited, 0, end - start def get_childrenA(states): # returns list of children by checking both 1 and 3 indexes away from "0" empty = states[-1].index("0") state = states[-1] previous = states[2] # in order to add all previous states to the next child children = [] if (empty < len(state) - (size)): child3 = swap_tiles(state, state[empty], state[empty + size]) temp = previous + 'd' children.append((temp, child3)) if (empty > (size - 1)): child4 = swap_tiles(state, state[empty], state[empty - size]) temp = previous + 'u' children.append((temp, child4)) if ((empty % size != size - 1)): child1 = swap_tiles(state, state[empty], state[empty + 1]) temp = previous + 'r' # child includes all previous states as a list children.append((temp, child1)) if ((empty % size != 0)): child2 = swap_tiles(state, state[empty], state[empty - 1]) temp = previous + "l" children.append((temp, child2)) return children def Astar5(startstate, goals, sizes, m): #working order messed up, essentially Astar 4 global goal # edit global variables goal = goals global size size = sizes next = [(manhattan(startstate, size, goal), random.randint(0, 100), '', startstate)] # BFS algorithm from class of a list of states visited = set() start = time.process_time() if (parity_check(startstate) != parity_check(goals)): end = time.process_time() print("No Solution." + " seconds to run: %s" % (end - start) + ".") return False, visited, 0, end - start while len(next) != 0: v = heappop(next) '''heuris = m * (len(v[1]) + 1) + manhattan(v, size, goal) if (str(heuris)+v[-1]) in visited: continue visited.add((str(heuris)+v[-1]))''' if (goal_test(v)): end = time.process_time() print("path length: " + str(len(v[2])) + ". seconds to run: %s" % (end - start) + "." + v[2]) return True, visited, len(v[2]), end - start for child in get_childrenA(v): heuris = m * (len(v[2]) + 1) + manhattan(child[-1], size, goal) if not (str(heuris) + child[-1]) in visited: visited.add((str(heuris) + child[-1])) heappush(next, (heuris, random.randint(0, 100), child[0], child[-1])) end = time.process_time() print("No Solution." + " seconds to run: %s" % (end - start) + ".") return False, visited, 0, end - start def Astar3B(startstate, goals, sizes, m): # modified to calculate nodes/ sec for A*, nodes/sec IDDFS and BFS with counter within their code segments global goal # edit global variables goal = goals global size size = sizes count = 0 next = [(manhattan(startstate, size, goal), random.randint(0, 100), '', startstate)] # BFS algorithm from class of a list of states visited = set() start = time.process_time() if (parity_check(startstate) != parity_check(goals)): end = time.process_time() print("No Solution." + " seconds to run: %s" % (end - start) + ".") return False, visited, 0, end - start while len(next) != 0: v = heappop(next) count += 1 '''heuris = m * (len(v[1]) + 1) + manhattan(v, size, goal) if (str(heuris)+v[-1]) in visited: continue visited.add((str(heuris)+v[-1]))''' if (goal_test(v)): end = time.process_time() print("path length: " + str(len(v[2])) + ". seconds to run: %s" % (end - start) + "." + v[2]) return True, visited, len(v[2]), end - start, count for child in get_childrenA(v): heuris = m * (len(v[2]) + 1) + manhattan(child[-1], size, goal) if not (str(heuris) + child[-1]) in visited: visited.add((str(heuris) + child[-1])) heappush(next, (heuris, random.randint(0, 100), child[0], child[-1])) end = time.process_time() print("No Solution." + " seconds to run: %s" % (end - start) + ".") return False, visited, 0, end - start, count def IDDFS(startstate, goals, sizes, depth): count = 0 for k in range((depth + 1)): solution = kDFS2(startstate, goals, sizes, k) count+=solution[-1] if solution[0] != None: return (solution[0],solution[1],solution[2],solution[3],count) return None def manhattan(state, sizes, goals): #returns estimate of distance of state to goal - never overestimating global goal # edit global variables goal = goals global size size = sizes sizes = size ** 2 totaldist = 0 for x in state: index = goal.index(x) index2 = state.index(x) if index == index2: totaldist += 0 elif x != "0": corrow = index // size corcol = index % size row = index2 // size column = index2 % size totaldist += abs(row - corrow) + abs(column - corcol) return totaldist def BFS3C(startstate, sizes): #original code found frequency of pathlengths, edited to return dictionary of pathlengths to states global size size = sizes print(startstate) next = collections.deque([('', startstate)]) visited = {startstate} start = time.process_time() paths = {} while len(next) != 0: v = next.popleft() if (goal_test(v)): print("solved") # print(len(v)-1) end = time.process_time() # instead of returning after goal found, BFS_part2 keeps running through all of states for child in get_children2(v): if not child[-1] in visited: visited.add(child[-1]) next.append(child) if (not len(child[0]) in paths.keys()): paths[len(child[0])] = [child[-1]] #add states instead of frequency paths[len(child[0])].append(child[-1]) end = time.process_time() print("Number of Visited States: %s" % (len(visited))) print("seconds to run: %s" % (end - start)) print() for x in paths.keys(): print(paths[x][random.randint(0, len(paths[x]) - 1)]) return paths def BFS3D(startstate, sizes): #essentially same as above but with a breakpoint to ensure code can give an output at some time global size size = sizes print(startstate) next = collections.deque([('', startstate)]) visited = {startstate} start = time.process_time() paths = {} while len(next) != 0: v = next.popleft() if (goal_test(v)): print("solved") # print(len(v)-1) end = time.process_time() # instead of returning after goal found, BFS_part2 keeps running through all of states for child in get_children2(v): if not child[-1] in visited: visited.add(child[-1]) next.append(child) if (not len(child[0]) in paths.keys()): paths[len(child[0])] = [child[-1]] paths[len(child[0])].append(child[-1]) if len(paths.keys()) == 30: for x in paths.keys(): print(paths[x][random.randint(0, len(paths[x]) - 1)]) return paths end = time.process_time() print("Number of Visited States: %s" % (len(visited))) print("seconds to run: %s" % (end - start)) print() for x in paths.keys(): print(paths[x][random.randint(0, len(paths[x]) - 1)]) return paths # paths = BFS3C("012345678",3) # paths = BFS3D("0ABCDEFGHIJKLMNOPQRSTUVWX",5) # BFS_edited("087654321","012345678",3) # run_100_tests() # filename = sys.argv[1] #Astar4("ALBCDG0KHIEFQMNUJTRSOPVWX","0ABCDEFGHIJKLMNOPQRSTUVWX",5,1) '''filename = "15_puzzles.txt" file = open(filename) list = file.readlines() totaltime = 0 #for x in range(0, 20): Astar4("A0BCDEFGHIJKLMNO","0ABCDEFGHIJKLMNO",4,1)''' ''' temp = Astar4(str(list[30].rstrip()), str(list[0].rstrip()), 4, .5) temp = Astar4(str(list[30].rstrip()), str(list[0].rstrip()), 4, .6) temp = Astar4(str(list[30].rstrip()), str(list[0].rstrip()), 4, .7) temp = Astar4(str(list[30].rstrip()), str(list[0].rstrip()), 4, .8) temp = Astar4(str(list[30].rstrip()), str(list[0].rstrip()), 4, .9) temp = Astar4(str(list[30].rstrip()), str(list[0].rstrip()), 4, 1) temp = Astar4(str(list[30].rstrip()), str(list[0].rstrip()), 4, 1.1) temp = Astar4(str(list[30].rstrip()), str(list[0].rstrip()), 4, 1.2) temp = Astar4(str(list[30].rstrip()), str(list[0].rstrip()), 4, 1.3) temp = Astar4(str(list[30].rstrip()), str(list[0].rstrip()), 4, 1.4) temp = Astar4(str(list[30].rstrip()), str(list[0].rstrip()), 4, 1.5) ''' '''for x in range(1, len(list)): list[x] = list[x].rstrip() if list[x] != '': print("Puzzle: " + str(x) + " " + list[x]) start = time.process_time() temp = IDDFS(str(list[x]), str(list[0].rstrip()), 4, 53) temp = Astar3B(str(list[x]), "0ABCDEFGHIJKLMNO", 4,1) if temp[-2]>10: #when running Astar print("Nodes per Second: "+str(temp[-1]/temp[-2])) end = time.process_time() if temp != None: print("IDDFS: " + str(temp[2])+ " " + str(end-start)) totaltime += end-start if end-start>10: print("Nodes per Second: "+str(temp[-1]/(end-start))) try: temp = BFS_edited(str(list[x]), str(list[0].rstrip()), 4) if temp != None: print("BFS: " + str(temp[2]) + " " + str(temp[-2])) totaltime += temp[3] if temp[-2]>10: print("Nodes per Second: "+str(temp[-1]/temp[-2])) except: print("Memory Error")''' #operation = sys.argv[1] #state = sys.argv[2] filename = sys.argv[1] file = open(filename) list = file.readlines() for x in range(0, len(list)): list[x] = list[x].rstrip() if list[x] != '': operation = list[x][0] state = list[x][2:] if operation == "B": temp = BFS_edited(state,"0ABCDEFGHIJKLMNO",4) print(str(temp[2])+ " BFS " + str(temp[-2])) if operation == "I": temp = IDDFS(state,"0ABCDEFGHIJKLMNO",4,50) print(str(temp[2])+ " ID-DFS " + str(temp[-2])) if operation == "2": print("Bidirectional BFS was not implemented.") if operation == "A": temp = Astar4(state,"0ABCDEFGHIJKLMNO",4,1) print(str(temp[2])+ " A* " + str(temp[-1])) if operation == "7": temp = Astar4(state,"0ABCDEFGHIJKLMNO",4,0.7) print(str(temp[2]) + " A*: 0.7 " + str(temp[-1])) temp = Astar4(state, "0ABCDEFGHIJKLMNO", 4, 0.7) print(str(temp[2]) + " A*: 0.7 " + str(temp[-1])) temp = Astar4(state, "0ABCDEFGHIJKLMNO", 4, 0.7) print(str(temp[2]) + " A*: 0.7 " + str(temp[-1])) if operation == "!": temp = BFS_edited(state, "0ABCDEFGHIJKLMNO", 4) print(str(temp[2]) + " BFS " + str(temp[-2])) temp = IDDFS(state, "0ABCDEFGHIJKLMNO", 4, 50) print(str(temp[2]) + " ID-DFS " + str(temp[-2])) print("Bidirectional BFS was not implemented.") temp = Astar4(state, "0ABCDEFGHIJKLMNO", 4, 1) print(str(temp[2]) + " A* " + str(temp[-1])) temp = Astar4(state, "0ABCDEFGHIJKLMNO", 4, 0.7) print(str(temp[2]) + " A*: 0.7 " + str(temp[-1])) temp = Astar4(state, "0ABCDEFGHIJKLMNO", 4, 0.7) print(str(temp[2]) + " A*: 0.7 " + str(temp[-1])) temp = Astar4(state, "0ABCDEFGHIJKLMNO", 4, 0.7) print(str(temp[2]) + " A*: 0.7 " + str(temp[-1]))
d6612bcd32d8c138fd726206048250954d02d91e
anumala2/cs3b
/CS3B/aadithyaAnumalaLab5.py
1,402
3.84375
4
############################################### # CS 21B Intermediate Python Programming Lab #5 # Topics: web urllib # Description: This program finds the html source # from nasonline.org and finds the # frequency of certain key terms and # prints that out for the user. # Input: NA # Output: date and frequncies # Version: 3.7.0 # Development Environment: IDLE # Developer: Aadithya Anumala # Student ID: 20365071 # Date: 05/21/19 ############################################### from urllib import request from datetime import date nas = request.Request("http://www.nasonline.org") resp = request.urlopen(nas) pars = resp.read() pars = pars.decode(encoding='UTF-8',errors='strict') topics = ["research", "climate", "evolution", "cultural", "leadership", "nation", "physical", "science", "biological", "global"] print(f"Today's date is {date.today():%Y-%m-%d}\n") for topic in topics: count = str(pars.count(topic)) print(f"{topic} appears {count} times") """ RESTART: /Users/aadianumala/Documents/CollegeCompSci/CS3B/aadithyaAnumalaLab5.py Today's date is 2019-05-21 research appears 8 times climate appears 3 times evolution appears 3 times cultural appears 4 times leadership appears 2 times nation appears 17 times physical appears 1 times science appears 19 times biological appears 1 times global appears 1 times >>> """
8ba90a50182e5779d24e4ab1bb8503a89c7790a5
aa88bb/Learn_Python_From_0_to_1
/2.2.1.py
274
3.84375
4
import random def compareNum(num1,num2): if(num1 > num2): return 1 elif(num1 == num2): return 0 else: return -1 num1 = random.randrange(1,9) num2 = random.randrange(1,9) print(num1,num2,compareNum(num1,num2)) print(str(num1)+str(num2))
f6fd2ca35e0789161ed99a5e13aa6dcba7c7d557
maru12117/python_practice
/210611_practice_1.py
332
3.78125
4
'''stone = list(map(float,input("๋Œ์˜ ๋ฌด๊ฒŒ๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š” : ").split())) total=0 i = 0 for x in stone: i+=1 print(i,"๋ฒˆ์จฐ ๋Œ\n ๋ฌด๊ฒŒ(g): ", x) total = total+x avg = total/len(stone) print("\nํ‰๊ท ", avg)''' '''s = map(int,input("์ž…๋ ฅํ•ด์ฃผ์„ธ์š” : ").split()) print(type(s)) print(s)'''
bd1d0796086780f97ea4fef81e145b29672a3590
gitzx/Data-Structure-Algorithm
/LeetCode_Python/Math/Super_Pow.py
413
3.625
4
''' Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array. Example1: a = 2 b = [3] Result: 8 Example2: a = 2 b = [1,0] Result: 1024 ''' class Solution(object): def superPow(self, a, b): ans, pows = 1, a for x in b[::-1]: ans = (ans * ((pows ** x) % 1337)) % 1337 pows = (pows ** 10) % 1337 return ans
cca820ed893eb2ad3073586720e694ab3d323d89
OwenBowler/BCPR301A2
/module.py
1,028
3.53125
4
class Module: """create a module that will hold all the classes >>> a = Module() >>> a.create_module('test_module', ['classOne', 'classTwo', 'classThree']) >>> print(a.module_name) test_module >>> print(len(a.all_my_classbuilders)) 3 """ module_name = str def __init__(self): self.module_name = "" self.all_my_classbuilders = [] def create_module(self, new_module_name, new_classes): self.module_name = new_module_name.lower() for a_class in new_classes: self.all_my_classbuilders.append(a_class) def write_files(self): folder_name = self.module_name my_files = [] for a_class in self.all_my_classbuilders: file_data = "" file_data += a_class.print_class() file_name = a_class.name.lower() + ".py" my_files.append(tuple((file_name, file_data))) return (folder_name, my_files) if __name__ == "__main__": from doctest import testmod testmod()
02c35bb47654b319c845fa4b4783ad4530f04091
Harshad141/Maths-Programs
/Factorial.py
213
4.0625
4
Factorial def recur_func(n) if n==1 return 1 else return n*recur_func(n-1) num = int(input(value of n)) if num<0 print(no factorial) elif num==0 return 1