blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
a8ba28874e2364d7e356801451998561b61ecfb1
daniel-reich/turbo-robot
/XQwPPHE6ZSu4Er9ht_10.py
1,970
4.3125
4
""" A number is Economical if the quantity of digits of its prime factorization (including exponents greater than 1) is equal to or lower than the digit quantity of the number itself. Given an integer `n`, implement a function that returns a string: * `"Equidigital"` if the quantity of digits of the prime factorization (including exponents greater than 1) is equal to the quantity of digits of `n`; * `"Frugal"` if the quantity of digits of the prime factorization (including exponents greater than 1) is lower than the quantity of digits of `n`; * `"Wasteful"` if none of the two above conditions is true. ### Examples is_economical(14) ➞ "Equidigital" # The prime factorization of 14 (2 digits) is [2, 7] (2 digits) # Exponents equal to 1 are not counted is_economical(125) ➞ "Frugal" # The prime factorization of 125 (3 digits) is [5^3] (2 digits) # Notice how exponents greater than 1 are counted is_economical(1024) ➞ "Frugal" # The prime factorization of 1024 (4 digits) is [2^10] (3 digits) is_economical(30) ➞ "Wasteful" # The prime factorization of 30 (2 digits) is [2, 3, 5] (3 digits) ### Notes * Any given `n` will be a positive integer greater than 1. * Remember to count also the exponents greater than 1 into the prime factorization: 2¹ = 2 (one digit), 2² = 22 (two digits), 2¹° = 210 (three digits)... """ def is_economical(n): i = 2 a = n factDict = {} while a > 1: if a % i == 0: if i not in factDict: factDict[i] = 1 else: factDict[i] += 1 a = a // i else: i += 1 ctr = 0 for k,v in factDict.items(): ctr += len(str(k)) if v != 1: ctr += len(str(v)) if len(str(n)) > ctr: return 'Frugal' elif len(str(n)) == ctr: return 'Equidigital' else: return 'Wasteful'
db92d6c44041067b4166da11227060bff483a822
qiangayz/MyCode
/面向对象/继承1.py
1,151
3.890625
4
#coding=utf-8 class people(object): # def __init__(self): # self.age = 45 # print('People') def sleep(self): print(123) class Relation(object): def __init__(self): print('Relation') class Man(people,Relation): def __init__(self): super(Man,self).__init__() #这里继承了两个类,但是只会执行people的构造方法,不会执行relation的,如果people没有构造函数就走relation def sleep(self): #people.sleep(self) super(Man,self).sleep() print(456) # a = Man() # a.sleep() #深度优先于广度优先 """ python2中经典类是深度优先,新式类是广度优先,python3中都是广度优先 """ class A(object): def __init__(self): print('A') class B(A): def __init__(self): print('B') class C(A): def __init__(self): print('C') class D(B,C): # def __init__(self): # pass """ 深度优先:若D没有初始化函数,先去找B,B也没有去找A,A也没有再找C 广度优先:若D没有初始化函数,先去找B,B也没有去找C,C也没有去找A """
b30a7b6f6606c4c58a956fd5b40f8010eb860826
gclegg4201/python
/blackjack.py
1,616
3.5625
4
from random import randint def shuffle(): global deck deck=[] for suit in range(0,4): for value in range(1,14): if(value<10): deck.append(value) else: deck.append(10) for tweak in range(0,10): deck.pop(randint(0,len(deck)-1)) def drawcard(): global deck card=deck.pop(randint(0,len(deck)-1)) return card def round(): global players global deck global playercard shuffle() dealercard=[] playerbet=[] for player in range(0,players): playercard[player].append(drawcard()) playerbet[player].append([]) dealercard.append(drawcard()) print("Dealer: {0}".format(dealercard)) for player in range(0,players): print("Player {0} has {1}".format(player,playercard[player])) def game(): global players global startmoney global playercard playermoney=[] playercard=[] for player in range(0,players): playermoney.append(startmoney) playercard.append(player) round() if __name__=="__main__": global players global startmoney while True: try: players=(int(input("Number of Players: "))) if(players<1): raise ValueError else: break except: print("Invalid Input") while True: try: startmoney=(int(input("Starting Money: "))) if(startmoney<1): raise ValueError else: break except: print("Invalid Input") game()
03c15b351bf6ae113a7e8eeb28a5afc9077fdbbf
SethBixler/Python-Projects
/clothingPicker.py
3,609
4.03125
4
# Author : Seth Bixler # Description : Lab 3, CSCI 141 # File : clothingPicker.py # Date : October 11, 2016 # Lines 1-5 # Ask the user if it is windy # Receive input from user and save into a variable # If it windy, output "Be sure to not bring an umbrella because it is windy." # If it is not windy, output "It is not windy, bring an umbrella if you please." isWindy = (input("Is it windy? (yes or no) ")) if (isWindy == "yes") : print("Be sure not to bring an umbrella because it is windy.") else : print("It is not windy, bring an umbrella if you please.") # Lines 6-11 # Ask the user if it is windy # Receive input from user and save into a variable # Ask the user if it is sunny # Receive input from user and save into a variable # If it is both windy and sunny, output "It is windy and sunny, so don't bring a umbrella and wear a coat." # If it is not both windy and sunny, outut "It is not both windy and sunny." isWindy = (input("Is it windy? (yes or no) ")) isSunny = (input("Is it sunny? (yes or no) ")) if (isWindy == "yes" and isSunny == "yes") : print("It is windy and sunny, so don't bring a umbrella and wear a coat.") if (isWindy == "no" or isSunny == "no") : print("It is not both windy and sunny.") # Lines 12-21 # Ask the user if it is windy # Receive input from user and save into a variable # Ask the user if it is sunny # Receive input from user and save into a variable # If it is both windy and sunny, output "It is windy and sunny." # If it is windy and not sunny, output "It is windy and not sunny." # If it is sunny and not windy, output "It is sunny and not windy." # If it is neither sunny nor windy, output "It is neither sunny nor windy." isWindy = (input("Is it windy? (yes or no) ")) isSunny = (input("Is it sunny? (yes or no) ")) if (isWindy == "yes" and isSunny == "yes") : print("It is windy and sunny.") if (isWindy == "yes" and isSunny == "no") : print("It is windy and not sunny.") if (isWindy == "no" and isSunny == "yes") : print("It is sunny and not windy.") if (isWindy == "no" and isSunny == "no") : print("It is neither sunny nor windy.") # Lines 22-37 # Ask the user if it is sunny # Receive input from the user and save into a variable # Ask user what the temperature is # Receive input from the user and save into a variable # If it is sunny and less than 60 degrees, output "Wear a sweater." # If it is sunny and 60 degrees exactly, output "Woo hoo, it is 60 degrees. Wear what you want." # If it is sunny and more than 60 degrees, output "Wear a tee shirt and flip flops." # If it is not sunny and less than 40 degress, output "Wear a coat and hat." # If it is not sunny and between 40 and 50 degrees, output "Not quite freezing, but close. Bundle up." # If it is not sunny and 50 degrees exactly, output "A jacket is best." # If it is not sunny and more than 50 degrees, output isSunny = (input("Is it sunny? (yes or no) ")) temp = (input("What is the temperature? (enter integer in degrees fahrenheit) ")) if (isSunny == "yes" and temp < "60") : print("Wear a sweater.") if (isSunny == "yes" and temp == "60") : print("Woo hoo, it is 60 degrees. Wear what you want.") if (isSunny == "yes" and temp > "60") : print("Wear a tee shirt and flip flops.") if (isSunny == "no" and temp < "40") : print("Wear a coat and hat.") if (isSunny == "no" and "40" <= temp < "50") : print("Not quite freezing, but close. Bundle up.") if (isSunny == "no" and temp == "50") : print("A jacket is best.") if (isSunny == "no" and temp > "50") : print("Wear a long sleeved shirt.")
60e43fbf0eab1ab59a90e555c010d8297adfe9ae
alexchao/problems
/python/math_problems_test.py
1,401
3.75
4
# -*- coding: utf-8 -*- import unittest from math_problems import count_staircase_climb from math_problems import is_power_of_three class IsPowerOfThreeTest(unittest.TestCase): def test_zero(self): self.assertFalse(is_power_of_three(0)) def test_one(self): self.assertTrue(is_power_of_three(1)) def test_three(self): self.assertTrue(is_power_of_three(3)) def test_basic(self): self.assertTrue(is_power_of_three(9)) self.assertTrue(is_power_of_three(27)) self.assertTrue(is_power_of_three(81)) self.assertTrue(is_power_of_three(243)) def test_multiples_but_not_powers(self): self.assertFalse(is_power_of_three(12)) self.assertFalse(is_power_of_three(18)) self.assertFalse(is_power_of_three(99)) self.assertFalse(is_power_of_three(120)) class CountStaircaseClimbTest(unittest.TestCase): def test_base_case(self): self.assertEqual(count_staircase_climb(0), 0) self.assertEqual(count_staircase_climb(1), 1) self.assertEqual(count_staircase_climb(2), 2) self.assertEqual(count_staircase_climb(3), 4) def test_four_five_six(self): self.assertEqual(count_staircase_climb(4), 7) self.assertEqual(count_staircase_climb(5), 13) self.assertEqual(count_staircase_climb(6), 24) if __name__ == '__main__': unittest.main()
426550f2e9d95cdc2b615a9236dce6aa671d5083
Jiezhi/myleetcode
/src/88-MergeSortedArray.py
1,034
4.03125
4
#!/usr/bin/env python """ https://leetcode.com/problems/merge-sorted-array/description/ Created on 2018-11-16 @author: '[email protected]' Reference: """ class Solution: def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """ n1 = 0 n2 = 0 while n2 < n: # nums1 run out of number, just copy all left nums2 numbers if n1 >= m + n2: for i in range(n2, n): nums1[n1 + i - n2] = nums2[i] return if nums1[n1] > nums2[n2]: for i in range(m + n2, n1, -1): nums1[i] = nums1[i - 1] nums1[n1] = nums2[n2] n2 += 1 n1 += 1 def test(): nums1 = [1, 2, 3, 0, 0, 0] nums2 = [2, 5, 6] Solution().merge(nums1, 3, nums2, 3) assert nums1 == [1, 2, 2, 3, 5, 6]
88437f63c3e2f6cec3102a73f42c1d08f206f07e
valdecler/estudo
/exercicio34.py
639
4
4
#Crie um script com uma lista , exiba 2 msgs na tela, ambas vão ter interação #com o loop for, a segunda msg estará fora do bloco, e so vai ser executada #ao final do loop, apenas o ultimo elemento da lista aparecerá na 2msg, #explique por que isso acontece. nomes = [ 'rafael', 'danela', 'Carolina'] for nome in nomes: print (nome.title () + "vamos comer uma pizza!") print ( "eu mal posso esperar para comer a proxima fatia, " + nome.title () + "\n") #Este é um erro lógico . A sintaxe é código Python válida o codigo, mas #faz não produzir o resultado desejado porque ocorre um problema na sua lógica
14c36f02e70c67be9d3eaa43b7fdf8117f88e7fb
danmarton/code
/Python/prompt.py
394
3.5
4
from sys import argv script, user_name = argv prompt = 'Prompt: ' print "Hi %s, I'm %s!" % (user_name, script) print "What do you want to say?" likes = raw_input(prompt) print "Where do yo live?" lives = raw_input(prompt) print "What kind of computer do you have?" computer = raw_input(prompt) print """ You said %r. You live in %r. You have a %r computer. """ % (likes, lives, computer)
348e63307433a14fa6414cc4246ef55fbeba24fe
fountainhead-gq/MachineLearning
/Matplotlib/gallery/showcase/showcase-12.py
4,919
4
4
#coding = utf-8 #------------------------ # An implementation of the Domino Shuffling Algorithm on Aztec Diamond Graphs. #------------------ import random import matplotlib.pyplot as plt import matplotlib.patches as mps class Aztec_Diamond: def __init__(self, n): """ Use a dict to represent a tiling of the graph. The keys of the dict are the "coordinates" of the unit squares. Each square is specified by its left bottom corner (i, j). The j-th row (j from y=-n to y=n-1) has min(n+1+j, n-j) unit squares. """ self.order = n self.tile = dict() # initially all squares are holes, hence assigned with 'None self.cells = [] for j in range(-n, n): k = min(n+1+j, n-j) for i in range(-k, k): self.cells.append((i, j)) self.tile = {cell: None for cell in self.cells} def delete(self): """ Delete all bad blocks in a tiling. A bad block is a pair of dominoes that lie in a 2x2 square and move towards each other under the shuffling. To find all bad blocks one must start the search from the boundary. """ for i, j in self.cells: try: if ((self.tile[(i, j)] == 'n' and self.tile[(i+1, j)] == 'n' and self.tile[(i, j+1)] == 's' and self.tile[(i+1, j+1)] == 's') or (self.tile[(i, j)] == 'e' and self.tile[(i, j+1)] == 'e' and self.tile[(i+1, j)] == 'w' and self.tile[(i+1, j+1)] == 'w')): self.tile[(i, j)] = None self.tile[(i+1, j)] = None self.tile[(i, j+1)] = None self.tile[(i+1, j+1)] = None except: pass return self def slide(self): ''' move each domino one sterp in the partial tiling ''' new_board = Aztec_Diamond(self.order+1) for (i, j) in self.cells: if self.tile[(i, j)] == 'n': new_board.tile[(i, j+1)] = 'n' if self.tile[(i, j)] == 's': new_board.tile[(i, j-1)] = 's' if self.tile[(i, j)] == 'w': new_board.tile[(i-1, j)] = 'w' if self.tile[(i, j)] == 'e': new_board.tile[(i+1, j)] = 'e' return new_board def create(self): # To fill in the bad blocks one must start the search from the boundary. for i, j in self.cells: try: if (self.tile[(i, j)] == None and self.tile[(i+1, j)] ==None and self.tile[(i, j+1)] == None and self.tile[(i+1, j+1)] == None): if random.random() > 0.5: # Here we fill the bad blocks with a pair of dominoes leaving each # other since a bad block in az(n) will be a good block in az(n+1). self.tile[(i, j)] = 's' self.tile[(i+1, j)] = 's' self.tile[(i, j+1)] = 'n' self.tile[(i+1, j+1)] = 'n' else: self.tile[(i, j)] = 'w' self.tile[(i+1, j)] = 'e' self.tile[(i, j+1)] = 'w' self.tile[(i+1, j+1)] = 'e' except: pass return self def draw(self): for (i, j) in self.cells: # we just need to find the leftbottom corner of the black square of each domino # This corner along with the type of the domino determines its position if (i+j+self.order) % 2 == 1: if self.tile[(i, j)] == 'n': p = mps.Rectangle((i-1,j), 2, 1, fc='r', ec='w', lw=lw) ax.add_patch(p) if self.tile[(i,j)] == 's': p = mps.Rectangle((i,j), 2, 1, fc='y', ec='w', lw=lw) ax.add_patch(p) if self.tile[(i,j)] == 'w': p = mps.Rectangle((i,j), 1, 2, fc='b', ec='w', lw=lw) ax.add_patch(p) if self.tile[(i,j)] == 'e': p = mps.Rectangle((i,j-1), 1, 2, fc='g', ec='w', lw=lw) ax.add_patch(p) return self N = 50 dpi = 100 fig = plt.figure(figsize=(8, 8), dpi=dpi) lw = dpi * fig.get_figwidth() / (20.0 * (N+1)) ax = fig.add_axes([0, 0, 1, 1], aspect=1) ax.axis('off') ax.axis([-N-1, N+1, -N-1, N+1]) az = Aztec_Diamond(0) for i in range(N): az = az.delete().slide().create() print('saving image with matplotlib...') az.draw() fig.savefig('random_tiling.png') print('done!')
96c9079163cbb37571ba2fec852bb0907838fc0a
rajureddym/python
/coding/problems/list_read_scores_find_runnerup.py
351
3.796875
4
if __name__ == '__main__': n = int(input()) arr = map(int, input().split()) a = list(set(list(arr))) print('printing list of scores after removing duplicates: ' + str(a)) print('printing list of scores after removing duplicates & sorting : ') a.sort() print(a) print('runner up score in a given list is: ' + str(a[-2]))
cfb8b0bfbffc17b6ee2a8959499b42e706482158
lodgeinwh/Study
/Python/LeetCode/Algorithm/007. Reverse Integer.py
441
3.703125
4
# !/usr/bin/env python3 # -*- coding: utf-8 -*- # @author: Lodgeinwh # @file: 007. Reverse Integer.py # @time: 2019/04/09 23:45:16 # @contact: [email protected] # @version: 1.0 class Solution: def reverse(self, x: int) -> int: if x >= 0: ans = int(str(x)[::-1]) else: ans = int(str(-x)[::-1]) * -1 if x > 2 ** 31 - 1 or x < -1 * 2 ** 31: return 0 else: return ans
365c172f481c50a948643eca8dec761260940368
salam1416/100DaysOfCode
/day11.py
413
4.1875
4
# Python Operators 2 # Logical Operators x = 4 print(x > 2 and x < 10) print( x < 2 or x > 0 ) print( not(x>3) ) print(x is 4) print( x is not 3) x = ['s','m'] y = ['s','m'] print(x is y) print('s' in x) print('m' not in y) # Bitwise operators # 1 is 01 # 2 is 10 print(1&2) # should be zero # 3 is 011 # 7 is 111 print(3&7) # should be 011 which is 3 print(3|7) # should be 111 which is 7 print(~2) # (-x-1) ss
b2b79819c2d71a9cb39b009eebcc80d84214bc48
AtiqulHaque/geeksforgeeks
/nth-item-through-sum.py
3,203
4.125
4
""" Given two sorted arrays, we can get a set of sums(add one element from the first and one from second). Find the N’th element in the set considered in sorted order. Note: Set of sums should have unique elements. -------------------------------------------------- Input : arr1[] = {1, 2} arr2[] = {3, 4} N = 3 Output : 6 We get following elements set of sums. 4(1+3), 5(2+3 or 1+4), 6(2+4) Third element in above set is 6. Input : arr1[] = {1, 3, 4, 8, 10} arr2[] = {20, 22, 30, 40} N = 4 Output : 25 We get following elements set of sums. 21(1+20), 23(1+22 or 20+3), 24(20+4), 25(22+3)... Fourth element is 25. ------------------------------------- Input: The first line of input contains an integer T denoting tghe number of test cases. Then T test cases follow. Each test case contains two integers m and n denoting the size of the two arrays respectively. The next two lines contains m and n space separated elements forming both the arrays respectively. The last line contains the value of N. Output: Print the value of Nth element in set. If Nth element doesn't exist in set print -1. Constraints: 1<=T<=10^5 1<=m,n<=10^5 1<=arr1[i],arr2[j]<=10^5 1<=N<=m*n Example: Input: 2 2 2 1 2 3 4 3 5 4 1 3 4 8 10 20 22 30 40 4 Output: 6 25 """ import math # Input number of test cases t = int(input()) arr = [0] * t l1 = [0]* t l2 = [0]* t nth = [0]* t def binarySearchInsertion(item, itemList): if len(itemList) == 0: itemList.append(item) return itemList if len(itemList) == 1: if itemList[0] == item: return itemList itemList.append([]) if itemList[0] > item : temp = itemList[0] itemList[0] = item itemList[1] = temp else: itemList[1] = item return itemList start = 0 end = len(itemList) - 1 while True: calculate = end - start if(calculate == 1): if itemList[end] == item or itemList[start] == item: return itemList if item > itemList[end]: itemList.append([]) for i in range(end + 1,len(itemList)): temp = itemList[i] itemList[i] = item item = temp return itemList else: itemList.append([]) for i in range(start,len(itemList)): temp = itemList[i] itemList[i] = item item = temp return itemList mid = math.ceil((start + end) / 2) if itemList[mid] > item: end = mid if itemList[mid] < item: start = mid if itemList[mid] == item: return itemList # print(binarySearchInsertion(4,[4,5])) for i in range(t): arr[i] = list(map(int, input().split())) l1[i] = list(map(int, input().split())) l2[i] = list(map(int, input().split())) nth[i] = int(input()) r = [] for j in range(len(l1[i])): for k in range(len(l2[i])): temp = l1[i][j] + l2[i][k] binarySearchInsertion(temp,r) print (r[nth[i] - 1])
9c3c78034cdaa232dd3b7707eea5d32f6fd2cc96
ramudasari123/PythonPractice
/UdemyDemo/Decorators.py
841
3.703125
4
def Master(name="ram"): def child1(name): print("I am child1 {}".format(name)) def child2(name): print(f"I am child2 {name}") if(name.upper()=="RAM"): return child1 else: return child2 calling=Master("nadi") calling("nadi") ###Passing one method/function as arguments to another function############## def sayhello(): print('Hi Ram') def callerfunc(somefunc): print("I am calling some function") print(somefunc()) callme=callerfunc(sayhello) #callme() ####################Decators######################### def maindec(somefunc): def func1(): print('code before modification') somefunc() print("code after modification") return func1() @maindec def somedefunc(): print("decorator main func called") #calldec=maindec(somedefunc) #calldec()
19839a9ccb9fb048dd8a03255080f10234f0fcf7
JuanPyV/Python
/while/W5_A00368753.py
152
3.65625
4
n = int(input("¿Hasta que numero? ")) c = 0 g = 0 while c < n: g = g + 3.785 c = c + 1 print("%d gal. equivale a %.3f lts" % (c, g))
624841aa07b17ecc6b152d17d8ccc8aa7cb3a80f
Nubstein/Python-exercises
/Condicionais e Loop/Ex10.py
644
3.71875
4
#Meses com 31 dias: 1, 3, 5, 7, 8, 10 ou mês 12 #Meses com 30 dias: 4, 6, 9 e o mês 11. #algo errado no código abaixo d=int(input("Insira o dia: ")) m=int(input("Insira o mês: ")) a=int(input("Insira o ano: ")) if m==1 or m==3 or m==5 or m==7 or m==8 or m==10 or m==12: #meses com 31 dias if d<=31: valida=True if m==4 or m==6 or m==9 or m==11: #Meses com 30 dias if d<=30: valida=True if m==2: if (a%4==0 and a%100!=0) or (a%400==0): #Ano bissexto if(dia<=29): valida = True elif(dia<=28): valida = True if (valida): print("Data Valida") else: print("Data Inválida")
c85a59e2a9af8f1e9b515e9b2b08819c3cd7621f
petr-tik/misc
/zenhacks_jarjar.py
536
3.515625
4
#!/usr/bin/env python # https://www.hackerrank.com/contests/zenhacks/challenges/pairing N = int(raw_input()) def solve(Num): res = {} answer = 0 for x in xrange(Num): shoe = raw_input() res_k = shoe[:-2] foot = shoe[-1:] if not res.has_key(res_k): res[res_k] = [foot] else: res[res_k].append(foot) for k in res: lefts = res[k].count('L') rights = res[k].count('R') answer += min(lefts, rights) return answer print solve(N)
e2db677056ec0083d2e131bb7b12b9a7d085557e
calvinloveland/letterwords
/python/sort_by_size.py
359
3.53125
4
dictionary = list() def get_dictionary(): file = open("dictionary.csv") for line in file: dictionary.append(line.strip()) def set_dictionary(): file = open("newdictionary.csv",'w') for word in dictionary: file.write(word + '\n') get_dictionary() dictionary.sort() dictionary.sort(key=len) set_dictionary() print('DONE')
e3861e1c9c533ce8532028a64bef869860a5a2f0
everqiujuan/python
/day08/code/09_不定长参数.py
1,104
3.75
4
# 不定长参数 # *args: 可以接收任意数量的参数, 会接收到一个元组tuple # args: arguments参数的意思 def fn(*args): print(args) # (1, 2, 3) fn(1, 2, 3, True, "a") list1 = [1, 2, 3] fn(*list1) def fun(name, age, *args, sex='男'): print(name) # 昆凌 print(age) # 25 print(sex) # 女 print(args) # ('中国台湾', '165', '90') fun("昆凌", 25, '中国台湾', '165', '90', sex='女') # **kwargs: 不定长关键字参数, 接收任意数量的关键字参数,会接收到一个字典dict # kwargs: keyword arguments 关键字参数 def fn2(**kwargs): print(kwargs) # {'name': '罗志祥', 'age': 37} fn2(name='罗志祥', age=37) dic = {"qq": "123456", 'wechat': 'xiaozhu'} fn2(**dic) # {'qq': '123456', 'wechat': 'xiaozhu'} # def fun2(name, *args, sex='男', **kwargs): print(name) # 黄渤 print(args) # ('黄磊', '黄晓明') print(kwargs) # {'name1': '徐峥', 'name2': '宝强'} fun2('黄渤', '黄磊', '黄晓明', name1='徐峥', name2='宝强') # 印囧
4fff956bcb3566b527331f03a9b082d058f94dbc
medshi3/Exercices-from-practicepython.org
/exer15.py
512
4.40625
4
"""" Write a program (using functions!) that asks the user for a long string containing multiple words. Print back to the user the same string, except with the words in backwards order. For example, say I type the string: """ def str_reverser(input = None): if input != None: data = ' '.join(input.split()[::-1]) else: data = raw_input('Please Enter any string you like\n=> ') data = ' '.join(data.split()[::-1]) print (data) if __name__ == '__main__': str_reverser()
2bf025ff5245da47e18d897ab17c06f39d068bd8
sunnyding602/CISC-610-O-LateSpring
/Assignment3/trees.py
1,790
3.796875
4
import csv from bintree_tree import Tree from collections import deque class Trees: leaf_count = 0 height = 0 def inorder(self, root_node): current = root_node if current is None: return if current.is_leaf: self.leaf_count = self.leaf_count + 1 self.inorder(current.left_child) self.inorder(current.right_child) def breadth_first_traversal(self, root_node): list_of_nodes = [] traversal_queue = deque([root_node]) while len(traversal_queue) > 0: self.height = self.height + 1 for i in range(len(traversal_queue)): node = traversal_queue.popleft() if node.left_child: traversal_queue.append(node.left_child) if node.right_child: traversal_queue.append(node.right_child) def main(): numbers = [] with open('random_numbers.csv', 'r', encoding='utf-8-sig', newline='') as csvfile: randomNumberReader = csv.reader(csvfile, delimiter=',', quotechar='"') for row in randomNumberReader: for number in row: try: numbers.append(int(number)) except ValueError as e: print(str(e)) print(f"Could not convert data to an integer. This {number} will be discarded!") tree = Tree() for num in numbers: tree.insert(num) trees = Trees() trees.inorder(tree.root_node) print("Leaf count:{}".format(trees.leaf_count)) trees.breadth_first_traversal(tree.root_node) print("The height of the tree is {}".format(trees.height)) if __name__ == "__main__": main()
5b4073d2eb2ab52d27b0c7a394dae427ce0aa869
g-buzzi/Padaria_GUI
/entidades/estocado.py
802
3.8125
4
from abc import ABC, abstractmethod class Estocado(ABC): @abstractmethod def __init__(self, codigo: int, nome: str) -> None: super().__init__() self.__codigo = codigo self.__nome = nome self.__quantidade_estoque = 0 @property def codigo(self) -> int: return self.__codigo @codigo.setter def codigo(self, codigo: int): self.__codigo = codigo @property def nome(self): return self.__nome @nome.setter def nome(self, nome: str): self.__nome = nome @property def quantidade_estoque(self) -> int: return self.__quantidade_estoque @quantidade_estoque.setter def quantidade_estoque(self, quantidade_estoque: int): self.__quantidade_estoque = quantidade_estoque
4da3fc15f4ff099bfbbd3b6fe84025731b426adc
ps9610/python-web-scrapper
/02-01/return_1.py
534
3.875
4
#print와 return의 차이에 대해서 알아보자 def p_plus(a, b): print(a + b) def r_plus(a, b): return a + b p_result = p_plus(2, 3) r_result = r_plus(2, 3) print(p_result, r_result) #>>>5, None 5 #ㄴ>첫번째 5는 line 3의 print(a+b) #ㄴ>두번째는 p_result = none, r_result = 5가 나왔다. #none이 나온 이유는 p_plus는 되돌아오는 값이 없기 때문에 none #print(a+b)는 어떤 결과값이 아니고 단순히 print()라는 함수를 실행했을 뿐이다.
544657a0c71184277472a0d8d54a4bee8fa3c827
bk17Git/python
/calculator.py
405
4.28125
4
firstNo = int(input("Enter you first operand: ")) operator = input("Enter your operator: ") secondNo = int(input("Enter your second operand: ")) if operator == "+": print(firstNo + secondNo ) elif operator == "-": print(firstNo - secondNo) elif operator == "*": print(firstNo * secondNo) elif operator == "/": print(firstNo / secondNo) else: print("Your operator is a wrong one!")
af4b61aee362544b2394e54e2ed19867ae5fdd44
EddyYeung1/Top-75-LC-Questions
/Solutions/Group_Anagram.py
2,030
4.15625
4
''' Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] ''' ''' Solution 1: we create a dictionary with a sorted word as a key and a list of anagrams as its value. The key here is by having the sorted word as a key we can easily find other anagrams in the list with constant time. Afterwards all we need to do is append the groups to the answer list. The only issue about this is that it takes O(M * KLogK) because for every word we check out on the list we are also sorting it and thats takes O(K log K) time, yikes. ''' def groupAnagrams(strs): dic = {} ans = [] for word in strs: temp = "".join(sorted(word)) if temp not in dic: dic[temp] = [] if temp in dic: dic[temp].append(word) for key in dic: ans.append(dic[key]) return ans ''' Solution 2: This is essentially the same concept as the above, however instead we are defining an array with 26 letters as its size. We count the frequency of every letter and convert that frequency list into a tuple which becomes a key for the dictionary. We have to convert it to a list because keys have to be immutable and tuples are immutable. ''' def groupAnagrams(self, strs): ans = collections.defaultdict(list) for word in strs: frequencyList = [0] * 26 # this creates an array in python for char in word: # ord() returns the ascii val of a char we subtract by ord('a') so we can access the correct indicie in our frequencyList # i.e ord('b') - ord('a') = 1, frequencyList[1] = second letter in alphabet frequencyList[ord(char) - ord('a')] += 1 # convert to tuple because key for a dict must be immutable # the reason the key has to be immutable is because for hashing to work changing the key would fuck up the mapping ans[tuple(frequencyList)].append(word) return(ans.values())
d043abe1af412fe40e964ae2ea8c530c99a0ffad
Yasmin-Core/Python
/Mundo_1(Python)/operacoes_aritmeticas/aula7_desafio13(porcentagem2).py
171
3.53125
4
salário= float(input('Qual é o seu salário ? R$')) novo= salário + (salário * 15/100) print ('O seu salario teve um aumento de 15% e passou a ser R$ {}'.format(novo))
678b06349751b40b9839816eb25b1e06fe5c2140
trumiddd/LearningX
/advanced_ML/tree_ensembles/src/GradientBoostedTree.py
1,926
3.609375
4
""" GradientBoostedTree.py (author: Anson Wong / git: ankonzoid) """ import numpy as np from sklearn.tree import DecisionTreeRegressor class GradientBoostedTreeRegressor: def __init__(self, n_estimators=20, max_depth=5, min_samples_split=2, min_samples_leaf=1): self.n_estimators = n_estimators self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf def fit(self, X, y): """ Method: 1) Train tree with greedy splitting on dataset (X, y) 2) Recursively (n_estimator times) compute the residual between the truth and prediction values (res = y-y_pred), and use the residual as the next estimator's training y (keep X the same) 3) The prediction at each estimator is the trained prediction plus the previous trained prediction, making the full prediction of the final model the sum of the predictions of each model. """ self.models = [] y_i = y y_pred_i = np.zeros(y.shape) for i in range(self.n_estimators): # Create tree with greedy splits model = DecisionTreeRegressor(max_depth=self.max_depth, min_samples_split=self.min_samples_split, min_samples_leaf=self.min_samples_leaf) model.fit(X, y_i) # Boosting procedure y_pred = model.predict(X) + y_pred_i # add previous prediction res = y - y_pred # compute residual y_i = res # set training label as residual y_pred_i = y_pred # update prediction value self.models.append(model) def predict(self, X): y_pred = np.zeros(len(X)) for model in self.models: y_pred += model.predict(X) return y_pred
9d350c258a984ddb48a857df39e446196432c8c1
JuanGinesRamisV/python
/practica 5/p5e7.py
254
4
4
#juan gines ramis vivancos p5e7 #Escribe un programa que pida la altura de un triángulo y lo dibuje de la siguiente manera print('introduce la altura de tu trianuglo') altura = int(input()) anchura = altura for i in range(altura+1): print('*'*(altura-(i*1)))
b4104021daa233e13de184c1775404a3ea97151b
chanson20/battleship
/main.py
1,961
3.609375
4
import batlib import time #Heart of the Game def main(): global turn,message,debug,map,shipcol,shiprow while turn > 0: #Loop until turns are gone batlib.clear(100) print "BATTLE SHIP" batlib.clear(2) if debug == True: print 'Coordinates are %s row and %s colum' % (shiprow,shipcol) print message#explains what happened for row in map: #This prints out the map on each line instead of all together print " ".join(row) batlib.clear(3)#3 lines of whitespace guessrow = input("Row ") guesscol = input("Colum ") #If they guess correctly if guessrow == shiprow and guesscol == shipcol: batlib.updatestats(True,batlib.gettotal(),batlib.getwin()) print "Well done soldier! Direct hit." batlib.printstats() if batlib.again() == True: start() else: print 'At ease, soldier.' break #If they guess out of range elif guessrow not in range(1,6) or guesscol not in range(1,6): message = "Those coordinates could harm civilians!" batlib.clear(1) turn -= 3 #If they already hit a certain spot elif map[guesscol][guessrow] == "x": message = "Sir, we already tried that spot." batlib.clear(1) turn -= 2 #If they miss else: message = "Sir, the missile failed to hit anything." batlib.clear(1) map[guesscol][guessrow] = "x" turn -= 1 #If they run out of turns else: batlib.updatestats(False,batlib.gettotal(),batlib.getwin()) print('') print('') print('') print "Game Over" print "The enemy has sunk you" batlib.printstats() if batlib.again() == True: start() else: print 'rage quit omg' ### #Defining Variables and such def start(): global turn,map,debug,shipcol,shiprow,message message = "" shiprow = batlib.random() shipcol = batlib.random() debug = False map = batlib.createmap() turn = 5 # global turn,map,debug,shipcol,shiprow,message main() start()
e56869731f3da0b497e669d5a8852aca9cac7a5f
lincrampton/pythonHackerRankLeetCode
/complexNumberMultiply.py
675
4.03125
4
'''A complex number can be represented as a string on the form "real+imaginaryi" where: real is the real part and is an integer in the range [-100, 100]. imaginary is the imaginary part and is an integer in the range [-100, 100]. i2 == -1. Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.''' class Solution: def complexNumberMultiply(self, num1: str, num2: str) -> str: real1, img1 = map(int, num1[:-1].split('+')) real2, img2 = map(int, num2[:-1].split('+')) return '%d+%di' % ( (real1 * real2) - (img1 * img2), (real1 * img2) + (img1 * real2) )
f408be4608e59ad50983997bd3a1ea06dc35b351
Pshowo/fastAPI-encryptor
/vigenere/encryptor.py
4,071
3.65625
4
import numpy as np import string import random class Vigenere: def __init__(self, alphabet, **kwargs): self.raw_alphabet = alphabet self.alphabet = self.gen_alphabet(self.raw_alphabet) self.key_length = kwargs['key_length'] if "key_length" in kwargs else 8 self._ke = None self.table = self.gen_table() def __str__(self): print("Raw alphabet:", self.raw_alphabet) print("Key length:", self.key_length) return str(self.table) def gen_alphabet(self, alphabet): """Based on the input alphabet, the method generated an array. If char appears twice or more in the alphabet, the rest of them removed. Parameters ---------- alphabet : [str] A string containing all chars to use. Returns ------- [np.array] 1d array with chars """ # for char_ in alphabet: if alphabet.count(char_) > 1: alphabet = alphabet.replace(char_, "") " " + alphabet return np.array([char_ for char_ in alphabet]) def gen_table(self): """Generate cipher table. In the each row alphabet is shuffle randomly. Returns ------- [numpy arr] Cipher table. """ key_alphabet = " " + string.ascii_letters + string.digits + string.punctuation self._ke = [char for char in key_alphabet] # List of chars to generate a random key ke_ = np.array([[char] for char in key_alphabet]) table = np.array([np.copy(self.alphabet)]) for i in range(0, len(ke_) - 1): t1 = np.copy(self.alphabet) np.random.shuffle(t1) table = np.append(table, [t1], axis=0) table = np.append(ke_, table, axis=1) return table def encrypt(self, msg): """Encrypts message using by Vigenere method. The message before encoded was reverse. Parameters ---------- msg : [str] Message to encrypting. Returns ------- [tuple(msg, key)] Tuple with encrypted message and the key, which a message will be decrypted. """ if msg == "": return "Message is empty. Write the message to encode.", -1 else: closed_msg = "" key_range = self.key_length if len(msg) >= self.key_length else len(msg) key = "".join(random.choice(self._ke[1:]) for _ in range(key_range)) k = 0 msg = msg[::-1] for char in range(len(msg)): if msg[char] not in self.raw_alphabet: return f'This: "{msg[char]}" character is not available. Replace it for similar.', -1 if k == len(key): k = 0 x0 = np.argwhere(self.table[0][1:] == msg[char])[0][0] + 1 x1 = np.argwhere(self.table[1:, [0]] == key[k])[0][0] + 1 closed_msg += self.table[x1][x0] k += 1 return closed_msg, key def decrypt(self, c_msg, key): """Decodes and reverse cipher message. Parameters ---------- c_msg : [str] Closed message. key : [str] Key to open the message. Returns ------- [str] Decrypted message. """ if c_msg == "": return "No message. Write encoded message." if key == "" or key == -1: return "No key. Write the key attached with the encoded message." else: open_msg = "" k = 0 for char in range(len(c_msg)): if k == len(key): k = 0 x1 = np.argwhere(self.table[1:, [0]] == key[k])[0][0] + 1 # Finds char in key column x0 = np.argwhere(self.table[x1][1:] == c_msg[char])[0][0] # Finds char in particular row open_msg += self.table[0][1:][x0] k += 1 return open_msg[::-1]
6f4cfb4dfbe20907586e4e3091b59f479554906d
zhchua/vigenere-c2pytest
/vigeneremain2.py
629
4.0625
4
# input is basically printf and scanf combined text = input('Enter text (preferably without spaces):\n') key = input('Enter key\n') # force uppercase for simplicity text = text.upper() from vigenereenc import rptkey key = rptkey(text, key.upper()) def cmd(): # This doesnt work without the int act = int(input('1 for ENC \n2 for DEC\n')) if act is 1: # conditional selective importing from vigenereenc import encry print(encry(text, key)) elif act is 2: from vigenereenc import decry print(decry(text, key)) else: print('Invalid input') return cmd()
e838ba47e848752abef9ebbed0d7dc30f826e93f
collective/p4a.common
/p4a/common/formatting.py
5,105
4.03125
4
from datetime import datetime from datetime import timedelta ONE_DAY = timedelta(days=1) def day_suffix(day): """ Return correct English suffix (i.e. 'st', 'nd' etc.) >>> day_suffix(1) u'st' >>> day_suffix(6) u'th' >>> day_suffix(21) u'st' >>> day_suffix(26) u'th' """ if 4 <= day <= 20 or 24 <= day <= 30: return u'th' else: return [u'st', u'nd', u'rd'][day % 10 - 1] def same_day(*dates): """Return True if and only if each date in *dates represents the exact same date. >>> from datetime import date >>> same_day(date(2006, 1, 29)) True >>> same_day(date(2006, 1, 29), date(2006, 1, 29)) True >>> same_day(date(2006, 1, 29), date(2006, 1, 29), date(2006, 3, 22)) False """ onedate = dates[0] for x in dates[1:]: if x.year != onedate.year or x.month != onedate.month \ or x.day != onedate.day: return False return True def same_month(*dates): """Return True if and only if each date in *dates represents the exact same month and year. >>> from datetime import date >>> same_month(date(2006, 1, 29)) True >>> same_month(date(2006, 1, 29), date(2006, 1, 29)) True >>> same_month(date(2006, 1, 29), date(2006, 1, 29), date(2006, 1, 22)) True >>> same_month(date(2006, 1, 29), date(2006, 5, 29)) False """ onedate = dates[0] for x in dates[1:]: if x.year != onedate.year or x.month != onedate.month: return False return True def fancy_date_interval(start, end=None): """ If dates share month and year, format it so the month is only displayed once. >>> from datetime import datetime, timedelta >>> fancy_date_interval(datetime(2006, 1, 29), datetime(2006, 1, 30)) u'Jan 29th-30th, 2006' >>> fancy_date_interval(datetime(2006, 1, 29), datetime(2006, 2, 1)) u'Jan 29th-Feb 1st, 2006' >>> fancy_date_interval(datetime(2006, 1, 29), datetime(2006, 1, 29)) u'Jan 29th, 2006' >>> fancy_date_interval(datetime.today()) u'Today' >>> fancy_date_interval(datetime.today()-timedelta(days=1)) u'Yesterday' """ if end is None or same_day(start, end): if same_day(start, datetime.today()): return u'Today' if same_day(start, datetime.today() - ONE_DAY): return u'Yesterday' return u'%s %s%s, %s' % (unicode(start.strftime("%b"), "utf-8"), start.day, day_suffix(start.day), start.year) elif same_month(start, end): return u'%s %s%s-%s%s, %s' % (unicode(start.strftime("%b"), "utf-8"), start.day, day_suffix(start.day), end.day, day_suffix(end.day), start.year) else: return u'%s %s%s-%s %s%s, %s' % (unicode(start.strftime("%b"), "utf-8"), start.day, day_suffix(start.day), end.strftime("%b"), end.day, day_suffix(end.day), start.year) def fancy_time_amount(v, show_legend=True): """Produce a friendly representation of the given time amount. The value is expected to be in seconds as an int. >>> fancy_time_amount(391) u'06:31 (mm:ss)' >>> fancy_time_amount(360) u'06:00 (mm:ss)' >>> fancy_time_amount(6360) u'01:46:00 (hh:mm:ss)' >>> fancy_time_amount(360, False) u'06:00' """ remainder = v hours = remainder / 60 / 60 remainder = remainder - (hours * 60 * 60) mins = remainder / 60 secs = remainder - (mins * 60) if hours > 0: val = u'%02i:%02i:%02i' % (hours, mins, secs) legend = u' (hh:mm:ss)' else: val = u'%02i:%02i' % (mins, secs) legend = u' (mm:ss)' if show_legend: full = val + legend else: full = val return full def fancy_data_size(v): """Produce a friendly reprsentation of the given value. The value Is expected to be in bytes as an int or long. >>> fancy_data_size(54) u'54 B' >>> fancy_data_size(37932) u'37.0 KB' >>> fancy_data_size(1237932) u'1.2 MB' >>> fancy_data_size(2911237932) u'2.7 GB' """ suffix = 'B' format = u'%i %s' if v > 1024: suffix = 'KB' v = float(v) / 1024.0 format = u'%.1f %s' if v > 1024: suffix = 'MB' v = v / 1024.0 if v > 1024: suffix = 'GB' v = v / 1024.0 return format % (v, suffix) def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test()
557b6cdf4d1666d85b7758f7ac93d117dc0226f1
Jiawei-Wang/LeetCode-Study
/283. Move Zeroes.py
2,705
3.5
4
# 解法1:使用新的array class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ # 创建一个新array newArray = [-1] * len(nums) # 遍历nums,如果元素非0,放进新array,同时统计0的总数 totalZero = 0; for i in range(len(nums)): if nums[i] == 0: totalZero += 1 else: newArray[i-totalZero] = nums[i] # 把新array的尾部填充满0 for j in range(len(nums)-totalZero, len(nums)): newArray[j] = 0 # 把新array的值给nums for i in range(len(nums)): nums[i] = newArray[i] # 解法2:非0元素往前放,尾部用0填充 class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ last_zero = 0 for i in range(len(nums)): if nums[i] != 0: nums[last_zero] = nums[i] last_zero += 1 for i in range(last_zero, len(nums)): nums[i] = 0 # 解法3: class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ zero = 0 # records the position of "0" for i in range(len(nums)): if nums[i] != 0: nums[i], nums[zero] = nums[zero], nums[i] zero += 1 """ 分析: 两个指针,一个遍历元素,另一个先按顺序遍历直到找到第一个0 在这个0后面的元素会出现两种情况:不为0和为0 如果后面的元素不为0,则将二者的值交换,并把指针加1 (实现的是把后面第一个不为0的元素放在第一个0前面) 如果后面的元素为0,则什么都不做(即两个0并排放在一起),继续寻找下一个元素 用一个具体例子来形容:在找到第一个0之前所有元素不动,在找到0之后,遇到非0元素就抽出来放在0前面,遇到0就叠加在一起继续往后推 """ # 将一个list中的所有0全部放置于末尾,其他元素的相对位置不变 # 要求:in place class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ cnt = 0 # how many zeros together for i in range(len(nums)): if not nums[i]: cnt += 1 elif cnt > 0: # 如果nums[i]不为0且此时有至少一个0 nums[i], nums[i-cnt] = 0, nums[i] # 将此元素和第一个0对调
ae16defe708591a78d085ad10f461c5c17f083a1
m4mayank/ComplexAlgos
/kthsmallest.py
1,357
3.9375
4
#!/home/cloud_user/.local/share/virtualenvs/algo-9u7x6JDZ/bin/python3 class Node: def __init__(self, data): self.left = None self.right = None self.data = data def insert(self, data): if data < self.data: if self.left is None: self.left = Node(data) else: self.left.insert(data) elif data > self.data: if self.right is None: self.right = Node(data) else: self.right.insert(data) def PrintTree(node): if node.left: PrintTree(node.left) print(node.data) if node.right: PrintTree(node.right) def kthsmallest(root, k): stack = [root] counter = 0 while stack: node = stack.pop() if not node.left and not node.right: counter += 1 if counter == k: return node.data else: if node.right: stack.append(node.right) node.right = None stack.append(node) if node.left: stack.append(node.left) node.left = None root = Node(12) llist = [5,1,87,40,10] for i in llist: root.insert(i) PrintTree(root) print(f"Kth smallest element is :{kthsmallest(root, 2)}")
4ce4c3d208e665c7b857bf01a51a60ff91f335ff
canicode/project_cs303e.py
/Try Except Q&A Files.py
574
3.8125
4
def main(): while True: try: guess = int(input("Please enter your quess: ")) except ValueError: print("Sorry, please put it into Arabic Numbers") continue else: print("You are correct") break while True: try: alphaguess= str(input("Please enter your guess: ")) except NameError: print("Sorry, please spell it out") continue else: print("You are correct") break main()
6c77837dbcde3a72b1eacb67e73d928b09586491
OmarAbdelrazek/8-Puzzle
/8puzzle.py
8,277
3.734375
4
import time import sys from math import sqrt from collections import deque import heapq goal = [0,1,2,3,4,5,6,7,8] nodes_expanded = 0 moves =[] explored = {} frontier = [] board_length = 0 board_side = 0 frontier_U_explored = set() class Board: def __init__(self,state: list,parent = None,move = "initial",cost= 0): self.state = state self.parent = parent self.cost = cost self.move = move self.key = 0 def print_board(self): print(""+str(self.state[0:3])+"\n"+str(self.state[3:6])+"\n"+str(self.state[6:9])+"\n\n" ) pass def move_up(self): new_state = list(self.state) index = new_state.index(0) new_state[index] = self.state[index - 3] new_state[index-3] = self.state[index] return Board(new_state, self, "up",self.cost + 1) def move_down(self): new_state = list(self.state) index = new_state.index(0) new_state[index] = self.state[index + 3] new_state[index+3] = self.state[index] return Board(new_state, self, "down", self.cost +1 ) def move_left(self): new_state = list(self.state) index = new_state.index(0) new_state[index] = self.state[index - 1] new_state[index-1] = self.state[index] # self.state = new_state return Board(new_state, self, "left",self.cost + 1) def move_right(self): new_state = list(self.state) index = new_state.index(0) new_state[index] = self.state[index + 1] new_state[index+1] = self.state[index] # self.state = new_state return Board(new_state, self, "right",self.cost + 1) def can_move_up(self): index = self.state.index(0) if(index in range(0,3)): return False return True def can_move_down(self): index = self.state.index(0) if(index in range(6,9)): return False return True def can_move_left(self): index = self.state.index(0) if(index in range(0,7,3)): return False return True def can_move_right(self): index = self.state.index(0) if(index in range(2,9,3)): return False return True def get_parent(self): return self.parent def __eq__(self, other): return self.state == other.state def __lt__(self, other): return self.key < other.key def get_neighbors(board :Board): global nodes_expanded neighbors = [] nodes = [] if board.can_move_up() == True : neighbors.append(board.move_up()) nodes_expanded += 1 if board.can_move_down()== True : neighbors.append(board.move_down()) nodes_expanded += 1 if board.can_move_left()== True : neighbors.append(board.move_left()) nodes_expanded += 1 if board.can_move_right()== True : neighbors.append(board.move_right()) nodes_expanded += 1 return neighbors def get_path(my_goal): while my_goal.move != "initial": moves.append(my_goal.move) my_goal = my_goal.parent return def BFS(initial_board, goal_board_state): frontier_U_explored = set() frontier_U_explored.add(str(initial_board.state)) frontier.append(initial_board) while frontier: b = frontier.pop(0) if b.state == goal_board_state: return b neighbours = get_neighbors(b) for neighbour in neighbours: if str(neighbour.state) not in frontier_U_explored: frontier_U_explored.add(str(neighbour.state)) frontier.append(neighbour) return "fail" def DFS(initial_board, goal_board_state): frontier_U_explored = set() frontier_U_explored.add(str(initial_board.state)) frontier.append(initial_board) while frontier: b = frontier.pop() if b.state == goal_board_state: return b neighbours = get_neighbors(b) for neighbour in neighbours: if str(neighbour.state) not in frontier_U_explored: frontier_U_explored.add(str(neighbour.state)) frontier.append(neighbour) return "fail" def manhattan_distance(state): global board_length,board_side return sum(abs(b % board_side - g % board_side) + abs(b//board_side - g//board_side) for b, g in ((state.index(i), goal.index(i)) for i in range(1, board_length))) def euclidean_distance(state): global board_length return sum(sqrt(pow(b % board_side - g % board_side,2)) + sqrt(pow(b//board_side - g//board_side,2)) for b, g in ((state.index(i), goal.index(i)) for i in range(1, board_length))) def aStar_euclidean(initial_board, goal_board_state): heap_entry = {} key = euclidean_distance(initial_board.state) entry = (key,initial_board.state,initial_board) heapq.heappush(frontier,entry) frontier_U_explored = set() heap_entry[str(initial_board.state)] = entry while frontier: b = heapq.heappop(frontier) frontier_U_explored.add(str(b[2].state)) if b[2].state == goal_board_state: return b[2] neighbours = get_neighbors(b[2]) for neighbor in neighbours: neighbor.key = neighbor.cost + euclidean_distance(neighbor.state) entry = (neighbor.key, neighbor.move, neighbor) if str(neighbor.state) not in frontier_U_explored: frontier_U_explored.add(str(neighbor.state)) heapq.heappush(frontier,entry) heap_entry[str(neighbor.state)] = entry elif str(neighbor.state) in heap_entry and neighbor.key < heap_entry[str(neighbor.state)][2].key: hindex = frontier.index((heap_entry[str(neighbor.state)][2].key,heap_entry[str(neighbor.state)][2].move,heap_entry[str(neighbor.state)][2])) frontier[int(hindex)] = entry heap_entry[str(neighbor.state)] = entry heapq.heapify(frontier) return "fail" def aStar_manhattan(initial_board, goal_board_state): heap_entry = {} key = manhattan_distance(initial_board.state) entry = (key,initial_board.state,initial_board) heapq.heappush(frontier,entry) heap_entry[str(initial_board.state)] = entry while frontier: b = heapq.heappop(frontier) frontier_U_explored.add(str(b[2].state)) if b[2].state == goal_board_state: return b[2] neighbours = get_neighbors(b[2]) for neighbor in neighbours: neighbor.key = neighbor.cost + manhattan_distance(neighbor.state) entry = (neighbor.key, neighbor.move, neighbor) if str(neighbor.state) not in frontier_U_explored: frontier_U_explored.add(str(neighbor.state)) heapq.heappush(frontier,entry) heap_entry[str(neighbor.state)] = entry elif str(neighbor.state) in heap_entry and neighbor.key < heap_entry[str(neighbor.state)][2].key: hindex = frontier.index((heap_entry[str(neighbor.state)][2].key,heap_entry[str(neighbor.state)][2].move,heap_entry[str(neighbor.state)][2])) frontier[int(hindex)] = entry heap_entry[str(neighbor.state)] = entry heapq.heapify(frontier) return "fail" def print_output(final_state,running_time): global nodes_expanded print("Path to goal: ",moves) print("Cost of path: ",final_state.cost) print("Search depth: ",final_state.cost) print("Nodes expanded: ",(nodes_expanded)) print("Running time: ",running_time) def main(): global goal,moves,board_length,board_side start_time = time.time() b = Board([8,6,4,2,1,3,5,7,0],"root") board_length = len(b.state) board_side = int(board_length ** 0.5) #A-star using euclidean formula final_state = aStar_euclidean(b,goal) #A-star using manhattan formula final_state = aStar_euclidean(b,goal) #DFS final_state = DFS(b,goal) #BFS final_state = BFS(b,goal) get_path(final_state) moves.reverse() running_time = time.time() - start_time print_output(final_state,running_time) if __name__ == "__main__": main()
0d58c220d7065a6ac461f38e400b43f0e4925a84
msaintja/computer-vision-archive
/PS0/code/PS0-3-code/PS0-3-code.py
954
3.515625
4
# Importing the opencv library for Python import cv2 # Importing numpy for matrices/images handling import numpy as np # Importing matplotlib.pyplot to embed images within this notebook import matplotlib.pyplot as plt # 1. Input images # Loading the 2 images downloaded # from http://sipi.usc.edu/database/database.php?volume=misc img1 = cv2.imread('./images/4.2.06.tiff', cv2.IMREAD_COLOR) img2 = cv2.imread('./images/4.2.07.tiff', cv2.IMREAD_COLOR) ). # 3. Replacement of pixels #Replacing inner 100 pixels square from one image by another img1Mg = img1[:,:,1].copy() #BGR, green is the 2nd channel img2Mg = img2[:,:,1].copy() margin = (np.shape(img1Mg)[0] - 100) / 2 #both images are the same size img1MgInner = img1Mg[margin:-margin, margin:-margin].copy() img2MgRep = img2Mg.copy() img2MgRep[margin:-margin, margin:-margin] = img1MgInner cv2.imwrite('./out/ps0-3-a.tiff', img2MgRep) plt.imshow(img2MgRep, cmap='gray', vmin = 0, vmax = 255)
7280349bc990e074eb87acf4118935d7a7941156
NarendraPutta/Python_Documentation_till_OOPs
/Tuples.py
1,094
4.5
4
Tuples: Tuples are similar to the list that is these are the group of different type of elements. The different between list & tuple is list is mutable that is we can alter the list whenever we want but once we create the tuple. We can alter it. So, tuple is immutable. tuple =() #tuples are identified by paranthesis #empty tuple num = () #Here num is an empty tuple. #tuple assignment >>> companies = ('Google', 'Facebook', 'Twitter', 'Microsoft') >>> companies ('Google', 'Facebook', 'Twitter', 'Microsoft') >>> companies[0] 'Google' #Nested tuples >>> tuple1 ((10, 2.3), (25, 2.3)) >>> tuple1[0] (10, 2.3) >>> tuple1[0][0] 10 Note: Since tuples are immutable, We cant insert any element, delete any element, replace any element in the tuple. If we take these operations in the tuple wud give error. >>> companies.sort() Traceback (most recent call last): File "<pyshell#48>", line 1, in <module> companies.sort() AttributeError: 'tuple' object has no attribute 'sort' So, there are no operators in the tuples. This is it for Python programming in tuples. meet you in next class.
ed4377f23f9114e24ba34a94f0c103a5a5863d31
nsoft21/programming
/Practice/13/Python/13.py
510
3.75
4
k = 0 while (k == 0): try: a = int(input('Введите число: ')) if a < 2 or a > 10**9: print('Вводимое число должно быть в пределах от 2 до 10^9 включительно!') else: k = 1 except: print("Неверный формат ввода. Попробуйте еще раз:") num = 2 while a % num != 0: num += 1 if num == a: print('Простое') else: print('Составное')
61d5931963772a6962229178e64847151813fb9d
epamekids/Danik_chatbot
/inter_2.py
673
3.625
4
i = 0 s = 0 d = 0 gr = [] par = [] while i < 20: print("Say something !") z = input() v = input("If you greet me, type 'gr', otherwise 'par' ") if v == 'gr': if s == 0: gr.append(z) print("Hello you too!") elif s > 0: if z in gr: print("Hello you too!", "you have already wrote this") else: gr.append(z) print("Hello you too!") s+=1 elif v == 'par': if d == 0: par.append(z) print("Goodbye my friend") elif d > 0 : if z in par: print("Goodbye my friend", "you have already wrote this") else: par.append(z) print("Goodbye my friend") d+=1 else: print("I'm buzy right now, let's talk another time") i+=1
e7f36451def6e1721e757594de8e330e47a47741
pinturam/PyCodeChallenges
/Factorial.py
330
4.28125
4
# program to find factorial of a number num = int(input('enter a number: ')) factorial = 1 if num < 0: print('sorry, factorial does not exist for negative number') elif num == 0: print('factorial = 1') else: for i in range(1, num+1): factorial = factorial*i print('the factorial = ', factorial)
a6b4c5ce8007f107a0824a3fafd6f33464e7888c
JorgeDPSilva/LCC
/2ºAno/2ºSemestre/LA2/retangulos.py
1,270
3.703125
4
import sys ''' def make_rectangules(first_coordenates, second_coordenates): for y in range(second_coordenates[1]-first_coordenates[1]+1): for x in range(second_coordenates[0]-first_coordenates[0]+1): print('#') def main(): aux_list = [] for line in sys.stdin: line = line.strip('\n').split() line = list(map(int,line)) first_coordenates = (line[0],line[1]) second_coordenates = (line[2],line[3]) make_rectangules(first_coordenates, second_coordenates) main() ''' import sys def main(): aux_list = [] for line in sys.stdin: line = line.strip('\n').split() line = list(map(int,line)) aux_list.append(list(line)) #print(aux_list) max_x = 0 max_y = 0 for elem in aux_list: if elem[2] > max_x: max_x = elem[2] if elem[3] > max_y: max_y = elem[3] array = [[" " for x in range(max_y+1)] for y in range(max_x+1)] for elem in aux_list: for i in range(elem[0], elem[2]+1): for j in range(elem[1], elem[3]+1): array[i][j] = '#' for x in range(max_y+1): for y in range(max_x+1): print(array[y][x], end='') print("") main()
12e9c0ce7579da6bf49bcb9a9f7e9aa0ca54fba5
RomainFloreani/Comp598-Project
/filtering_the_post.py
3,446
3.8125
4
import json import pandas as pd import re import random import argparse def get_post_titles(inp): """ (file) --> (list) this function takes as input a file with Reddit post collected with the reddit API returns a list of all the titles of each of the posts. """ list_of_titles = [] file_in = open(inp,'r') for line in file_in: data = json.loads(line) list_of_titles.append(data['data']['title']) return list_of_titles def get_titles_by_candidate(list_of_titles, candidate): """ (list, string (biden or trump in lower case)) --> list This takes as input a list of post titles and returns a list of post titles containing the name of the candidate. """ if candidate != 'trump' and candidate != 'biden': raise ValueError ('candidate must be equal to "trump" or "biden" ') titles_containing_the_candidate = [] for title in list_of_titles: lower_title = title.lower() if re.search(f"[^0-9a-zA-Z]{candidate}[^0-9a-zA-Z]", lower_title) or re.search(f"{candidate}[^0-9a-zA-Z]", lower_title): titles_containing_the_candidate.append(title) return titles_containing_the_candidate def choose_random_line(list_of_post, num_post): """ (list, int) --> list This function takes as input a list of titles posts and a number. It returns a list of list of length of that number containing radomly selected posts from list_of_posts. """ random_post = [] while(len(random_post) < num_post): mytitle = list_of_post.pop(random.randint(0,len(list_of_post)-1)) random_post.append(mytitle) return random_post def main(): parser = argparse.ArgumentParser() parser.add_argument('input_file_d1', help = 'this is the file for one of your reddit post collection') parser.add_argument('input_file_d2') parser.add_argument('input_file_d3') parser.add_argument('-c','--candidate') parser.add_argument('-o','--output_file') args = parser.parse_args() ## We now get the list of titles for the 3 days we collected the reddit data from titles_day1 = get_post_titles(args.input_file_d1) titles_day2 = get_post_titles(args.input_file_d2) titles_day3 = get_post_titles(args.input_file_d3) # Now from the lists of titles from the 3 days we get the ones containing the name of # of the candidate of our choice candidate_titles_day1 = get_titles_by_candidate(titles_day1, args.candidate) candidate_titles_day2 = get_titles_by_candidate(titles_day2, args.candidate) candidate_titles_day3 = get_titles_by_candidate(titles_day3, args.candidate) # We now chose randomly for the three list of titles containign shortlist_day1 = choose_random_line(candidate_titles_day1,66) shortlist_day2 = choose_random_line(candidate_titles_day2,66) shortlist_day3 = choose_random_line(candidate_titles_day3,66) sample_titles = [] larger_list = [shortlist_day1,shortlist_day2]#,shortlist_day3] for sublist in larger_list: for title in sublist: sample_titles.append(title) posts = {'titles': sample_titles} df = pd.DataFrame(posts,columns = ['titles']) df.to_csv(f'{args.output_file}.csv', index = False, encoding = 'utf-8') if __name__ == '__main__': main()
5ce7ba3e97884502cc37ba8bcb675dacf8844206
Lor3nzoMartinez/Python
/SPR19/Quiz&EC/TakeHome_Quiz_5_2.py
871
3.625
4
import math def circleArea(R): A = math.pi*R**2 return round(A, 2) def circleCircumference(R): C = 2*math.pi*R return round(C, 2) def cylinderArea(R, H): SA = (circleCircumference(R)*H)+(2*circleArea(R)) return round(SA, 2) def cylinderVolume(R, H): V = circleArea(R)*H return round(V, 2) def AtoVRatio(R, H): AtoVRatio = cylinderArea(R, H) / cylinderVolume(R, H) return round(AtoVRatio, 2) # print(circleArea(12)) # # print(circleCircumference(12)) # # print(cylinderArea(12, 5)) # # print(cylinderVolume(12,5)) # # print(f'%{AtoVTRatio(12, 5)}') print('R H Cyl Area Cyl Vol (Cyl Area)/(Cyl Vol)') print('-------------------------------------------------') for i in range(1, 4): for j in range(4, 7): print(f'{i} {j} {cylinderArea(i, j)} {cylinderVolume(i, j)} {AtoVRatio(i, j)}')
4dde3bf3ae91901d0769b95a004deb2450d0e0db
RianMarlon/Python-Geek-University
/secao5_estruturas_condicionais/exercicios/questao38.py
2,838
4.1875
4
""" 38) Leia uma data de nascimento de uma pessoa fornecida através de três números inteiros: Dia, Mês e Ano. Teste a validade desta data para saber se esta é uma data válida. Teste se o dia fornecido é um dia válido: dia > 0, dia <= 28 para o mês (29 se o ano for bissexto), dia <= 30 em abril, junho, setembro e novembro, dia <= 31 nos outros meses. Teste a validade do mês: mês > 0 e mês <13. Teste a validade do ano: ano <= ano atual (use uma constante definida com o valor igual a 2008). Imprimir: "data válida" ou "data inválida" no final da execução. """ ano = int(input("Digite o ano do seu nascimento: ")) mes = int(input("Digite o mês do seu nascimento: ")) dia = int(input("Digite o dia do seu nascimento: ")) ano_atual = 2008 print() if ano <= ano_atual: if mes == 1: if (dia >= 1) and (dia <= 31): print("data válida") else: print("data inválida") elif mes == 2: if (ano % 400 == 0) or ((ano % 4 == 0) and not (ano % 100 == 0)): if (dia >= 1) and (dia <= 29): print("data válida") else: print("data inválida") else: if (dia >= 1) and (dia <= 28): print("data válida") else: print("data inválida") elif mes == 3: if (dia >= 1) and (dia <= 31): print("data válida") else: print("data inválida") elif mes == 4: if (dia >= 1) and (dia <= 30): print("data válida") else: print("data inválida") elif mes == 5: if (dia >= 1) and (dia <= 31): print("data válida") else: print("data inválida") elif mes == 6: if (dia >= 1) and (dia <= 30): print("data válida") else: print("data inválida") elif mes == 7: if (dia >= 1) and (dia <= 31): print("data válida") else: print("data inválida") elif mes == 8: if (dia >= 1) and (dia <= 31): print("data válida") else: print("data inválida") elif mes == 9: if (dia >= 1) and (dia <= 30): print("data válida") else: print("data inválida") elif mes == 10: if (dia >= 1) and (dia <= 31): print("data válida") else: print("data inválida") elif mes == 11: if (dia >= 1) and (dia <= 30): print("data válida") else: print("data inválida") elif mes == 12: if (dia >= 1) and (dia <= 31): print("data válida") else: print("data inválida") else: print("data inválida") else: print("data inválida")
1bce53158baf61b46e8f46a56d7b9dda229105e9
SergeyMakhotkin/client_server_apps
/L_1/task_4.py
629
3.625
4
# Преобразовать слова «разработка», «администрирование», «protocol», «standard» из строкового # представления в байтовое и выполнить обратное преобразование (используя методы encode и decode). VAR_1 = 'разработка' VAR_2 = 'администрирование' VAR_3 = 'protocol' VAR_4 = 'standard' VAR_LIST = [VAR_1, VAR_2, VAR_3, VAR_4] for item in VAR_LIST: utf_code = bytes(item, 'utf-8') print(f'{item}', utf_code, utf_code.decode('utf-8'), sep='\n') print('*' * 50)
6c16de233f4c52031b359daf0dccaeb054bece98
Jaehi/python_practice
/데코레이터_사용하기/decorator_functools_wraps.py
512
3.640625
4
import functools def is_multiple(x): def decorator(func): @functools.wraps(func) def wrraper(a,b): r = func(a,b) if r % x == 0: print(f'{func.__name__}의 반환값은 {x}의 배수가 맞습니다') else: print(f'{func.__name__}의 반환값은 {x}의 배수가 아닙니다') return r return wrraper return decorator @is_multiple(3) @is_multiple(7) def add(a,b): return a+b print(add(10,20))
fb689bb13db17910ffe49b62f51a7590b672dccd
sudoheader/TAOD
/powerball_simulator_app.py
2,211
4.28125
4
#!/usr/bin/env python3 import random print("---------------------Power Ball Simulator---------------------") white_balls = int(input("How many white-balls to draw from for the 5 winning numbers (Normally 69): ")) if white_balls < 5: white_balls = 5 red_balls = int(input("How many red-balls to draw from for the Power Ball (Normally 26): ")) if red_balls < 1: red_balls = 1 odds = 1 for i in range(5): odds *= white_balls - i odds *= red_balls / 120 print("You have a 1 in " + str(odds) + " chance of winning this lottery.") ticket_interval = int(input("Purchase tickets in what interval: ")) winning_numbers = [] while len(winning_numbers) < 5: number = random.randint(1, white_balls) if number not in winning_numbers: winning_numbers.append(number) winning_numbers.sort() number = random.randint(1, red_balls) winning_numbers.append(number) print("\n----------Welcome to the Power Ball----------") print("\nTonight's winning numbers are: ", end="") for number in winning_numbers: print(str(number), end=' ') input("\nPress 'Enter' to begin purchasing tickets!!!") tickets_purchased = 0 active = True tickets_sold = [] while winning_numbers not in tickets_sold and active == True: lottery_numbers = [] while len(lottery_numbers) < 5: number = random.randint(1, white_balls) if number not in lottery_numbers: lottery_numbers.append(number) lottery_numbers.sort() number = random.randint(1, red_balls) lottery_numbers.append(number) if lottery_numbers not in tickets_sold: tickets_purchased += 1 tickets_sold.append(lottery_numbers) print(lottery_numbers) else: print("Losing ticket generated; disregard...") if tickets_purchased % ticket_interval == 0: print(str(tickets_purchased) + " tickets purchased so far with no winners...") choice = input("\nKeep purchasing tickets (y/n): ") if choice != 'y': active = False if lottery_numbers == winning_numbers: print("\nWinning ticket numbers: ", end='') for number in lottery_numbers: print(str(number), end=' ') print("\nPurchased a total of " + str(tickets_purchased) + " tickets.") else: print("\nYou bought " + str(tickets_purchased) + " tickets and still lost!") print("Better luck next time!")
6f3fdfe71476b92790abdbca3efe1fc411a640b1
alexandraback/datacollection
/solutions_2700486_0/Python/debiatan/B.py
1,422
3.765625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys def read_int(f): return int(f.readline().strip()) def read_l_int(f): return [int(e) for e in f.readline().strip().split()] possible_worlds = [] def simulate(world, N): if not N: possible_worlds.append(world) return x, y = 0, 0 while (x,y) in world: y += 2 if y == 0: return simulate(world+[(x, y)], N-1) if ((x+1, y-1) in world) and ((x-1, y-1) in world): return simulate(world+[(x, y)], N-1) # Two branches orig_x, orig_y = x, y if (x+1, y-1) not in world: while (x+1, y-1) not in world and y > 0: x += 1 y -= 1 simulate(world+[(x,y)], N-1) x, y = orig_x, orig_y if (x-1, y-1) not in world: while (x-1, y-1) not in world and y > 0: x -= 1 y -= 1 return simulate(world+[(x,y)], N-1) def solve(N, X, Y): global possible_worlds res = 0. x, y = 0, 0 possible_worlds = [] simulate([], N) total = len(possible_worlds) good = sum((X,Y) in p for p in possible_worlds) return float(good)/total if __name__ == '__main__': if len(sys.argv)<2: print 'Syntax', sys.argv[0], 'fname' sys.exit(1) f = open(sys.argv[1]) n_cases = read_int(f) for i_case in range(1, n_cases+1): N, X, Y = read_l_int(f) print 'Case #%d:'%i_case, solve(N, X, Y)
5794c78f3bf2909ea2b61cb1333a1f29ac94bb51
manutdmohit/mypythonexamples
/pythonexamples/exceptionhandling2.py
343
3.71875
4
try: x=int(input('Enter First Number:')) y=int(input('Enter Second Number:')) print('The result:',x/y) except BaseException as msg: print('The type of exception:',type(msg)) print('The type of exception:',msg.__class__) print('The name of class',msg.__class__.__name__) print('The Description of exception:',msg)
88b1cd889dae0c91d0a6058039cfb8abd46b9984
mel-c-lowe/Python_Challenge
/PyPoll/main.py
4,545
3.796875
4
# Import OS and CSV modules import os import csv # Establish file path election_csv_file = os.path.join("Resources", "election_data.csv") # Set up to read election_csv_file and refer to it as election_data with open(election_csv_file) as election_data: # Build the csvreader, print header to confirm document is reading electionreader = csv.reader(election_data, delimiter=",") header = next(electionreader) #print(f"CSV Header: {header}") # Establish empty list for candidate column vote_cast = [] # Loop through data to fill vote_cast list for voter in electionreader: vote_cast.append(str(voter[2])) # That's all I need in that loop because now I can read my list # and set the csvfile aside as all additional data will not impact # the election results # Credit to Stephanie Richards for sharing her approach to pull data to a lists vs a dictionary # This helped me simplify a LOT of the work that had me stumped. # Count the number of votes total_vote_count = len(vote_cast) #print(total_vote_count) # Identify unique names in vote_cast list # Count appearances of each name in vote_cast list # Identify the unique candidates unique_candidates = [] for vote in vote_cast: # Look through the list if vote not in unique_candidates: unique_candidates.append(vote) # Check to see list has all 4 and only 4 desired candidates print(unique_candidates) # Identify vote counts for each candidate candidate_votes = [] # Start with the list of all votes cast and counter of 0 vote_count = 0 for vote in unique_candidates: # And compare to name in candidate list for name in vote_cast: # Start running total of votes for candidates if vote == name: vote_count = int(vote_count) + 1 # Add to the list candidate_votes.append(vote_count) #Reset counter for next unique name vote_count = 0 print(candidate_votes) # Calculate percentages, use float to keep numbers after decimal # Round to three decimal places # I have tried numerous formatting opetions, but it either gives me no zeros after the decimal # or it gives me 6. Since all the numbers round to a whole number (no value in the decimal place), # I elected to be satisfied with this formatting. percent_of_vote = [] for each in (candidate_votes): vote_percent = round(float(int(each) / int(total_vote_count)), 3) percentage = "{:.00%}".format(vote_percent) percent_of_vote.append(percentage) # print(percentage) # Ok, so I now have three lists: candidate names, vote counts, and percentages # The first determines the order in which the second two display data as it is used # as the initial comparison to draw out the counts and calculate percentages # Identify winner election_winner = max(percent_of_vote) index_for_winner = percent_of_vote.index(election_winner) winner = unique_candidates[index_for_winner] print(winner) # Results Formatting # Following the example of Stephanie Richards and Beau Jeffrey, I removed the hardcoding # of four lines, one for each candidate, and zipped my reference lists into a tuple. # Many thanks to them for sharing their idea! # And many thanks to TA Benji for heling me print the tuple to a text file! election_results_tuple = tuple(zip(unique_candidates, percent_of_vote, candidate_votes)) print(election_results_tuple) print("Election Results") print("----------------------------------") print(f"Total Votes: {total_vote_count}") print("----------------------------------") for entry in election_results_tuple: print(f'{entry[0]}: {entry[1]} {entry[2]}') print("----------------------------------") print(f"Winner : {winner}") print("----------------------------------") # Thanks to Beau Jeffrey for cracking the \n new line syntax and sharing with me! # I have not applied \n to all lines because of issues printing the tuple # This combination simplified the instructions, but ensured appropriate printing of the tuple, # so I decided to keep it as it is below. analysis_textfile = os.path.join("Analysis", "PyPoll Analysis.txt") with open(analysis_textfile, "w") as PyPoll_Analysis: print("Election Results\n" "----------------------------------\n" f"Total Votes: {total_vote_count}\n" "----------------------------------", file = PyPoll_Analysis) for entry in election_results_tuple: print(f'{entry[0]}: {entry[1]} {entry[2]}', file = PyPoll_Analysis) print("----------------------------------\n" f"Winner : {winner}", file = PyPoll_Analysis)
0e44a922469c03352806da764e57dfa0814af93c
mishaplx/hackerrank
/task_2_1_1.py
602
3.625
4
# задать список студентов с оценками (name scores) и вывести среднюю оценку зная имя студента if __name__ == '__main__': n = int(input()) sum = 0 answer = 0 student_marks = {} for _ in range(n): name, *line = input().split() scores = list(map(float, line)) student_marks[name] = scores query_name = input() srednee = student_marks.setdefault(query_name) for i in range(len(srednee)): sum += srednee[i] answer = sum / len(srednee) print('{:.2f}'.format(answer))
012e49f2772e6106a1d288550ccb5defe00088be
DZAymen/dz-Trafico
/dzTraficoBackend/dzTrafico/BusinessEntities/LCRecommendation.py
677
3.546875
4
class LCRecommendation: TURN_LEFT = -1 TURN_RIGHT = 1 STRAIGHT_AHEAD = 0 CHANGE_TO_EITHER_WAY = 2 change_lane = True change_to_either_way = False recommendation = 0 def __init__(self, lane, recommendation): self.lane = lane self.recommendation = recommendation if recommendation == self.TURN_RIGHT: self.target_lane = lane - 1 elif recommendation == self.TURN_LEFT: self.target_lane = lane + 1 elif recommendation == self.CHANGE_TO_EITHER_WAY: self.change_to_either_way = True elif recommendation == self.STRAIGHT_AHEAD: self.change_lane = False
99b44e11888b9edddfedbff223001c380b14d9ee
bzd111/PythonLearn
/decorator_use/decorator_def_with_args.py
708
3.59375
4
# -*- coding: utf-8 -*- from functools import wraps def decorate_args(name): def warp(func): @wraps(func) def warp_func(*args, **kwargs): print('{} say:'.format(name)) return func(*args, **kwargs) return warp_func return warp @decorate_args(name='zxc') def say_hello(): return ' hello' def say_hello_none(): return ' hello' class TestSay(object): @decorate_args(name='zxc') def say_hello(self): return ' hello' if __name__ == "__main__": print(say_hello()) print("-"*30) print(decorate_args(name='zcx')(say_hello_none)()) print("-"*30) test = TestSay() print(test.say_hello())
3b9e631b1cdf496234f6635dafafff14b9ce24b9
haileytyler/cmpt120-tyler
/Classwork/1.7.19Classwork.py
1,281
4.21875
4
#Hailey Tyler #Lab 3 from math import * #4 #a for i in range(1, 11): print(i*i) #b for i in [1, 3, 5, 7, 9]: print(i, ":", i**3) print(i) #c x = 2 y = 10 for j in range(0, y, x): print(j, end="") print(x + y) print("done") #d ans = 0 for i in range(1, 11): ans = ans + i*i print(i) print(ans) #2 def pizza(): print("This program calculates the cost per square inch of a circular pizza") diameter = int(input("What is the diameter of the pizza? (inches)")) price = round(float(input("What is the price of the pizza?")), 2) radius = diameter/2 area = pi*((radius) ** 2) cost = round(price/area, 2) print("The cost per square inch of the pizza is", cost, "dollars.") print("Press <Enter> to end the program.") pizza() #10 def ladder(): print("This program calculates the length of a ladder required to reach a given height when leaned against a house.") height = float(input("What is the height of the house? (feet)")) angle_degrees = float(input("What is the angle of the ladder against the house? (degrees)")) angle_radians = (pi/180)*angle_degrees length = round((height/sin(angle_radians)), 2) print("The length of the ladder is", length, "feet.") print("Press <Enter> to end the program.") ladder()
1607fff42a84cbf0cfe8f2e29e65dda7ceedb23f
liusska/Python-Basic-Sept-2020-SoftUni
/ConditionalStatment/ex/2.BonusScore.py
309
3.53125
4
number = int(input()) bonus = 0 if number <= 100: bonus += 5 elif number > 100: if number > 1000: bonus += number * 0.10 else: bonus += number * 0.20 if number % 2 == 0: bonus += 1 elif number % 10 == 5: bonus += 2 print(bonus) print(bonus + number)
dbf4b44474d1c922b694d4775333f9b091643d1e
vsofi3/UO_Classwork
/313/OwenMcEvoy_Lab3/OwenMcEvoy_MaxHeap.py
4,422
3.953125
4
class MaxHeap(object): def __init__(self, size): # finish the constructor, given the following class data fields: self.__maxSize = size self.__length = 0 self.__myArray = [] #i will be using the append feature, the list size is exactly how many items there are this way ''' free helper functions ''' def getHeap(self): return self.__myArray def getMaxSize(self): return self.__maxSize def setMaxSize(self, ms): self.__maxSize = ms def getLength(self): return self.__length def setLength(self, l): self.__length = l ''' Required Methods ''' def insert(self, data): # Insert an element into your heap. # When adding a node to your heap, remember that for every node n, # the value in n is greater than or equal to the values of its children, # but your heap must also maintain the correct shape. size = self.getMaxSize() if self.__length == self.__maxSize: self.setMaxSize(size + 1) self.__myArray.append(data) self.__length += 1 self.__heapify() def maximum(self): # return the maximum value in the heap maximum = self.__myArray[0] return maximum def extractMax(self): index = 0 #in a max heap, largest value is at the 0 index rMax = self.__myArray.pop(index) self.__length -= 1 self.__heapify() return rMax def __heapify(self, node = None): # helper function for reshaping the array if node is None: node = self.__length // 2 #starting index for heapify process lChild = (2 * node) + 1 #location of the left child in the array rChild = (2 * node) + 2 #location of the right child in the array while rChild > (self.__length - 1): #error checking technique, ensures that list index is not out of range node = node - 1 #rChild > lChild, so that is what we must be checking lChild = (2 * node) + 1 if lChild == (self.__length - 1): #checks to see if left child is the last item in the heap swapVal = self.__myArray[lChild] #this is only the case when the node has a left child but no right child if swapVal > self.__myArray[node]: #so the index of the left child is the last one in the array self.swap(lChild, node) nNode = node - 1 if nNode >= 0: #we want to be able to access array at index[0], index[-1] would self.__heapify(nNode) #return last item in the array else: pass rChild = (2 * node) + 2 if self.__myArray[lChild] and self.__myArray[rChild]: #case where there are two children if self.__myArray[lChild] > self.__myArray[rChild]: swapVal = lChild else: #determines the larger of the 2 children to swap with swapVal = rChild if self.__myArray[swapVal] > self.__myArray[node]: #if the child is greater than the parent, swap self.swap(swapVal, node) nNode = node - 1 if nNode >= 0: #makes sure node index is not 0 self.__heapify(nNode) #recursively calls heapify using decremented index else: pass ''' Optional Private Methods can go after this line # If you see yourself using the same ~4 lines of code more than once... # You probably want to turn them into a method.''' def swap(self, x, y): temp = self.__myArray[y] #to save a couple of lines of code in heapify i made this swap function self.__myArray[y] = self.__myArray[x] #swaps values at indexes x&y in the array self.__myArray[x] = temp def buildMax(self): self.__heapify() #calling this will turn the unsorted array into a maxheap ''' heap = MaxHeap(10) heap.insert(5) heap.insert(12) heap.insert(64) heap.insert(1) heap.insert(37) heap.insert(90) heap.insert(91) heap.insert(97) print(heap.getHeap()) print(heap.maximum()) print(heap.extractMax()) print(heap.getHeap()) '''
0f1eea9e2d131bef30feadf75380ed92a1f34c92
imgsc/assistScript
/pokerLife/pokerLife.py
836
3.8125
4
''' Listen to me What's your poker life? Please put your birthday and you can see your life... ''' import datetime,time def getPoker(str): t=time.strptime(str,'%Y-%m-%d') y,m,d = t[0:3] #print (datetime.datetime(y,m,d)) pokerNumber = ['Ace','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King'] pokerColor = ['Spades','Hearts','Diamonds','Clubs'] birthday = datetime.date(y, m, d).isocalendar() year,week,day = birthday[0:3] birthNumber = week//4 birthColor = week%4-1 return y,m,d,pokerNumber[birthNumber],pokerColor[birthColor] if __name__ == '__main__': str = input("Enter your birthday(yyyy-mm-dd): ") y,m,d,pokerNumber,pokerColor = getPoker(str)[0:5] print('Birthday :'+datetime.date(y, m, d).strftime('%Y-%m-%d')) print('Poker : the '+pokerNumber+' of '+pokerColor)
15533ace6ab93490bfde15364120c5c0c3b5ae3c
darkframemaster/here-and-there
/python/pygame/day_three/day_three_arc.py
585
3.96875
4
#!/usr/bin/env python2.7 import math import pygame from pygame.locals import * pygame.init() screen=pygame.display.set_mode((600,500)) pygame.display.set_caption("Drawing Arcs") while True: for event in pygame.event.get(): if event.type in (QUIT,KEYDOWN): #More Python Programming 30 gramming for the Absolute Beginner sys.exit() screen.fill((0,0,200)) #draw the arc color =255,0,255 position=200,150,200,200 start_angle=math.radians(0) end_angle=math.radians(180) width=8 pygame.draw.arc(screen,color,position,start_angle,end_angle,width) pygame.display.update()
87cb54327684e8564caad04da370f993a1fc627a
121jigowatts/til
/python/basis/file_operations/text_reader.py
267
3.53125
4
# text file reader import os path = './text.txt' if os.path.exists(path): with open('text.txt', 'r') as f: print(f.read()) while True: line = f.readline() print(line, end='') if not line: break
a78727bba0ccf3ccd05747d64f47f375c36d2a36
AugmentHCI/Tobii4C
/Experiment/Vector.py
2,360
3.546875
4
import math import numpy as np class Vector: def __init__(self, p1, p2): """ :param p1: Coordinate :param p2: Coordinate """ self.startPoint = p1 self.endPoint = p2 self.vector = self.calculateVector() self.direction = None self.setDirection() def calculateVector(self): x1 = self.startPoint.getX() x2 = self.endPoint.getX() y1 = self.startPoint.getY() y2 = self.endPoint.getY() vector = [x2 - x1, y2 - y1] return vector def getVector(self): return self.vector def getMagnitude(self): return np.linalg.norm(self.getVector()) def getDeltaX(self): return self.vector[0] def getDeltaY(self): return self.vector[1] def getAbsAngle(self): ''' Angle in degrees :return: ''' dx = self.getDeltaX() dy = self.getDeltaY() if dx != 0: radAngle = math.atan(dy / dx) degAngle = math.degrees(radAngle) else: degAngle = 90 return degAngle def getAngleBetween(self, v1): radAngle = angle_between(self.getVector(), v1.getVector()) degAngle = math.degrees(radAngle) return degAngle def getDirection(self): return self.direction def setDirection(self): angle = self.getAbsAngle() direction = 0 if angle < 45: direction = 0 elif angle < 90: direction = 1 elif angle < 135: direction = 2 elif angle < 180: direction = 3 elif angle < 225: direction = 4 elif angle < 270: direction = 5 elif angle < 315: direction = 6 elif angle < 360: direction = 7 else: direction = 8 self.direction = direction def unit_vector(vector): """ Returns the unit vector of the vector. """ if np.linalg.norm(vector) == 0: return vector else: return vector / np.linalg.norm(vector) def angle_between(v1, v2): """ Returns the angle in radians between vectors 'v1' and 'v2':: """ v1_u = unit_vector(v1) v2_u = unit_vector(v2) angle = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)) return angle
9e0b1c76f509e42f4384bb56bc96ca0191ac2967
rahul-bhave/python-practice
/random_generator.py
2,816
4.21875
4
""" This script is an example of how to pick groups of 'r' people randomly from within a larger sample of N people such that no single person appears in two groups. I find this script useful when I have to divide my employees into groups randomly First Output: $ python random_generator.py Groups chosen are: 0. ('Shiva', 'Rahul') 1. ('Smitha', 'Nilaya') 2. ('Mohan', 'Raji') 3. ('Preedhi', 'Annapoorani') 4. ('Kiran', 'Avinash') 5. ('Raj', 'Rohan D.') 6. ('Indira', 'Rohini') 7. ('Sravanti', 'Akkul') """ import argparse import itertools import random #Note: Listing employees just to keep the example short #You would (ideally) get a list of employees from some central datastore #UPDATE EMPLOYEES TO SUIT YOUR CONTEXT EMPLOYEES = ['Raji', 'Avinash', 'Shiva', 'Annapoorani', 'Rohan D.', 'Smitha', 'Indira', 'Rohan J.', 'Nilaya', 'Mohan', 'Rohini', 'Sravanti', 'Rahul', 'Preedhi', 'Raj', 'Kiran', 'Akkul'] def check_no_overlap(my_tuple, reference_list): """ Verify if at least one member of a tuple overlpas with the members in a list of tuples :return result_flag: boolean """ result_flag = True for reference_tuple in reference_list: result_flag &= set(my_tuple).isdisjoint(set(reference_tuple)) if result_flag is False: break return result_flag def get_groups(group_size): """ Return groups of size group_size :return groups: list of tuples """ unique_groups = [] expected_num_groups = int(len(EMPLOYEES)/group_size) #We shuffle the combinations to keep the order fresh everytime random.shuffle(EMPLOYEES) if group_size >= len(EMPLOYEES): unique_groups.append(tuple(EMPLOYEES)) else: #all_combos is a list of all group_size combinations all_combos = list(itertools.combinations(EMPLOYEES, group_size)) #Our next step is to make the groups disjoint #'disjoint' = One employee cannot appear in two groups for combo in all_combos: if check_no_overlap(combo, unique_groups): unique_groups.append(combo) #A small optimization is to stop checking combos once we reach the expected number of groups if len(unique_groups) == expected_num_groups: break return unique_groups #----START OF SCRIPT if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--size', dest = 'size', type = int, default = 2, help = 'Size of the group you want') args = parser.parse_args() if args.size < 1: parser.error(f'Invalid argument --size {args.size}. Group size should be an positive integer.') groups = get_groups(args.size) if len(groups): print('Groups chosen are:') for i, group in enumerate(groups): print(f'{i}. {group}')
54572845440f7150285779f961629266fa23be08
DoctorTeeth/diffmem
/ntm/memory.py
1,878
4.09375
4
""" Implements functions for reading and writing from and to the memory bank via weight vectors as in section 3. """ import autograd.numpy as np def read(mem, weight_vector): """ The reading procedure as described in 3.1. weight_vector (w_t below) is a weighting over the rows such that: 1. \sum_i w_t(i) = 1 2. 0 \leq w_t(i) \leq 1, \forall i We return \sum_i w_t(i) M_t(i); M_t(i) is the i-th row of memory. """ return np.dot(weight_vector.T, mem) def write(mem, w_t, e_t, a_t): """ The writing procedure as described in 3.2. w_t is a length N weighting over the rows as above. e_t (the erase vector) is length M with elements all in (0,1). a_t (the add vector) is length M with no such restrictions. We first multiply the memory matrix pointwise by [1-w_t(i)e_t] Then we do M_t(i) <- w_t(i)a_t. According to the paper, the erase/add decomposition was inspired by the forget/input gates in LSTM. """ # Perform erasure on the existing memory, parametrized by e_t and w_t W = np.reshape(w_t, (w_t.shape[0], 1)) E = np.reshape(e_t, (e_t.shape[0], 1)) # Transpose W so we can create WTE, a matrix whose i,j-th element # represents the extent to which we will erase M_t[i,j] WTE = np.dot(W, E.T) # KEEP is such that KEEP[i,j] represents the extent to which we # will keep M_t[i,j] KEEP = np.ones(mem.shape) - WTE # To complete erasure, multiply memory pointwise by KEEP newmem = np.multiply(mem, KEEP) # Perform addition on the newly erased memory # Convert add vector to a matrix A = np.reshape(a_t, (a_t.shape[0], 1)) # Add is the add vector weighted by w_t, which is added pointwise to # the existing memory, finishing the write sequence. ADD = np.dot(W, A.T) newmem = newmem + ADD return newmem
75a5b6d1b7e60a8d3ddf4c8732f6c1d041d7bc19
AJEET-JAISWAL922/Condition
/Ifelse.py
147
4.0625
4
a=3 b=5 if b % a == 0: print("b is divisible by a") elif b+1 == 10: print("increement in b produce 10") else: print("you are in else")
e3fcc01a7ba4d0084d536859d553cb71c889f555
Ivan6248/uiuc
/leetcode/two-sum.py
1,365
3.71875
4
# Given an array of integers, return indices of the two numbers such that they add up to a specific target. # You may assume that each input would have exactly one solution. # Example: # Given nums = [2, 7, 11, 15], target = 9, # Because nums[0] + nums[1] = 2 + 7 = 9, # return [0, 1]. # UPDATE (2016/2/13): # The return format had been changed to zero-based indices. Please read the above updated description carefully. class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ sorted_nums = sorted(nums) start = 0 end = len(sorted_nums) - 1 if end <= 1: return [] while start < end: sum = sorted_nums[start] + sorted_nums[end] if sum == target: break elif sum < target: start += 1 else: end -= 1 if start >= end: return [] for i in range(0, len(nums)): if sorted_nums[start] == nums[i]: start = i break for i in range(0, len(nums)): if start != i and sorted_nums[end] == nums[i]: end = i break if start > end: start, end = end, start return [start, end]
b5413854357454b58e843d3f2c7081e126f2785e
joook1710-cmis/joook1710-cmis-cs2
/function.py
3,016
3.859375
4
#Added two arguements def add(a,b): return a + b c = add(3, 4) print c #Subtraction two arguements def sub(j,k): return j - k l = sub(5, 3) print l #Multiplied two arguements def mul(r,t): return r * t e = mul(4,4) print e #Divided two arguements def div(q,w): return float(q / w) y = div(2,3) print y #Defined hours from seconds def hours_from_seconds_div(a,b): return a/b s = div(86400, 3600) print s #Representation of a radius of a circle def circle_area(r): return 3.14159265359 * (r**2) print circle_area(5) #Representation of a volume of the sphere def sphere_volume(v): return 3.14159265359 * 1.333333333333 * (v**3) print sphere_volume(5) #Representation of the average of the volumes def avg_volume(a,b): return ((1.0/6 * 3.14159265359 * a**3) + (1.0/6 * 3.14159265359 * b**3)) /2 print avg_volume (10,20) #Representation of the 3 side lengths of a triangle def area(a,b,c): n= (a+b+c)/2 return (n*(n-a)*(n-b)*(n-c))**0.5 print area(1, 2, 2.5) #Making a string an agrument and returnng it as a work with additional space def right_align(word): return (80-len(word))*(" ") + word print right_align( "Hello" ) #String as an agrument that is centered def center(word): return (40-len(word))*(" ") + word print center("Hello") #Message box #string as an argument and returns a message box def msg_box(word): return "+" + ((len(word)+4)*"-") + "+" + "\n" + "|" + (2*" ") + (word)+ (2*" ") + "|" + "\n" + "+" + ((len(word)+4)*"-") + "+" print msg_box("Hello") print msg_box("I eat cats!") #calling functions add1= add(5,6) add2= add(6,3) sub1= sub(9,3) sub2= sub(5,4) mul1= mul(2,3) mul2= mul(2,4) div1= div(5,3) div2= div(7,4) hoursfromsec1= hours_from_seconds_div(97000,4800) hoursfromsec2= hours_from_seconds_div(87000,4800) circlearea1= circle_area(4) circlearea2= circle_area(9) spherevolume1= sphere_volume(8) spherevolume2= sphere_volume(3) averagevolume1= avg_volume(6,4) averagevolume2= avg_volume(4,4) area1= area(1,2,3) area2= area(4,5,6) rightalign1= right_align("LOL") rightalign2= right_align("YEAA") center1= center("hahaha") center2= center("What") msgbox1= msg_box("Poop") msgbox2= msg_box("yo") #printing the functions print msg_box (str(add1)) print msg_box (str(add2)) print msg_box (str(sub1)) print msg_box (str(sub2)) print msg_box (str(mul1)) print msg_box (str(mul2)) print msg_box (str(div1)) print msg_box (str(div2)) print msg_box (str(hoursfromsec1)) print msg_box (str(hoursfromsec2)) print msg_box (str(circlearea1)) print msg_box (str(circlearea2)) print msg_box (str(spherevolume1)) print msg_box (str(spherevolume2)) print msg_box (str(averagevolume1)) print msg_box (str(averagevolume2)) print msg_box (str(area1)) print msg_box (str(area2)) print msg_box (str(rightalign1)) print msg_box (str(rightalign2)) print msg_box (str(center1)) print msg_box (str(center2)) print msg_box (str(msgbox1)) print msg_box (str(msgbox2)) #def is a keyword that indicates that this is a function definition #print would print out the outcome
ccec1917e26009da120a4f796c47720bd3f1dda8
wpy-111/python
/month01/progect_month01/game2048/bill.py
2,660
3.59375
4
""" 2048游戏核心算法 """ import random class GameCoreController: def __init__(self): self.list_merge=None self.__map = [[0, 0, 0, 0], [0, 0, 0, 0 ], [0, 0, 0, 0 ], [0, 0, 0, 0]] self.__list_blank_location=[] @property def map(self): return self.__map def __zero_to_end(self): for i in self.list_merge[::-1]: if i == 0: self.list_merge.remove(i) self.list_merge.append(0) def __merge_element(self): self.__zero_to_end() for m in range(len(self.list_merge) - 1): if self.list_merge[m] == self.list_merge[m + 1]: self.list_merge[m] = self.list_merge[m] * 2 del self.list_merge[m + 1] self.list_merge.append(0) def move_left(self): for line in self.map: self.list_merge = line self.__merge_element() def move_right(self): for line in self.__map: self.list_merge = line[::-1] self.__merge_element() line[::-1] = self.list_merge def __transpose(self): for c in range(0, 3): for i in range(c + 1, 4): self.map[i][c], self.map[c][i] = self.map[c][i], self.map[i][c] def move_up(self): self.__transpose() self.move_left() self.__transpose() def move_down(self): self.__transpose() self.move_right() self.__transpose() def random_digits(self,a,b): return random.randint(a,b) def add_random_digits(self): self.__list_blank_location.clear() self.calculate_blank(self.__list_blank_location) number=self.random_digits(0,len(self.__list_blank_location)-1) number01=self.__list_blank_location[number][0] number02=self.__list_blank_location[number][1] self.map[number01][number02]=self.craet_random_number() def calculate_blank(self,list_zero): for i in range(len(self.map)): for c in range(len(self.map)): if self.map[i][c] == 0: list_zero.append((i, c)) def craet_random_number(self): number=self.random_digits(1,10) if 0<number<10: return 2 else: return 4 def judgement_game_over(self): if len(self.__list_blank_location):return False for i in range(4): for c in range(3): if self.map[i][c]==self.map[i][c+1]or self.map[c][i]==self.map[c+1][i]: return False return True
c342f4445e068d3cb94dad84361903773cb46255
AdamZhouSE/pythonHomework
/Code/CodeRecords/2533/60643/235145.py
183
3.78125
4
lst=input()#输入默认是列表 even = [] odd=lst for i in lst: if i%2==0: even.append(i) for i in even: if i in odd: odd.remove(i) res = even+odd print(res)
650746152141a9c2c46fe14a1f1c1483e98d3c46
KRLoyd/holberton-system_engineering-devops
/0x18-api_advanced/0-subs.py
953
3.5
4
#!/usr/bin/python3 """ Module for Task 0 of Holberton Project #314 """ import requests import sys def number_of_subscribers(subreddit): """ Queries the Reddit API for the number of subscribers for a subreddit. Subreddit is passed as an argument. If the subreddit is not valid, 0 is returned. """ # set variables request_url = 'https://www.reddit.com/r/{}/about.json'.format(subreddit) headers = {'user-agent': 'chrome:number_of_subscribers_function:v1 (by /u/remyjuke)'} response = requests.get(request_url, headers=headers, allow_redirects=False) response_code = response.status_code if (response_code >= 300): return 0 subscriber_count = response.json().get("data").get("subscribers") return subscriber_count if __name__ == "__main__": number_of_subscribers("all") number_of_subscribers("fake_subreddit")
5bd7d0acac6c14256f22f3ce09077888dbe8424d
JulyKikuAkita/PythonPrac
/cs15211/plusone.py
2,818
3.640625
4
__source__ = 'https://leetcode.com/problems/plus-one/' # https://github.com/kamyu104/LeetCode/blob/master/Python/plus-one.py # Time: O(n) # Space: O(1) # Array # # Description: Leetcode # 66. Plus One # # Given a non-negative integer represented as a non-empty array of digits, plus one to the integer. # # You may assume the integer do not contain any leading zero, except the number 0 itself. # # The digits are stored such that the most significant digit is at the head of the list. # # Companies # Google # Related Topics # Array Math # Similar Questions # Multiply Strings Add Binary Plus One Linked List # import unittest class Solution: # @param digits, a list of integer digits # @return a list of integer digits def plusOne(self, digits): current, carry = 0, 1 #for i in xrange(len(digits) -1, -1, -1): for i in reversed(xrange(len(digits))): current = digits[i] + carry # +1 for digits[0] ; and + carry for digits[i] digits[i] = current % 10 carry = current / 10 if carry > 0: #digits = [1] + digits digits.insert(0,carry) return digits class SolutionOther: # @param digits, a list of integer digits # @return a list of integer digits def plusOne(self, digits): rans=[] sum=0 for i in range(len(digits)): #print i,sum,digits[i] sum += digits[i]*(10**(len(digits)-i-1)) sum+=1 while sum >=10 : rans += [sum%10] sum = int(sum/10) rans += [sum] return rans[::-1] class TestMethods(unittest.TestCase): def test_Local(self): print Solution().plusOne([9,9,9,9]) t1=SolutionOther() #print t1.plusOne([2,0,1,4]) #print t1.plusOne([1,0]) print t1.plusOne([199]) if __name__ == '__main__': unittest.main() Java = ''' # Thought: # 0ms 100% class Solution { public int[] plusOne(int[] digits) { int n = digits.length; for (int i = n - 1; i >= 0; i--) { if (digits[i] < 9) { digits[i]++; return digits; } digits[i] = 0; } int[] newNumber = new int[n + 1]; newNumber[0] = 1; return newNumber; } } # 0ms 100% class Solution { public int[] plusOne(int[] digits) { int carry = 1; int index = digits.length - 1; while (carry > 0 && index >= 0) { int sum = digits[index] + carry; digits[index] = sum % 10; carry = sum / 10; index--; } if (carry > 0) { int[] result = new int[digits.length + 1]; result[0] = 1; return result; } else { return digits; } } } '''
4ca8f48590cab2de6ba8dd2656607f03ac40cb1e
cpfyjjs/python
/FluentPython/16协程/04让协程返回值(StopInteration).py
525
3.90625
4
from collections import namedtuple Result = namedtuple('Result','count average') def averager(): total = 0 count =0 average = None while True: num = yield if num == None: break total +=num count +=1 average = total/count return Result(count,average) aver =averager() next(aver) for i in range(0,30,3): aver.send(i) try: aver.send(None) except StopIteration as e: result = e.value print(result) # Result(count=10, average=13.5)
246cdf8901d141ad8d1278ac283b6626458bcd7b
piweiblen/Number_Reader
/mlpt.py
5,287
3.953125
4
# defines a multilayer perceptron neural network class and associated algorithms import numpy as np import math def sigmoid(x): """perform sigmoid function""" if x < 0: a = math.e**x return a / (1 + a) else: return 1 / (1 + math.e**(-x)) def arr_sigmoid(arr): """perform sigmoid on an array""" sig = [] for f in arr: sig.append(sigmoid(f)) return np.array(sig) def inv_sigmoid(x): """perform inverse sigmoid function""" return -math.log(1/x - 1) def inv_dif_sig(x): """perform inverse sigmoid function, then derivative of the sigmoid this operation simplifies significantly also handy as it works with array input""" return x - x**2 def random(): """return a random float on the open interval (0, 1)""" x = np.random.random() if x == 0.0: # nasty edge case we don't want, negligible probability x = 0.5 # you saw nothing return x def rand_array(x, y, func=lambda x:x): """generates an x by y array of random numbers with an inverse sigmoid distribution""" arr = [] if y == 1: for f in range(x): arr.append(func(random())) else: for f in range(y): arr.append([]) for g in range(x): arr[-1].append(func(random())) return np.array(arr) def null_array(x, y, val=0): """generates an x by y array of zeros""" if y == 1: arr = x*[val] else: arr = [] for f in range(y): arr.append(x*[val]) return np.array(arr) class network(): def __init__(self, *layers): """initializes network with number of layers and neurons per layer specified in layers, where the first is input and the last is output""" self.layers = layers self.depth = len(layers) self.weights = [] self.biases = [] self.neurons = [] for f in range(1, self.depth): self.weights.append(rand_array(self.layers[f-1], self.layers[f], func=inv_sigmoid)) self.biases.append(rand_array(self.layers[f], 1, func=inv_sigmoid)) for f in self.layers: self.neurons.append(np.array(f*[0])) self.weights = np.array(self.weights) self.biases = np.array(self.biases) def evaluate(self, data): """take input data and output the neural network's evaluation also leaves the network state in self.neurons""" if len(data) != self.layers[0]: raise ValueError("Network input of invalid length") self.neurons[0] = np.array(data) for f in range(self.depth-1): self.neurons[f+1] = arr_sigmoid((self.weights[f] @ self.neurons[f]) + self.biases[f]) return self.neurons[-1] def cost(self, data, result): """claculate the distance between the evaluated result and the intended result""" actual = self.evaluate(data) result = np.reshape(result, self.layers[-1]) return ((actual-result)**2).sum() def all_cost(self, data, result): """claculate the distance between the evaluated results and the intended results""" num = len(data) costs = [] for f in range(num): costs.append(self.cost(data[f], result[f])) return costs def avg_cost(self, data, result): """claculate the average distance between the evaluated results and the intended results""" num = len(data) total_cost = 0 for f in range(num): total_cost += self.cost(data[f], result[f]) return total_cost/num def back_propagate(self, data_sets, result_sets, l_rate=1, momentum=[]): """back propagates the given data and intended results""" weight_change = [] bias_change = [] layer_change = [] for f in range(self.depth-1): weight_change.append(null_array(self.layers[f], self.layers[f+1])) bias_change.append(null_array(self.layers[f+1], 1)) for f in self.layers: layer_change.append(np.array(f*[0])) weight_change = np.array(weight_change) bias_change = np.array(bias_change) # for every data set, find the cost gradient and add to the total sum for cset in range(len(data_sets)): self.evaluate(data_sets[cset]) layer_change[-1] = l_rate*(np.array(result_sets[cset])-self.neurons[-1]) for f in range(self.depth-2, -1, -1): dz = inv_dif_sig(self.neurons[f+1]) bias_change[f] = bias_change[f] + (dz*layer_change[f+1]) weight_change[f] = weight_change[f] + (np.array([self.neurons[f]*dz[n]*layer_change[f+1][n] for n in range(len(self.neurons[f+1]))])) layer_change[f] = np.array([(self.weights[f][:,n]*dz*layer_change[f+1]).sum() for n in range(len(self.neurons[f]))]) # add momentum if any if momentum != []: weight_change += momentum[0] bias_change += momentum[1] # add the total cost gradient to the current network self.weights += weight_change self.biases += bias_change # return the change this go around return np.array([weight_change, bias_change])
3bb25e45db2dfef9974ced3ac9d7ddceaa469e29
Goom11/interview_practice
/islands/islands.py
839
3.5
4
#!/usr/bin/env python import itertools as it def islands(seq): top = max(seq) if top == 0: return 0 seq = [list(group) for _, group in it.groupby(seq, lambda x: x == top)] cur_islands = sum(1 for x in seq if top in x) seq = list(it.chain(*seq)) seq = [el if el != top else top - 1 for el in seq] cur_islands = cur_islands + islands(seq) return cur_islands def format_seq(seq): seq = [int(el) for el in seq.split()] seq = seq[1:] return seq def get_input(): k = int(raw_input()) seqs = [format_seq(raw_input()) for _ in xrange(k)] return seqs def print_results(results): for i, r in enumerate(results): print i + 1, r def main(): seqs = get_input() seqs = [islands(seq) for seq in seqs] print_results(seqs) if __name__ == "__main__": main()
43d8810f175171bd1568ffacea1a18f3368671f4
hsiaohan416/stancode
/SC_projects/games/quadratic_solver.py
938
4.25
4
""" File: quadratic_solver.py ----------------------- This program should implement a console program that asks 3 inputs (a, b, and c) from users to compute the roots of equation ax^2 + bx + c = 0 Output format should match what is shown in the sample run in the Assignment 2 Handout. """ import math def main(): """ TODO: """ print('hsiao quadratic solver!') a = int(input('Enter a= ')) if a == 0: print('FUCK YOU!! Enter again!!') a = int(input('Enter a= ')) b = int(input('Enter b= ')) c = int(input('Enter c= ')) discriminant = b*b-4*a*c if discriminant > 0: root_1 = (-b+math.sqrt(discriminant))/2*a root_2 = (-b-math.sqrt(discriminant))/2*a print("Two Roots=" + str(root_1) + "," + str(root_2)) elif discriminant == 0: root_0 = -b/2*a print('One Root= ' + str(root_0)) else: print('No Real Roots! Ugly Guy!') ###### DO NOT EDIT CODE BELOW THIS LINE ###### if __name__ == "__main__": main()
809812b090105adc4609194e8cb5cea78d22efdb
tcq1/epa
/epa_graphs.py
4,363
3.5625
4
import random import copy import collections def choose_nodes(choosen, target_nodes, edges): """ choose `edges` nodes from `target_nodes`, whitout `chossen` and doubled nodes Function is side effect free @param choosen list of already chossen elements @param list to choose elements from @param edges amount of edged @return nodes to pick """ target_nodes = copy.deepcopy(target_nodes) for elem in choosen: target_nodes.remove(elem) for _ in range(edges): node = random.choice(target_nodes) target_nodes.remove(node) yield node def gen_directed_graph(nodes = 1000, edge_factor = 2, costs = (1,1)): """ generates a dicrected graph with `nodes` nodes and `edge_factor` edges per node @param nodes amount of nodes @param edge_factor edges per node @param cost expects a tuple with (mu,sigma) for the normal distribution which generates the cost @retrun dict in the form dict[node] = [(node_1, cost), (node_2, cost), (node_3, cost)] """ graph = {} node_list = list(range(nodes)) for node_1 in range(nodes): graph[node_1] = [] for node_2 in choose_nodes([node_1], node_list, edge_factor): cost = random.gauss(costs[0],costs[1]) graph[node_1].append((node_2,cost)) return graph def gen_directed_graph_rand(nodes = 1000, edge_factor = 3, costs = (1,1)): """ generates a dicrected graph with `nodes` nodes and up to `edge_factor` edges per node @param nodes amount of nodes @param edge_factor up to `edge_factor` edges per node @param cost expects a tuple with (mu,sigma) for the normal distribution which generates the cost @retrun dict in the form dict[node] = [(node_1, cost), (node_2, cost), (node_3, cost)] """ graph = {} node_list = list(range(nodes)) for node_1 in range(nodes): graph[node_1] = [] edges = random.randint(1,edge_factor) for node_2 in choose_nodes([node_1], node_list, edges): cost = random.gauss(costs[0],costs[1]) graph[node_1].append((node_2,cost)) return graph def gen_undirected_graph(nodes = 1000, edge_factor = 2, costs = (1,1)): """ generates an undicrected graph with `nodes` nodes and around `edge_factor` edges per node @param nodes amount of nodes @param edge_factor approximate edges per node, might happen that some nodes have more edges @param cost expects a tuple with (mu,sigma) for the normal distribution which generates the cost @retrun dict in the form dict[node] = [(node_1, cost), (node_2, cost), (node_3, cost)] """ graph = collections.defaultdict(list) node_list = list(range(nodes)) for node_1 in range(nodes): if node_1 not in graph: graph[node_1] = [] edges = edge_factor - len(graph[node_1]) choosen = list(map(lambda x: x[0], graph[node_1])) choosen.append(node_1) for node_2 in choose_nodes(choosen, node_list, edges): cost = random.gauss(costs[0],costs[1]) graph[node_1].append((node_2,cost)) graph[node_2].append((node_1,cost)) return graph def gen_undirected_graph_rand(nodes = 1000, edge_factor = 3, costs = (1,1)): """ generates an undicrected graph with `nodes` nodes and up to `edge_factor` edges per node @param nodes amount of nodes @param edge_factor up to `edge_factor` edges per node @param cost expects a tuple with (mu,sigma) for the normal distribution which generates the cost @retrun dict in the form dict[node] = [(node_1, cost), (node_2, cost), (node_3, cost)] """ graph = collections.defaultdict(list) node_list = list(range(nodes)) for node_1 in range(nodes): if node_1 not in graph: graph[node_1] = [] edges = random.randint(1,edge_factor) edges = edges - len(graph[node_1]) choosen = list(map(lambda x: x[0], graph[node_1])) choosen.append(node_1) for node_2 in choose_nodes(choosen, node_list, edges): cost = random.gauss(costs[0],costs[1]) graph[node_1].append((node_2,cost)) graph[node_2].append((node_1,cost)) return graph
c57ecf5bf9ee70941186d6334e39ace1e1bc4f53
shi429101906/python
/07_语法进阶/hm_16_多值参数.py
282
3.6875
4
def demo(num, *nums, **person): print(num) print(nums) print(person) # demo(1) demo(1, 2, 3, 4, 5, name="小明", age=18) # atuple = (2, 4, 6) 直接传递元祖跟上面的不一样, 相当于元祖中又放了一个元祖 # demo(1, atuple, name="小明", age=18)
7eb7ec200e6794859fcdb18e95127bf4f4667127
estraviz/codewars
/7_kyu/Regex validate PIN code/test_solution.py
1,064
3.53125
4
from solution import validate_pin def test_should_return_False_for_pins_with_length_other_than_4_or_6(): assert validate_pin("1") is False assert validate_pin("12") is False assert validate_pin("123") is False assert validate_pin("12345") is False assert validate_pin("1234567") is False assert validate_pin("-1234") is False assert validate_pin("1.234") is False assert validate_pin("00000000") is False def test_should_return_False_for_pins_which_contain_chars_other_than_digits(): assert validate_pin("a234") is False assert validate_pin(".234") is False assert validate_pin("-123") is False assert validate_pin("-1.234") is False def test_should_return_True_for_valid_pins(): assert validate_pin("1234") is True assert validate_pin("0000") is True assert validate_pin("1111") is True assert validate_pin("123456") is True assert validate_pin("098765") is True assert validate_pin("000000") is True assert validate_pin("123456") is True assert validate_pin("090909") is True
0f253e5c5f347c7bdffef7ffb44801947f58b268
JaeZheng/jianzhi_offer
/62.py
768
3.75
4
""" 题目描述 给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。 """ # -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # 返回对应节点TreeNode def KthNode(self, pRoot, k): list = self.inorderTravel(pRoot) if len(list)==0 or k==0: return None if len(list) < k: return None return TreeNode(list[k-1]) def inorderTravel(self, root): if not root: return [] return self.inorderTravel(root.left) + [root.val] + self.inorderTravel(root.right)
8456b880078e2a3dd496a83347cc22b49866896a
YashaswiniPython/pythoncodepractice
/13_Loops.py
1,300
4.03125
4
# Python file Created By Bibhuti # for i in range(1,5) : # loop # print(i) # # print("Value outside the loop ",i); # for i in [1,2,8,5]: # print(i); #for i in (1,2,8,5): #print(i); # for i in {1,2,8,5}: # print(i); # for i in {1:2,"a":"Value of a",4:3}: # print(i); # for i in "Python" : # print(i) # for i in 1,2,3 : # print(i) # a=1,2,3; # print(a); # print(type(a)) # a=range(1,5); # It will store the value from 1 to 5-1=4 # print(type(a)); # list=["abc","defg"]; # for i in range(len(list)): # value of i itertate from 0 to length of the list -1 # print(i) # for i in range(0,4): # print(i); # break; # else: # print("else") """ While Loop """ # a=0; # while a<=5: # print(a); # a=a+1; # a=[1,2,"Python","Java","JS"]; # temp=0; # while temp<a.__len__() : # print(a[temp]); # temp=temp+1; # a=0; # while a<=3: # print(a); # a=a+1; # else: # print("While Loop Task Finished"); # a=0; # while a<=3: # print(a); # a=a+1; # break; # else: # print("While Loop Task Finished"); # for i in range(1,5): # if i==2: # continue; # continue will skip current execution only not whole thing # print(i); # for i in range(1,4): # if i==2: # pass # print(i);
dae5ae2efb31ebc3ef29a8cf9a6cd2e6a3e58ef9
MinjeongSuh88/python_workspace
/20200720/test5.py
230
3.6875
4
# 사용자로부터 숫자를 입력받아 홀수인지 짝수인지 판단 num=int(input("숫자를 입력하시오")) if num%2 == 0: print(num,"은 짝수입니다.") elif num %2 != 0: print(num,"은 홀수입니다.")
ca92472288c720adf4bf3685d7e501e155785199
MikiTeplitsky/PokerGame
/Poker_Game.py
7,520
3.734375
4
# Poker Game class # high card, pair, two pair, three of a kind, straight, flush, full house, # four of a kind, straight flush, royal straight flush(poker) # from Poker_Player import * from Deck import * from constants import * from Poker_Table import * # sum the values of the cards - working def sum_of_cards(player_cards): sum_cards = 0 for card in player_cards: sum_cards += card[0] return sum_cards def find_hand_for_two_pairs(all_cards): # init hand = list() extra = True # looking through all the cards for i in range(0, 7): # finding a pair (highest first) if all_cards[i][0] == all_cards[i + 1][0]: hand.extend([all_cards[i], all_cards[i + 1]]) i += 1 # if still haven't found a pair, we found our high card if extra is True: hand.extend(all_cards[i]) extra = False # after we found our 5 cards, we can finish if len(hand) == 5: i = 7 return hand # cards are sorted def find_hand_for_full_house(all_cards): # init hand = list() # looking through all the cards for i in range(0, 6): # finding a pair or a 3 of a kind if all_cards[i][0] == all_cards[i + 1][0]: hand.extend([all_cards[i][0], all_cards[i + 1][0]]) i += 1 if all_cards[i][0] == all_cards[i + 1][0]: i += 1 hand.extend(all_cards[i][0]) if len(hand) == 5: i = 7 return hand def find_hand_for_three_of_a_kind(all_cards): hand = list() extra = 0 # looking through all the cards for i in range(0, 6): # found 3 of a kind if all_cards[i][0] == all_cards[i + 1][0]: hand.extend([all_cards[i], all_cards[i + 1], all_cards[i + 2][0]]) i += 2 # 2 high cards elif extra != 2: hand.extend(all_cards[i]) extra += 1 if len(hand) == 5: i = 7 return hand def find_hand_for_four_of_a_kind(all_cards): hand = list() extra = True for i in range(0, 6): if all_cards[i][0] == all_cards[i + 1][0]: hand.extend([all_cards[i][0], all_cards[i + 1][0], all_cards[i + 2][0], all_cards[i + 3][0]]) i += 3 elif extra is True: hand.extend(all_cards[i][0]) extra = False if len(hand) == 5: i = 7 return hand # find a straight and returns if found + the cards for the straight def find_straight(cards): hand = list() result = 0 cards_values = list(dict(cards).keys()) # less the 5 unique values of cards => no chance for straight if len(cards_values) < 5: return result, hand for i in range(0, len(cards_values) - 4): if cards_values[i] == (cards_values[i + 1] - 1) and cards_values[i + 1] == (cards_values[i + 2] - 1) \ and cards_values[i + 2] == (cards_values[i + 3] - 1) and cards_values[i + 3] == ( cards_values[i + 4] - 1): result = STRAIGHT # getting the cards to hand for j in range(0, 7): if cards[j][0] == cards_values[i]: hand.extend(cards[j]) i += 1 if len(hand) == 5: j = 7 # what about 5, 4, 3, 2, Ace if result == 0 and cards_values[0] == 14: for i in range(0, len(cards_values) - 4): if cards_values[i] == (cards_values[i + 1] - 9) and cards_values[i + 1] == (cards_values[i + 2] - 1) \ and cards_values[i + 2] == (cards_values[i + 3] - 1) \ and cards_values[i + 3] == (cards_values[i + 4] - 1): result = STRAIGHT # getting the cards to hand for j in range(0, 7): if cards[j][0] == cards_values[i]: hand.extend(cards[j]) i += 1 if len(hand) == 5: j = 7 return result, hand # find a flush and returns if found + the cards for flush # Heart, Spade, Club, Diamond def find_flush(cards): # init hand = list() result = 0 count_h = 0 count_s = 0 count_c = 0 count_d = 0 # find out how many we got from each shape for i in range(0, 6): if cards[i][1] == 'Heart': count_h += 1 elif cards[i][1] == 'Spade': count_s += 1 elif cards[i][1] == 'Club': count_c += 1 else: count_d += 1 # do we have a flush? if count_d == 5 or count_h == 5 or count_s == 5 or count_c == 5: result = FLUSH if count_d == 5: shape = 'Diamond' elif count_c == 5: shape = 'Club' elif count_s == 5: shape = 'Spade' else: shape = 'Heart' # get the hand for i in range(0, 7): if cards[i][1] == shape: hand.extend(cards[i][1]) if len(hand) == 5: i = 7 return result, hand class Poker_Game: def __init__(self, player_list): self.player_list = player_list self.table_cards = list() self.table = Poker_Table() self.pot = 0 def calculate_hand(self, player): hand = list() best_choice = 0 # all cards all_cards = self.table_cards all_cards.extend(player.get_cards()) # sort by value all_cards.sort(reverse=True) # check pairs and three/four of a kind count_pairs = 0 kinds = 0 for i in range(0, 7): if all_cards[i][0] == all_cards[i + 1][0]: count_pairs += 1 if i != 4 and all_cards[i + 2][0] == all_cards[i][0]: kinds = 3 if i != 3 and all_cards[i + 3][0] == all_cards[i][0]: kinds = 4 # 3/4 of a kind + full house if kinds == 3: # 3of a kind + full house if count_pairs > 1: best_choice = FULL_HOUSE hand = find_hand_for_full_house(all_cards) else: best_choice = THREE_OF_A_KIND hand = find_hand_for_three_of_a_kind(all_cards) # 4 of a kind elif kinds == 4: best_choice = FOUR_OF_A_KIND hand = find_hand_for_four_of_a_kind(all_cards) # finds straight straight, hand_straight = find_straight(all_cards) # finds flush flush, hand_flush = find_flush(all_cards) # flush or straight if flush != 0 or straight != 0: # straight + flush if flush != 0 and straight != 0 and (hand_flush == hand_straight): hand = hand_straight # if the second highest card is a king then we got a royal straight flush if hand[1][0] == 13: best_choice = POKER else: # straight flush best_choice = STRAIGHT_FLUSH # flush elif best_choice < flush: best_choice = FLUSH hand = hand_flush # straight elif best_choice < STRAIGHT: best_choice = STRAIGHT hand = hand_straight if best_choice == 0: hand = all_cards[0:5] return sum_of_cards(hand) + best_choice
d04c6e0d3219e1ba6beeede86aec0aa9d5cacad0
footloops/Photo-To-ACSII
/PhotoToACSII/main.py
1,499
3.859375
4
from PIL import Image #Sorted from darkest symbol to lightest symbols = ["@", "#", "$", "%", "?", "*", "+", ";", ":", ",", "."] #Convert the pixels to the proper corresponding ASCII text def pixel_to_ascii(img): pixels = img.getdata() ascii_str = "" for pixel in pixels: #Divid the pixel ascii_str += symbols[pixel//25] return ascii_str #Converts image to grayscale so we can get pixel data def Convert_grayscale(img): return img.convert("L") #Resizing image by calculating aspect ratio and halving it to reduce size def resize(img): new_width = 100 width, height = img.size aspect_ratio = height/width new_height = aspect_ratio * new_width * 0.5 img = img.resize((new_width, int(new_height))) return img def main(): file = input(r"Enter the path to the image: ") try: img = Image.open(file) except: print("Invalid Path") img = resize(img) #convert image to grayscale image grayscale_image = Convert_grayscale(img) # convert greyscale image to ascii characters ascii_str = pixel_to_ascii(grayscale_image) img_width = grayscale_image.width ascii_str_len = len(ascii_str) ascii_img = "" #Split the string based on width of the image for i in range(0, ascii_str_len, img_width): ascii_img += ascii_str[i:i+img_width] + "\n" #save the string to a txt file and writes to it. with open("ascii_image.txt", "w") as f: f.write(ascii_img) main()
40f44b2177e12ad07ad2bb35f5a587bf1da687e5
kavyakammaripalle/python
/Day10-Session.py
549
3.578125
4
#!/usr/bin/env python # coding: utf-8 # In[7]: #classes:superclass-subclass class A: v1='iam variable one' v2='iam variable two' class B(A): pass a=A() a.v1 b=B() b.v2 # In[11]: #Overwrite a variable class A: v1='iam variable one' v2='iam variable two' v3='iam variable three' v4='iam variable four' class B(A): v4='iam modified variable' x=A() x.v4 y=B() y.v4 # In[13]: class mom: v1='iam mom' class dad: v2='iam dad' class child(mom,dad): v3='iam child' x=child() x.v1 x.v2 # In[ ]:
8438e6eff938a5764c2c3e40ed668714c54773d0
DanielWu18316/keyword-quiz
/main.py
1,900
3.578125
4
import random def setup(): global info, keywords, desc f = open("keywords.txt") info = f.readlines() f.close() keywords = [] desc = [] for i in range(0, len(info), 2): keywords.append(info[i]) for i in range(1, len(info), 2): desc.append(info[i]) process() def process(): user_choice = 0 user_choice = input( "Choose an option:\n1. Show Keywords + Description\n2. Play Quiz\n> ") if user_choice == "1": print("Selected: Show Keywords + Description") for i in range(0, len(info) // 2): print("\n-",keywords[i][:-1] + ":") print(desc[i][:-1]) user_choice = input( "\nWould you like to play the quiz now? [Y] or [N]\n> ") if user_choice == "Y": quiz() elif user_choice == "N": print("Okay") elif user_choice == "2": quiz() def quiz(): question_number = 1 points = 0 user_answer = "" print("\nEnter '-1' to stop quiz") while user_answer != "-1": question = random.choice(desc) print("\n- Question", question_number, "-\n" + question) user_answer = input("- Answer:\n> ") if user_answer.lower() == str(keywords[(desc.index(question))][:-1]): points = points + 1 print("Correct! +1\nPoints:", points) elif user_answer == "-1": print("\nEnding Quiz...") break else: print("Incorrect.\nThe answer was", keywords[(desc.index(question))][:-1]) question_number = question_number + 1 print("You got", points, "/", question_number - 1, "questions correct") if points == 0: print("You did not attempt the quiz\n") elif points > question_number // 2: print("You passed!\n") else: print("You did not pass.\n") setup() setup()
b94abd64d9ffb4a2af109cfa34c4f34c5b0a9b7c
chaunceyt/apisnoop
/dev/user-agent-stacktrace/lib/utils.py
291
3.5
4
from collections import defaultdict def defaultdicttree(): return defaultdict(defaultdicttree) def defaultdict_to_dict(d): if isinstance(d, defaultdict): new_d = {} for k, v in d.items(): new_d[k] = defaultdict_to_dict(v) d = new_d return d
8fd8d6873c0cf67ab012b1c3a52cd937193438de
chsclarke/Python-Algorithms-and-Data-Structures
/coding_challenge_review/LL_questions.py
4,309
4.46875
4
# -*- coding: utf-8 -*- """ This is an example of a Doubly Linked List in Python 3. Copyright 2018 Chase Clarke [email protected] """ class Node: def __init__(self,val): self.val = val self.next = None self.prev = None class LList: def __init__(self, node): self.head = node self.tail = None self.iterator = None def find(self, val): self.iterator = self.head #iterate through list until element is found or list ends while(self.iterator.next is not None): if (self.iterator.val is val): return ("found") self.iterator = self.iterator.next if(self.iterator.val is val): return("Found") if (self.iterator.next is None): return str(val) + " not found." def insert(self, val): insertNode = Node(val) self.iterator = self.head #if only one element if(self.head.next is None): self.head.next = insertNode insertNode.prev = self.head self.tail = insertNode return #> 1 element else: while(self.iterator.next is not None): self.iterator = self.iterator.next self.iterator.next = insertNode insertNode.prev = self.iterator self.tail = insertNode self.tail = insertNode def remove(self, val): self.iterator = self.head iterator = self.iterator #head of list if(self.head.val is val): self.head = self.head.next self.head.prev = None return #tail of list elif(self.tail.val is val): self.tail = self.tail.prev self.tail.next = None return #middle of list else: while(iterator.next is not None): iterator = iterator.next if(iterator.val is val): iterator.prev.next = iterator.next iterator.next.prev = iterator.prev return else: return str(val) + "not found." def printList(self): if(self.head is not None): self.iterator = self.head print(self.iterator.val, end=" -> ") while(self.iterator.next is not None): self.iterator = self.iterator.next print(self.iterator.val, end=" -> ") print("None") else: print("List is empty.") print("") # //////////////////////////////// LINKED LIST IMPLIMENTED ABOVE //////////////////////////////// # def reverseSLL(myList): #function built to reverse SLL #edge case: head of list previous = None current = myList.head nextNode = current.next myList.tail = current #middle of list while current.next != None: current.next = previous previous = current current = nextNode nextNode = nextNode.next #edge case: tail of list current.next = previous myList.head = current def detectCycle(myList): #tortoise and hare approach hare = myList.head.next tortoise = myList.head while hare.val != tortoise.val and hare.next != None: if (hare.next.next != None): hare = hare.next.next tortoise = tortoise.next if hare.val == tortoise.val: return True return False if __name__ == '__main__': node1 = Node(12) #initialize new node lst1 = LList(node1) #initialize new llist with node #add values to list lst1.insert(13) lst1.insert(14) lst1.insert(15) #print full list from head to tail lst1.printList() #reverses list reverseSLL(lst1) #print reversed list from head to tail print("Reversed list:") lst1.printList() #creating a circularly linked list lst1.tail.next = lst1.head #detecting cycle print("Cycle:", detectCycle(lst1))
480753a9cf15b2ca18814ccfd7d0e2c79f6d6232
zheng1073/Grokking-the-Coding-Interview-Patterns-for-Coding-Questions
/Pattern: Merge Intervals/Pattern_MergeIntervals.py
1,935
4.28125
4
""" Deals with overlapping intervals. In a lot of problems involving intervals, we either need to find overlapping intervals or merge intervals if they overlap. Six ways 2 intervals can relate to each other. 1. 'a' and 'b' do not overlap; 'a' before 'b' 2. 'a' and 'b' overlap and 'b' ends after 'a' 3. 'a' completely overlaps 'b' 4. 'a' and 'b' overlap, 'a' ends after 'b' 5. 'b' completely overlaps 'a' 6. 'a' and 'b' do not overlap; 'b' before 'a' """ #Merge Intervals (medium) """ Given a list of intervals, merge all the overlapping intervals to produce a list that has only mutually exclusive intervals. Time Complexity: O(NlogN) Space Complexity: O(N) """ from __future__ import print_function class Interval: def __init__(self, start, end): self.start = start self.end = end def print_interval(self): print("[" + str(self.start) + ", " + str(self.end) + "]", end='') def merge(intervals): #edge case if there is only one interval if len(intervals) < 2: return intervals #sort interval based on the start intervals.sort(key=lambda x: x.start) mergedIntervals = [] start = intervals[0].start end = intervals[0].end for i in range(1, len(intervals)): interval = intervals[i] #check if second interval is in our first interval if interval.start <= end: end = max(interval.end, end) else: mergedIntervals.append(Interval(start, end)) start = interval.start end = interval.end mergedIntervals.append(Interval(start, end)) return mergedIntervals #Insert Interval (medium) """ Given a list of non-overlapping intervals sorted by their start time, insert a given interval at the correct position and merge all necessary gintervals to produce a list that has only mutually exclusive intervals. Time Complexity: O(NlogN) Space Complexity: O(N) """
655447f43817d241cc30f6715596a2f631957820
SNithiyalakshmi/pythonprogramming
/Beginnerlevel/oddeven.py
117
3.78125
4
a=int(input()) if(a==0): print 'zero value' elif(a>=1 and a<=100000): print 'even value' else: print 'odd value'
3dd9e13d0dd32e098150e68b9ee292c05b615573
ma-lijun/ISO100-Stock
/stk_prc.py
3,128
3.53125
4
#Created on 2015/06/15, last modified on 2016/05/04 #By Teague Xiao #This script is aim to download the current price of a specific stock from SINA Stock #The info of each column is: stock number, stock name, opening price today, closing price today, current price, highest price today,lowest price today,don't know, don't know,stock dealed, price dealed today, date, time #Sample 1#: http://hq.sinajs.cn/list=sh601003 #Sample 2#: http://hq.sinajs.cn/list=sz000002 import urllib #import sqlite3 import MySQLdb import os import ConfigParser #stock_num = raw_input('Please enter the stock number(6 digits): ') #example stock_num = '000002' #conn = sqlite3.connect('stock.sqlite') Config = ConfigParser.ConfigParser() Config.read("settings.ini") con = MySQLdb.connect( Config.get('mysql', 'host'), Config.get('mysql', 'username'), Config.get('mysql', 'password'), Config.get('mysql', 'DB'), charset="utf8" ) c = con.cursor() c.execute('''CREATE TABLE IF NOT EXISTS stk_prc( stk_num CHAR(20) PRIMARY KEY, stk_name CHAR(20), open_prc float, close_prc float, current_prc float, highest_prc float, lowest_prc float, buy1 float, sell1 float, stock_dealed float, price_dealed float, date CHAR(20), time CHAR(20) )''') c.execute("SELECT stk_num from stk_lst") for stk_num in c.fetchall(): stk_num = stk_num[0] if stk_num.startswith('6'): url = 'http://hq.sinajs.cn/list=sh' + stk_num elif stk_num.startswith('0'): url = 'http://hq.sinajs.cn/list=sz' + stk_num elif stk_num.startswith('3'): url = 'http://hq.sinajs.cn/list=sz' + stk_num else: print 'Invalid stock number!' continue try: html = urllib.urlopen(url).read() except: print 'Invalid stock number!' continue l = html.split(',') start = l[0] #stk_name = start[-8:].decode('gb2312','ignore') stk_name = start[21:].decode('gb2312','ignore') #Remove the spaces between charaters stk_name = stk_name.replace(" ", "") #print len(html) if len(html) == 24: continue else: open_prc = l[1] close_prc = l[2] current_prc = l[3] highest_prc = l[4] lowest_prc = l[5] buy1 = l[6] sell1 = l[7] stock_dealed = l[8] price_dealed = l[9] date = l[30] time = l[31] #print stk_name,open_prc,close_prc,current_prc,highest_prc,lowest_prc,buy1,sell1 c.execute('''REPLACE INTO stk_prc ( stk_num, stk_name, open_prc, close_prc, current_prc, highest_prc, lowest_prc, buy1, sell1, stock_dealed, price_dealed, date, time) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)''', (stk_num,stk_name,open_prc,close_prc,current_prc,highest_prc,lowest_prc,buy1,sell1,stock_dealed,price_dealed,date,time,)) con.commit() c.close() #print "stk_prc process done!"
165384d3827b4f02899c3068d9794669ec08c926
lixinchn/LeetCode
/src/0130_SurroundedRegions.py
4,107
3.609375
4
class Solution(object): def solve(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ island_set = {} mapping = [[]] island_flipping = [] len_board = len(board) island = 1 board_temp = [] for i in range(len_board): line = [] board_temp.append(line) for j in range(len(board[i])): line.append(board[i][j]) if board[i][j] == 'O': island_top = island_set['%s_%s' % (i - 1, j)] if i - 1 >= 0 and '%s_%s' % (i - 1, j) in island_set else 0 island_left = island_set['%s_%s' % (i, j - 1)] if j - 1 >= 0 and '%s_%s' % (i, j - 1) in island_set else 0 if not island_top and not island_left: island_min = island elif island_top and island_left: island_min = min(island_top, island_left) elif island_top: island_min = island_top else: island_min = island_left if i == 0 or i == len_board - 1 or j == 0 or j == len(board[i]) - 1: island_flipping.append(island_min) if not island_top and not island_left: island_set['%s_%s' % (i, j)] = island_min mapping.append(['%s_%s' % (i, j)]) island += 1 elif island_top and island_left: island_set['%s_%s' % (i, j)] = island_min self.adjust_island(island_set, mapping, island_min, island_top, island_left, island_flipping) mapping[island_min].append('%s_%s' % (i, j)) elif island_top: island_set['%s_%s' % (i, j)] = island_min mapping[island_min].append('%s_%s' % (i, j)) else: island_set['%s_%s' % (i, j)] = island_min mapping[island_min].append('%s_%s' % (i, j)) island_flipping_set = set(island_flipping) for i in range(len(mapping)): if not i in island_flipping_set: for key in mapping[i]: arr_index = key.split('_') index_i, index_j = int(arr_index[0]), int(arr_index[1]) board_temp[index_i][index_j] = 'X' for i in range(len(board_temp)): line = board_temp[i] board[i] = ''.join(line) def adjust_island(self, island_set, mapping, island_min, island_top, island_left, island_flipping): if island_top != island_min: for key in mapping[island_top]: mapping[island_min].append(key) island_set[key] = island_min mapping[island_top] = [] if island_top in island_flipping: island_flipping.append(island_min) elif island_left != island_min: for key in mapping[island_left]: mapping[island_min].append(key) island_set[key] = island_min if island_left in island_flipping: island_flipping.append(island_min) mapping[island_left] = [] if __name__ == "__main__": solution = Solution() arr = ["XOXX","OXOX","XOXO","OXOX","XOXO","OXOX"] solution.solve(arr) print arr arr = ["OXOOOOOOO","OOOXOOOOX","OXOXOOOOX","OOOOXOOOO","XOOOOOOOX","XXOOXOXOX","OOOXOOOOO","OOOXOOOOO","OOOOOXXOO"] solution.solve(arr) print arr arr = ['XXX', 'XOX', 'XXX'] solution.solve(arr) print arr arr = ["XOXOXO","OXOXOX","XOXOXO","OXOXOX"] solution.solve(arr) print arr arr = ["XXXXX","XOOOX","XXOOX","XXXOX","XOXXX"] solution.solve(arr) print arr arr = ["OXOOXX","OXXXOX","XOOXOO","XOXXXX","OOXOXX","XXOOOO"] solution.solve(arr) print arr
98af31b797f940f1363a87fc228a360252ed753e
justega247/python-scripting-for-system-administrators
/bin/exercises/exercise-3.py
1,644
4.25
4
#!/usr/bin/env python3.7 # Building on top of the conditional exercise, write a script that will loop through a list of users where each item # is a user dictionary from the previous exercise printing out each user’s status on a separate line. Additionally, # print the line number at the beginning of each line, starting with line 1. Be sure to include a variety of user # configurations in the users list. # # User Keys: # # 'admin' - a boolean representing whether the user is an admin user. # 'active' - a boolean representing whether the user is currently active. # 'name' - a string that is the user’s name. # # Depending on the values of the user, print one of the following to the screen when you run the script. # # Print (ADMIN) followed by the user’s name if the user is an admin. # Print ACTIVE - followed by the user’s name if the user is active. # Print ACTIVE - (ADMIN) followed by the user’s name if the user is an admin and active. # Print the user’s name if neither active nor an admin. user_list = [ {'admin': True, 'active': True, 'name': 'Kevin'}, {'admin': False, 'active': True, 'name': 'Kingsley'}, {'admin': True, 'active': False, 'name': 'Kelechi'}, {'admin': False, 'active': False, 'name': 'Kess'} ] def user_status(user): prefix = "" if user['admin'] and user['active']: prefix = "ACTIVE - (ADMIN) " elif user['admin']: prefix = "(ADMIN) " elif user['active']: prefix = "ACTIVE - " return prefix + user['name'] for index, person in enumerate(user_list, start=1): print(f"{index} {user_status(person)}")
2867d0b759a5b916311ad504b07f330a1772714a
himanshuchelani/Python_course
/day1/bhubali2vsdangal.py
1,314
4.09375
4
""" Code Challenge: Simple Linear Regression Name: Box Office Collection Prediction Tool Filename: Bahubali2vsDangal.py Dataset: Bahubali2vsDangal.csv Problem Statement: It contains Data of Day wise collections of the movies Bahubali 2 and Dangal (in crores) for the first 9 days. Now, you have to write a python code to predict which movie would collect more on the 10th day. Hint: First Approach - Create two models, one for Bahubali and another for Dangal Second Approach - Create one model with two labels """ #METHOD 1 #Import Libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt #Load Datsets df=pd.read_csv("Bahubali2_vs_Dangal.csv") #Applying Model from sklearn.linear_model import LinearRegression features=df.iloc[:, :1].values labels1=df.iloc[:,1].values labels2=df.iloc[:,2].values regressor=LinearRegression() regressor.fit(features,labels1) x=np.array([10],ndmin=2) y=regressor.predict(x) regressor.fit(features,labels2) z=regressor.predict(x) if y>z: print("bhahubali2") else: print("dangal") #METHOD 2 label=df.iloc[:,1:] regressor.fit(features,label) result=regressor.predict(x) print(result) if result[0][0]>result[0][1]: print("bahubali2") else: print("dangal")
f8282da37f8add94c6f7c3d9029cfe030912bc7b
baishuai/leetcode
/algorithms/p138/138.py
1,327
3.90625
4
# package p138 # A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. # Return a deep copy of the list # Definition for singly-linked list with a random pointer. class RandomListNode(object): def __init__(self, x): self.label = x self.next = None self.random = None class Solution(object): def copyRandomList(self, head): """ :type head: RandomListNode :rtype: RandomListNode """ cnt = 0 cur = head while cur: cnt += 1 cur = cur.next lst = [RandomListNode(i) for i in range(0, cnt)] cur = head for i in range(0, cnt): lst[i].label = cur.label cur.label = i if i+1 < cnt: lst[i].next = lst[i+1] cur = cur.next cur = head for i in range(0, cnt): if cur.random is not None: lst[i].random = lst[cur.random.label] cur = cur.next cur = head for i in range(0, cnt): cur.label = lst[i].label cur = cur.next return None if cnt == 0 else lst[0] if __name__ == "__main__": solution = Solution() solution.copyRandomList(RandomListNode(-1))
9367598b75c333e2ac61f561483a5dc5f1510f1d
tylerkrupicka/practice
/ch2/28.py
691
4.03125
4
# Loop Detection # return the node at loop beginning of circular linked list from linked_list import * def detect_loop(l): r1 = l.head r2 = l.head first = True while(first or r1 != r2): first = False r1 = r1.next r2 = r2.next.next if r1 == None or r2 == None: return "Not a loop" #find Intersection r2 = l.head while(r1 != r2): r1 = r1.next r2 = r2.next return r1 if __name__ == '__main__': l1 = LinkedList() first = l1.append("first") l1.append("second") l1.append("third") l1.append("fourth") fifth = l1.append("fifth") fifth.next = first print(detect_loop(l1))
a0fc2bab6e7fd99b8686c01cf245e4812cbf56e4
JSNavas/CursoPython2.7
/Metodos de los Diccionarios/Metodo del() y clear().py
980
4.375
4
# encoding: utf-8 dic = {'nombre': "", 'apellido': ""} print dic['nombre'] = raw_input("Ingrese su nombre: ") dic['apellido'] = raw_input("Ingrese su apellido: ") print print dic['nombre'], dic['apellido'] print print "(1) Si desea eliminar su nombre." print "(2) Si desea eliminar su apellido. \n" n = input() if n == 1: print "\n[Al presionar ENTER se eliminara su nombre...] \n" raw_input() # Se usa la funcion "del" eliminar una clave # de un diccionario del (dic['nombre']) print "Se ha eliminado su nombre. \n" print dic['apellido'] if n == 2: print "\n[Al presionar ENTER se eliminara su apellido...] \n" raw_input() del (dic['apellido']) print "Se ha eliminado su apellido. \n" print dic['nombre'] # Para eliminar un diccionario (dejarlo vacio) se utiliza la funcion ".clear()" # se utiliza nombrando el diccionario que queremos eliminar antes de la funcion # "diccionario.clear()"
d397d4ceb5ab9ad3bf39f05c7b66f78efdadcf87
vianairan/JobDash-Assignment---Iranga-Samarasingha
/Assignment - Iranga Samarasingha/Part 2 - Word Cloud Script/word_clouds.py
2,840
4.21875
4
# -*- coding: utf-8 -*- """ Date: Jan 23rd, 2015 @author: Iranga Samarasingha Purpose: Assignment for JobDash Question: Write a stand alone Python script that creates word clouds.To do this, you'll first need to build the data. Write code that takes a long string and builds its word cloud data in a dictionary, where the keys are the words and the values are the number of times the words occured. """ # Import Libraries import string from pprint import pprint # Input text to test the script original_string = "Write a stand alone Python script that creates word clouds. To do this, you'll first need to build the data. Write code that takes a long string and builds its word cloud data in a dictionary, where the keys are the words and the values are the number of times the words occured."; def exclude_punctuation( input_str ): """ Purpose: Excludes all the punctuation marks conatained in a string and ... returns a new string without any punctuation marks. Input Args: input_str - String that needs to be processed (Type: String) Returns: output_str - String with out punctuation marks (Type: String) Usage: output_str = exclude_punctuation(input_str) """ output_str = ""; # Initialize string variable for output string for char in input_str: # Ite a = dictrate through each charactor of the string if char not in string.punctuation: # Add the charactor to the output if not included in the standard string of punctuations output_str = output_str + char return output_str # Returns the output string def count_words( input_list ): """ Purpose: Counts the number of occurances of each string in the input list and ... returns a dictionary with words and the frequency. Input Args: input_list - List of strings (Type: List) Returns: word_dict - Dictionary of words and frequency (Type: Dictionary) Usage: output_dict = count_words(input_list) """ word_dict = {}; # Initialize a dictionary (hashtable) to store the words and frequency for value in input_list: # Iterate through each word in the list if value not in word_dict: word_dict[value] = 1 else: word_dict[value] += 1 return word_dict # Returns the output dictionary print "START" print "-----" print "Original Input String : " print "....................." print "" print original_string print "" print "" new_string = exclude_punctuation(original_string) word_list = new_string.lower().split(); new_dict = count_words(word_list) print "Result : " print "......." print "" pprint(new_dict) print "" print "" print "END" print "---"
c15f7b0e33b8a26518310e14d2202e9230a65504
ynsong/Introduction-to-Computer-Science
/a05/a05q2.py
2,532
3.703125
4
##============================================================================== ## Yining Song (20675284) ## CS 116 Spring 2017 ## Assignment 05, Problem 2 ##============================================================================== import check ## list_stat(lst) produces a list containing exactly 5 natural numbers which calculates ## the number of different types of the elements in the consumed list lst in the order ## of integers, floats, booleans, strings and all of the other types ## ## list_stat: (listof Any) -> (list of Nat) ## Examples: ## list_stat([3, "wow", -3.967, True, True, False, "nice"]) => [1, 1, 3, 2, 0] ## list_stat(["good", [3,4], [10]]) => [0, 0, 0, 1, 2] ## list_stat([]) => [0, 0, 0, 0, 0] def list_stat(lst): ## list_stat_acc(lst,origin) produces a new list containing exactly 5 natural numbers ## by adding the number of different types of the elements in the consumed list lst ## and the each corrsponding number in the list origin ## list_stat_acc: (listof Any) (listof Nat) -> (listof Nat) def list_stat_acc(lst,origin): if lst == []: return origin elif type(lst[0]) == int: origin[0] = origin[0] + 1 return list_stat_acc(lst[1:],origin) elif type(lst[0]) == float: origin[1] = origin[1] + 1 return list_stat_acc(lst[1:],origin) elif type(lst[0]) == bool: origin[2] = origin[2] + 1 return list_stat_acc(lst[1:],origin) elif type(lst[0]) == str: origin[3] = origin[3] + 1 return list_stat_acc(lst[1:],origin) else: origin[4] = origin[4] + 1 return list_stat_acc(lst[1:],origin) ## Body of list_stat: return list_stat_acc(lst, [0, 0, 0, 0, 0]) ## Testing for list_stat(lst): check.expect("empty lst", list_stat([]), [0, 0, 0, 0, 0]) check.expect("lst only has ints", list_stat([1, 3, 43]), [3, 0, 0, 0, 0]) check.expect("lst only has floats", list_stat([1.324, 42.32]), [0, 2, 0, 0, 0]) check.expect("lst only has bools", list_stat([True, True, False]), [0, 0, 3, 0, 0]) check.expect("lst only has strs", list_stat(['1', 'as', 'sc']), [0, 0, 0, 3, 0]) check.expect("lst only has other types", list_stat([[12], ['as']]), [0, 0, 0, 0, 2]) check.expect("lst1", list_stat([3, "wow", -3.967, True, True, False, "nice"]), [1, 1, 3, 2, 0]) check.expect("lst2", list_stat(["good", [3,4], [10]]), [0, 0, 0, 1, 2])
2faf41a82ad05bdf0e42ea280eb88da6b43569fa
pallav12/numerical_techniques
/nt.py
1,999
3.640625
4
import sys import argparse global a global df def fx(n): return eval(a.replace('x',str(n))) def dfx(n): return eval(df.replace('x',str(n))) def solve(l,r,n): mid=(l+r)/2 print('lower limit {}, upper limit {}, iteration {}, fx(mid) {}'.format(l,r,n,fx(mid))) if(n==0): return fx(mid) if(fx(mid)<0): solve(mid,r,n-1) else: solve(l,mid,n-1) def inputEq(): global a print("Enter the equation in one variable (Eg 3*x^2-4*x+5)") a=input() a=a.replace('^','**') a=a.replace(' ','') def inputDfx(): global df print("Derivative of fx u just entered (Eg 6*x-4)") df=input() df=df.replace('^','**') df=df.replace(' ','') def newton_bisection(): inputEq() print("Enter lower and upper limits (Spaced real no, Eg 6 11)") l,r=map(int,input().split()) print('Enter number of iteration (Eg 20') n=int(input()) if(fx(l)*fx(r)<0): solve(l,r,n) else: print('Incorrect limits f(l)*f(r) should be <0 ') def _newton_method(n,guess): if(n==0): temp=guess-fx(guess)/dfx(guess) print('x{}= {} fx{} = {}'.format(n,temp,n,fx(temp))) return guess-fx(guess)/dfx(guess) nmm=_newton_method(n-1,guess) temp=nmm-fx(nmm)/dfx(nmm) print('x{}= {} fx{} = {}'.format(n,temp,n,fx(temp))) return nmm-fx(nmm)/dfx(nmm) def newton_method(): inputEq() inputDfx() print("Enter number of iteration") n=int(input()) print("Enter known x for which f(x)>0") guess=int(input()) _newton_method(n,guess) parser = argparse.ArgumentParser("numerical_techniques",formatter_class=argparse.RawTextHelpFormatter) parser.add_argument("-bis","--bisection_method", help="bisection", action='store_true') parser.add_argument("-nm", "--newton_method", help="Newton secant method", action='store_true') args = parser.parse_args() if(args.bisection_method): newton_bisection() exit() if(args.newton_method): newton_method() exit()
30304588c5dc46f32bd13a4617e16ac9b577425b
mskl/fit-bi-zns-homeworks
/ulohy/02/Graph/Node.py
2,799
3.53125
4
class Node: def __init__(self, id, name="Unnamed node"): """ Generate a new node. :param id: unique id :type id: int :param name: name of the node :type name: str """ self.edges_out = set() self.edges_in = set() self.height = 0 self.name = name self.__id = id def remove_edges_containing(self, node): """ Remove all edges on this node that contain the node from the parameter. :param node: the node that needs to be removed :type node: Node """ # remove incoming to_remove_in = [] for e in self.edges_in: if e.contains(node): to_remove_in.append(e) for d in to_remove_in: self.edges_in.remove(d) # remove outgoing to_remove_out = [] for e in self.edges_out: if e.contains(node): to_remove_out.append(e) for d in to_remove_out: self.edges_out.remove(d) def calculate_height(self): """ Recursively calculate the maximum distance to any leaf. :return: height value :rtype: int """ for e in self.edges_out: n = e.other(self) self.height = max(n.calculate_height(), self.height) return self.height + 1 def get_solution(self): """ Recursively find any (only) leaf. :rtype: Node :return: any leaf """ if len(self.edges_out) > 1 or len(self.edges_in) > 1: return None for e in self.edges_out: return e.other(self).get_solution() return self def __id__(self): """ Unique id of the Node used for hashing :rtype: str """ return "id=" + str(self.__id) + " name=\"" + str(self.name) def get_id(self): """ Get the unique id assigned when creating. :return: unique creation id :rtype: int """ return self.__id def __str__(self): """ String representation of the node. :return: string representation of the node. """ return self.__id__() + "\" e_in=" + str(len(self.edges_in)) + " e_out=" + str(len(self.edges_out)) def __eq__(self, other): """ Check if 2 node are equal by comparing their hashes. :param other: other node :type other: Node :rtype: bool """ if other is None: return False elif hash(self) == hash(other): return True return False def __hash__(self): """ Unique hash generated from the id string. :return: unique hash """ return hash(self.__id__())