blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
a71a6603ee40fd07bcf73d2ccb802e29cb6ecb77
julianascimentosantos/cursoemvideo-python3
/Desafios/Desafio080.py
462
3.984375
4
valores = list() for p in range(0, 5): n = int(input('Digite um valor: ')) if p == 0 or n >= valores[-1]: valores.append(n) print(f'Valor adicionado ao final da lista.') else: p = 0 while p < len(valores): if n <= valores[p]: valores.insert(p, n) print(f'Adicionado na {p} posição.') break p += 1 print(f'Os valores digitados foram: {valores}')
32902b17fb804bbebf87af86029ac1b43abf5931
zosiadom96/pw_pwzn_z2019
/lab_3/tasks/task_2.py
1,313
4.125
4
def check_frequency(input): """ Perform counting based on input queries and return queries result. Na wejściu otrzymujemy parę liczb całkowitych - operacja, wartość. Możliwe operacje: 1, x: zlicz x 2, x: usuń jedno zliczenie x jeżeli występuje w zbiorze danych 3, x: wypisz liczbę zliczeń x (0 jeżeli nei występuje) Do parsowania wejścia wykorzystaj funkcję parse_input. Po wejściu (już jakoliście) iterujemy tylko raz (jedna pętla). Zbiór danych zrealizuj za pomocą struktury z collections. :param input: pairs of int: command, value :type input: string :return: list of integers with results of operation 3 :rtype: list """ # hint collections, jedna pętla from collections import Counter from task_1 import parse_input commands = parse_input(input) numbers = Counter() frequency = [] for command, value in commands: if command == 1: numbers[value] += 1 elif command == 2: n = numbers[value] numbers[value] = n-1 if n > 0 else 0 elif command == 3: frequency.append(numbers[value]) return frequency _input = """ 1 5 1 6 2 1 3 2 1 10 1 10 1 6 2 5 3 2 """ if __name__ == '__main__': assert check_frequency(_input) == [0, 1]
2099fc18471834592e4c19c64622901573a4a835
parveen99/infytqpy
/list_adjacent_pos_count.py
336
3.765625
4
#PF-Exer-18 def get_count(num_list): count=0 for i in range(0,len(num_list)-1): if(num_list[i]==num_list[i+1]): count=count+1 # Write your logic here return count #provide different values in list and test your program num_list=[1,1,5,100,-20,-20,6,0,0] print(get_count(num_list))
4b84a9df539fa6b5250a834f5292a626b92441f4
overmesgit/hhtask
/square_solution.py
4,232
3.90625
4
"""Solution for First Test Task of HeadHunter's School Python3.4 author: Артем Безукладичный mail: overmes@gmail.com """ import argparse parser = argparse.ArgumentParser(description='Division in different number systems') parser.add_argument('file', metavar='F', type=open, help='file') args = parser.parse_args() class Square: """Square representation """ def __init__(self, xa, ya, xb, yb): """ :param xa: left bottom x :param ya: left bottom y :param xb: right top x :param yb: right top y """ if xa > xb: raise ValueError("xa > xb") if ya > yb: raise ValueError("ya > yb") self.xa = xa self.ya = ya self.xb = xb self.yb = yb def check_other(self, other): if not isinstance(other, Square): raise ValueError('Wrong input') def split_without_intersect(self, other): """Return squares from other which not intersect with self it not intersection return None """ self.check_other(other) if self.has_intersect(other): left_part = self._get_left_part(other) right_part = self._get_right_part(other) top_part = self._get_top_part(other) bottom_part = self._get_bottom_part(other) result = [part for part in (left_part, right_part, top_part, bottom_part) if part] else: result = None return result def _get_left_part(self, other): if self.xa < other.xa: left_part = Square(self.xa, self.ya, other.xa, self.yb) if not left_part.empty(): return left_part else: return None def _get_right_part(self, other): if self.xb > other.xb: right_part = Square(other.xb, self.ya, self.xb, self.yb) if not right_part.empty(): return right_part else: return None def _get_bottom_part(self, other): if self.ya < other.ya: return Square(max(self.xa, other.xa), self.ya, min(self.xb, other.xb), other.ya) else: return None def _get_top_part(self, other): if self.yb > other.yb: return Square(max(self.xa, other.xa), other.yb, min(self.xb, other.xb), self.yb) else: return None def has_intersect(self, other): self.check_other(other) return self.xb > other.xa and other.xb > self.xa and self.ya < other.yb and self.yb > other.ya def empty(self): return self.xa == self.xb or self.ya == self.yb def __str__(self): return '({}, {}) ({}, {})'.format(self.xa, self.ya, self.xb, self.yb) def get_square(self): return (self.xb - self.xa)*(self.yb - self.ya) class NotIntersectSquares: """Represent massive of Squares which not intersect """ def __init__(self): self.squares = [] def split_with_first_squares_with_intersect(self, insert_square): """If inserted square intersect with self.squares return not intersection parts else return None """ for square in self.squares: split_result = insert_square.split_without_intersect(square) if split_result is not None: return split_result def insert_squares(self, squares): """Insert squares list, remove intersect part if need """ squares_for_insert = squares.copy() while squares_for_insert: current_square = squares_for_insert.pop() split_result = self.split_with_first_squares_with_intersect(current_square) if split_result is None: self.squares.append(current_square) else: squares_for_insert.extend(split_result) def get_square_sum(self): square_sum = 0 for s in self.squares: square_sum += s.get_square() return square_sum squares_from_file = [] for row in args.file: squares_from_file.append(Square(*[int(n) for n in row.split()])) not_inserted_squares = NotIntersectSquares() not_inserted_squares.insert_squares(squares_from_file) print(not_inserted_squares.get_square_sum())
477537fecd9ace527877e344f202280ea705d384
mardommah/from-linux
/python/project/konversi_suhu_fahrenheit_ke_celcius.py
366
3.9375
4
import math #Program konversi suhu dari fahrenheit ke celcius #Masukkan nilai celcius F = int(input('Masukkan Suhu Dalam Fahrenheit: ')) if F < 32 or F > 212: print('Masukkan suhu dengan benar') else: C = 5 * (F - 32) / 9 #fungsi round adalah untuk membulatkan angka beberapa di belakang koma print(f'Suhu dalam Celcius adalah: {round(C,3)}')
1597646f29250908099ddeb9623abb0dd86f199f
TheWrL0ck/T-T-Lab
/LAB 5/prog7.py
199
3.859375
4
texts = ["php", "w3r", "Python", "abcd", "Java", "aaa"] result = list(filter(lambda x: (x == "".join(reversed(x))), texts)) print("Palindromes present in the given list are:",end=" ") print(result)
87eadc4fc0b5a7a130a36c6f534bb7092ffa34b8
microease/Python-Cookbook-Note
/Chapter_1/1.8.py
450
4.125
4
# 怎样在数据字典中执行一些计算操作(比如求最小值、最大值、排序等等)? price = { 'ACME': 45.23, 'AAPL': 612.78, 'IBM': 205.55, 'HPQ': 37.20, 'FB': 10.75 } min_price = min(zip(price.values(),price.keys())) test = zip(price.values(),price.keys()) print(test) print(min_price) max_price = max(zip(price.values(),price.keys())) print(max_price) price_sorted = sorted(zip(price.values(),price.keys()))
220cdf4cca2e86dfefe528f88eaa5b098c40d00b
sireesha98/laky
/laky.py
483
4.25
4
num1 = input() # take input from the user # num = int(input("Enter a number: ")) # prime numbers are greater than 1 if num1 > 1: # check for factors for i in range(2,num1): if (num1 % i) == 0: print(num1,"is not a prime number") print(i,"times",num1//i,"is",num1) break else: print(num1,"is a prime number") # if input number is less than # or equal to 1, it is not prime else: print(num1,"is not a prime number")
e5ac8bba4348249cf67b3be1d1fe1b2a16012131
wko27/advent_2019
/1.py
377
3.671875
4
import math def calculate_fuel(value): if value <= 0: return 0 fuel = math.floor(value / 3) - 2 if fuel < 0: return 0 return fuel + calculate_fuel(fuel) sum_fuel = 0 with open("input1.txt") as f: lines = f.readlines() for line in lines: mass = int(line.strip()) # breakpoint() fuel = calculate_fuel(mass) sum_fuel += fuel print(sum_fuel)
1f78107b2913112540e32f9d093a6e8ebcf19b5e
Tokyo113/leetcode_python
/暴力递归到动态规划/code_01_Hanoi.py
749
4.03125
4
#coding:utf-8 ''' @Time: 2019/11/15 11:43 @author: Tokyo @file: code_01_Hanoi.py @desc: ''' def Hanoi(n): process(n, "左", "右", "中") def process(i, start, end, other): if i == 1: print("move "+str(i)+' from '+start+' to '+end) return process(i-1, start, other, end) print("move "+str(i)+' from'+start+' to '+end) process(i-1, other, end, start) def hanoi(n): return process1(n,'左','中','右') def process1(n,from1,by,end): if n == 1: print('move'+str(n)+'from'+from1+'to'+end) return process1(n-1,from1,end,by) print('move'+str(n)+'from'+from1+'to'+end) process1(n-1,by,from1,end) if __name__ == '__main__': hanoi(3) print('===') Hanoi(3)
f6d82529b14f8206291f5b7dc62acb5ebfd4a6eb
otmoru/lesson02
/work05.py
295
3.875
4
my_list = [7, 5, 3, 3, 2] i = 0 print('Наш список ', my_list) while i < 10: new = int(input('введите новый элемент для списка: ')) my_list.append(new) print(my_list) my_list.sort() my_list.reverse() print(my_list) i += 1
b96f477b56ac5e0c3683cfc5c2a1634e3078a467
barua-anik/integrify_assignments
/Python exercises/factorial.py
201
4.34375
4
# Factorial operation using recursive function def factorial(n): if (n<=1): return n else: return n * factorial(n-1) print("The result is: ", factorial(int(input("Enter a number: "))))
707f2b86005dd29621ab5f87691c57e3fb5ff456
naveencloud/python-basic
/dec182017/ps_stringfmt2.py
986
4.375
4
"""demo for string formatting is for printing the rows and column {:fmt-str}""" name, age, gender = 'sarah', 3, 'female' # Variable Parallel assignment print("|{}|{}|{}|".format(name, age, gender)) # It will print output as directly print("|{:>22}|{:>9}|{:>20}|".format(name, age, gender)) # It will have the Column width size, output will alligned from right side in column print("|{:<22}|{:<9}|{:<20}|".format(name, age, gender)) # It will have the Column width size, output will alligned from Lift side in column print("|{:^22}|{:^9}|{:^20}|".format(name, age, gender)) # # It will have the Column width size, output will alligned from Center side in column print("|{:22}|{:9}|{:20}|".format(name, age, gender)) # # It will have the Column width size, output will alligned as per data type side in column print("|{:>22}|{:>9.2f}|{:20}|".format(name, age, gender)) ## It will have the Column width size, output will alligned from right side in column with "floating" in age column
9e64856d3426688bef12c689b7c497382b84869c
kafuuma/Fast-food-challenge2
/app/users.py
787
3.765625
4
from app.datastruct import DataStruct store = DataStruct() class Users: """This class handles creation and storing users in a Datastructure""" def __init__( self,full_name="", password="", email="", contact="" ,user_role="",user_id =0, ): self.full_name = full_name self.password = password self.email = email self.contact = contact self.user_role = user_role if len(store.users) >= 1: self.user_id = store.users[-1].user_id+1 else: self.user_id = 1 def save_user(self): """The mothode creates a user and appends to the Datastructure""" store.add_user(self) def login(self): pass def signup(self): pass
33e274fc73e9a00ab9fc7cff3e985c9e93d08bb0
themohal/Python
/Quarter 1/Python/Part3/function1.py
141
3.953125
4
def add(): num1=int(input("Enter first number:")) num2=int(input("Enter 2nd number:")) print(f"{num1}+{num2}={num1+num2}") add()
f3fa7544a130494d8a6f4401e9de3a00c9dfdf58
GLAU-TND/python-programming-assignment-2-Chetan-verma713
/assignment_1.py
213
3.640625
4
ls = ['chair', 'height', 'racket', 'touch', 'tunic'] ls1 = [] p = ls[0][-1] for j in ls: for i in ls: if p == i[0] and i not in ls1: ls1.append(i) p = i[-1] print(ls1)
a315dda805ce9b3472a32e76c9e2cb98df66cbe1
Vimlesh073/mynewrepository
/Python 24th Jan/ifEx.py
969
3.984375
4
n1 = 24 #check even no. #if condition if n1 % 2 == 0: print('even no.') #if else if n1 % 2 == 0: print(n1,' even no.') else: print(n1,' odd no.') #if elif elif ...... #print day name d = int(input('enter day no. ')) if d ==1: print('monday') elif d == 2: print('tuesday') elif d==3: print('wednesday') elif d == 4: print('thursday') elif d ==5: print('friday') else: print('weekend ') #nested if else : if inside if a = int(input('enter data ')) b = int(input('enter data ')) c = int(input('enter data ')) #print greater no. if a>b and a>c: print('a is gt') elif b>a and b>c: print('b is gt') else: print('c is gt') #### if a>b: if a>c: print('a is gt') else: print('c is gt') else: if b>c: print('b is gt') else: print('c is gt')
5b6205b3e8d4316a20047f86979d508598d5d37f
abhishekrodriguez/Additional-files-python
/Dictionaries.py
132
3.734375
4
# Dictionaries d1={"Hat": 35, "Toy": 50, "Vegies": 60} print (d1 ["Hat"]) d1["Mat"]="55" print(d1) del (d1["Mat"]) print(d1)
dc62a64a31c242866ce4bdf6ca011f37e0bf6401
marcelxyz/kmeans-pyspark
/src/helpers.py
680
4.0625
4
import time from datetime import datetime def datetime_to_timestamp(datetime_value): """ Converts a datetime string of the format 2017-12-15T14:01:10.123 to a unix timestamp. :param datetime_value: The datetime string to convert :return: Integer timestamp """ return time.mktime(datetime.strptime(datetime_value, '%Y-%m-%dT%H:%M:%S.%f').timetuple()) def is_valid_tuple(data, length): """ Returns true if the tuple has the expected length and does NOT contain None values. :param data: The tuple :param length: The expected length :return: True if valid, false otherwise """ return len(data) == length and None not in data
ee0633266ca2f71018db1d653d78f6a812a87798
TayExp/pythonDemo
/05DataStructure/51二叉树的list实现.py
519
3.65625
4
def BinTree(data,left=None,right=None): return [data,left,right] def is_empty_BinTree(btree): return btree is None def root(btree): return btree[0] def left(btree): return btree[1] def right(btree): return btree[2] def set_root(btree,data): btree[0] = data def set_left(btree,left): btree[1] = left def set_right(btree,right): btree[2] = right # list内部的嵌套层数等于树的高度 t1 = BinTree(2,BinTree(4),BinTree(8)) print(t1) set_left(left(t1),BinTree(5)) print(t1)
acd8aeec3229d02b25bcfb753509728e0a7ba596
Gokcekuler/Algoritma-Analizi
/maxsubsum_n_logn.py
989
3.53125
4
import time start= time.time() def max_of_two(a, b): if (a > b): return a else: return b def max_of_three(a, b, c): return max_of_two(a, max_of_two(b, c)) def my_f_3(a=[4, -3, 5, -2, -1, 2, 6, -2,4, -3, 5, -2, -1, 2, 6, -2]): n = len(a) if (n == 1 ) : return a[0] left_i = 0 left_j = n // 2 right_i = n // 2 right_j = n left_sum =my_f_3(a[left_i:left_j]) right_sum =my_f_3(a[right_i:right_j]) temp_left_sum = 0 t = 0 for i in range(left_j-1,left_i-1,-1): t = t + a[i] if(t > temp_left_sum): temp_left_sum = t temp_right_sum=0 t=0 for i in range(right_i,right_j): t = t + a[i] if(t > temp_right_sum): temp_right_sum = t center_sum = temp_left_sum + temp_right_sum return (max_of_three(left_sum, right_sum, center_sum)) print(my_f_3(a=[4, -3, 5, -2, -1, 2, 6, -2])) finish=time.time() sub=finish-start print(sub)
93dc3d7b314f6d6f423ed07db1e1151cd45706a8
6thfdwp/pygraph
/base.py
7,974
3.875
4
class Vertex: """ Vertex Class represents a vertex in graph """ #__slots__ = ['index', 'label', 'predecessor', 'status'] def __init__(self, label): """ Initialize vertex's attributes index -- Self incremental integer storing its index in the whole graph lable -- String name representing this vertex Temporary attributes used in graph traversal predecessor (Vertex) -- Vertex's predecessor dtime (int) -- Discovered time in dfs ftime (int) -- Finisheed time in dfs cost (float) -- Cost to reach this vertex in Dijkstra """ self.index = -1 self.label = label self.predecessor = None self.dtime = -1 self.ftime = -1 self.cost = float('inf') self.status = () def __getitem__(self, key): """ Protocal for dict style get Eg. vertex['index'] """ if key == 'index': return self.index elif key == 'label': return self.label elif key == 'predecessor': return self.predecessor elif key == 'dtime': return self.dtime elif key == 'ftime': return self.ftime def __setitem__(self, key, value): """ Protocol for dict style set Eg. vertex['index'] = index """ if key == 'index': self.index = value elif key == 'label': self.label = value elif key == 'predecessor': self.predecessor = value elif key == 'dtime': self.dtime= value elif key == 'ftime': self.ftime = value def __hash__(self): return hash(self.index) def __eq__(self, other): return self.index == other.index def __repr__(self): # return '%s_%s(%d)' % (self.__class__.__name__, self.label, self.index) return self.label def __str__(self): return '%s[%f]' % (self.label, self.cost) class Edge: def __init__(self, source, destination, weight=1.0): """ Initialize Edge attributes source (Vertex) -- The source vertex (one end) of the edge destination (Vertex) -- The destination vertex (the other end) of the edge weight (float) -- The weight of the edge, default is 1.0 in unweighted graph """ self.source = source self.destination = destination self.weight = weight def __getitem__(self, key): if key == 'source': return self.source elif key == 'dest': return self.destination elif key == 'weight': return self.weight elif key == 'type': return self.type def __setitem__(self, key, value): if key == 'weight': self.weight = value elif key == 'type': self.type = value def reverse(self): return Edge(self.destination, self.source, self.weight) def __str__(self): return '%s->%s [%d]' % (str(self.source), str(self.destination), self.weight) class GraphAdj: """ Graph class using adjacent representation It contains a list of vertices each of which has a list edges representing its connection with other vertices """ def __init__(self, conf=None): """ Initialize vertices (list) -- All the Vertex instances contained curIndex (int) -- Current iterating vertex's index in the graph """ self.vertices = [] self.curIndex = -1 if conf is not None: self.setup(conf) def setup(self, conf): """ Set up the graph with a conf file It has the following format: a b c d e # the label of each vertex 0 1 21 # an edge between vertex 0 (a) and 1 (b) with weight as 21 0 2 55 # an edge between vertex 0 (a) and 2 (c) with weight as 55 ... """ f = open(conf) for i, line in enumerate(f): items = line.split(' ') if i == 0: # the first line contains all vertex label, add them all # as graph ventry instances for item in items: self.addVertex(Vertex( item.strip() )) continue # from the second line representing connection sindex, dindex = items[0], items[1] try: weight = float(items[2]) except IndexError: # no weight specified weight = 1.0 self.addEdge(sindex, dindex, weight) def output(self): print "initial graph: \n", for u in self: for e in self.adjcent(u): print e class VEntry: """ Internal class representing a vertex and its edges """ def __init__(self, v): self.vert = v self.edges = [] # def __str__(self): # return str(self.vert) class EdgeIter: """ Internal class for iterator of a vertex's edges """ def __init__(self, v, graph): self.graph = graph self.edgesTo = graph.getVEntry(v).edges def __iter__(self): """ Make edges iterable using for .. in syntax """ return iter(self.edgesTo) def addVertex(self, v): v['index'] = self.size() self.vertices.append(GraphAdj.VEntry(v)) def addEdge(self, sindex, dindex, weight): """ Add an edge to link source to destination vertex Only create Edge instance in the base class, since for undirected and directed graph it has different ways to add the edge in both connected vertices @param sindex (int) -- The index of source vertex @param dindex (int) -- The index of destination vertex @param weight (float) -- The weight of the edge @return Edge instance """ sindex, dindex = int(sindex), int(dindex) try: source = self.getVertex(sindex) dest = self.getVertex(dindex) newedge = Edge(source, dest, weight) return newedge except IndexError: print "vertex indext error" def getVertex(self, index): try: result = self.vertices[index].vert except IndexError: result = None return result def getVEntry(self, v): return self.vertices[v['index']] def size(self): return len(self.vertices) def degree(self, v): """ The number of outgoing edges of the vertex @return int """ return len(self.getVEntry(v).edges) """ Protocol to make the graph iterable over its vertices list using for ... in syntax """ def next(self): self.curIndex += 1 try: #result = self.getVertex(self.curIndex) result = self.vertices[self.curIndex].vert except IndexError: self.curIndex = -1 raise StopIteration return result def __iter__(self): #vlist = [each.vert for each in self.vertices] #return iter(vlist) return self def adjcent(self, u): """ Visit the adjcent nodes of a vertex @return iterator to loop the edge list of a vertex """ return self.EdgeIter(u, self) def path(self, dest): pre = dest['predecessor'] if pre is None: return [dest] return self.path(pre) + [dest] if __name__ == '__main__': G = GraphAdj() for i in range(5): G.addVertex( Vertex('a'+str(i)) ) #for u in G: #print '...' #v1 = Vertex('a') #v2 = Vertex('b') #print v1['label'] #print v2['label'] #v2['label'] = 'c'
2fd11c95fc1328aabcb1d33f0060078db948b2d6
YevgenyY/Python_Course2
/week4/abstract_factory_pythonstyle.py
2,553
3.515625
4
class HeroFactory: @classmethod def create_hero(Class, name): return Class.Hero(name) @classmethod def create_weapon(Class): return Class.Weapon() @classmethod def create_spell(Class): return Class.Spell() class WarriorFactory(HeroFactory): class Hero: def __init__(self, name): self.name = name self.weapon = None self.spell = None def add_weapon(self, weapon): self.weapon = weapon def add_spell(self, spell): self.spell = spell def hit(self): print("WARRIOR {} hits with {}".format(self.name, self.weapon.hit())) def cast(self): print("WARRIOR {} casts {}".format(self.name, self.spell.cast())) class Spell(): def cast(self): return "Power" class Weapon: def hit(self): return "Claymore" class MageFactory(HeroFactory): class Hero: def __init__(self, name): self.name = name self.weapon = None self.spell = None def add_weapon(self, weapon): self.weapon = weapon def add_spell(self, spell): self.spell = spell def hit(self): print("Mage {} hits with {}".format(self.name, self.weapon.hit())) def cast(self): print("Mage {} casts {}".format(self.name, self.spell.cast())) class Weapon(): def hit(self): return "Staff" class Spell(): def cast(self): return "Fireball" class AssassinFactory(HeroFactory): class Hero: def __init__(self, name): self.name = name self.weapon = None self.spell = None def add_weapon(self, weapon): self.weapon = weapon def add_spell(self, spell): self.spell = spell def hit(self): print("Assassin {} hits with {}".format(self.name, self.weapon.hit())) def cast(self): print("Assassin {} casts {}".format(self.name, self.spell.cast())) class Weapon(): def hit(self): return "Dagger" class Spell(): def cast(self): return "Invisibility" def create_hero(factory): hero = factory.create_hero("Nagibator") weapon = factory.create_weapon() spell = factory.create_spell() hero.add_weapon(weapon) hero.add_spell(spell) return hero player = create_hero(AssassinFactory()) player.hit() player.cast()
e8482fb2c62e14d6b07ac2d44c35a55ff7509b6d
Coconuthack/python-rice
/Interactive Python - P1/wk1-more-modules.py
8,623
3.953125
4
# Moduleeees # - Modules are libraries of Python code that implement useful operations not included in basic Python. # - Modules can be accessed via the import statement. # - CodeSkulptor implements parts of the standard Python modules math and random. #-------------------------------------- # Math Module # The Math Module contains many useful functions and # constants used in mathematical expressions. To use the # Math Module, it must be imported first. import math # Here are some examples of the functions in the Math Module. # For explanations of what they do, please check the # documentation. Feel free to change these ones around # and try more of them from the module. print "Ex. 1:", math.ceil(.2), math.ceil(-1.4) print "Ex. 2:", math.floor(4.9999), math.floor(-3.2) # Note: math.pow() is the same as the '**' symbol print "Ex. 3:", math.pow(3, 4), 3 ** 4 print "Ex. 4:", math.fabs(-5), math.fabs(5) # returns absoltue value of float! print "Ex. 5:", math.sqrt(9), math.sqrt(2) # Note: all trig function parameters are in radians print "Ex. 6:", math.sin(0), math.sin(4.5) print "Ex. 7:", math.radians(180), math.degrees(3.1415926) print # The Math Module also contains important constants # Note: Because they are constants, they do not require ()'s print "Pi:", math.pi print "e:", math.e print "--------" # Here are some sample functions involving the Math Module # Pythagorean Theorem (finding the hypotenuse of a right triangle) def pythagorean(a, b): c = math.sqrt(math.pow(a, 2) + math.pow(b, 2)) return c print "Pythagorean Theorem:", pythagorean(3, 4) # Area of a circle def area_of_circle(radius): area = math.pi * math.pow(radius, 2) return area print "Area of Circle:", area_of_circle(3.4) # Radioactive decay (approximation) def radioactive_decay(initial_amount, half_life, time_elapsed): x = -0.693 * time_elapsed / half_life amount = initial_amount * math.exp(x) return amount print "Radioactive Decay:", radioactive_decay(100, 17.9, 10) #-------------------------------------- # More Operations # Random # The Random Module contains many useful functions for # generating random numbers. To use the Random Module, # it must be imported first. import random # Here are some examples of how to use the functions in the # Random Module. Run the program multiple times to see # what different random numbers you can get. Check the # documentation for explanations of how the functions work, # and for more functions # random.choice(list) # Returns a random value from the list or a random character # of a string print "Choice 1:", random.choice([1,2,7,18,92]) print "Choice 2:", random.choice(["a","b","yes","no"]) print "Choice 3:", random.choice("abcdefghijklmnopqrstuv") #alphabet # Only allows one parameter #print "Error:", random.choice("hi", "hello") # TypeError: choice() takes exactly 1 arguments (2 given) # Parameter must be a list #print "Error:", random.choice(4) # TypeError: seq must be a sequence print # random.randint(a, b) # Returns an int from a to b inclusive print "Randint 1:", random.randint(1,10) print "Randint 2:", random.randint(-5, 27) # Requires two parameters #print "Error:", random.randint(4) # TypeError: randint() takes exactly 2 arguments (1 given) # Parameters must be integers #print "Error:", random.randint(0, 4.5) # it's a floa yo # ValueError: non-integer stop for randrange() print # random.randrange([start], stop[, step]) # Note: parameters in brackets are optional # Returns an integer from start (inclusive) to stop (not # included), skipping numbers by step. If step is not # specified (only two parameters), it defaults to 1. If # start is also omitted (only one parameter), it defaults # to 0. # Returns odd numbers from [1,9) (1 being the first number # included in the range, and 9 being the first number # excluded in the range) print "Randrange 1:", random.randrange(1, 9, 2) # Returns multiples of 5 from 0 to 50 print "Randrange 2:", random.randrange(0, 51, 5) # Returns ints form [3,10) print "Randrange 3:", random.randrange(3, 10) # Returns positive ints less than 200, including 0 print "Randrange 4:", random.randrange(200) # Returns negative ints greater than -10, including 0 print "Randrange 5:", random.randrange(-10) # reversed yo # Requires 1, 2, or 3 parameters -> TypeErrors #print "Error:", random.randrange() #print "Error:", random.randrange(1, 2, 3, 4) # Parameters must be integers -> ValueErrors #print "Error:", random.randrange("hi", 4, 5) #print "Error:", random.randrange(2, 5, .5) # Stop must be greater than start if both are given #print "Error:", random.randrange(5, 3, 6) # Note: if only two arguments are specified, they are # automatically start and stop. It is impossible to specify # step without start as well, although start can be set to # zero to achieve the same effect. # Trying to count by 2 from 0 to 10, including 10 # Doesn't work #print "Randrange 6:", random.randrange(10, 2) # Doesn't work - only goes to 8 print "Randrange 6:", random.randrange(0, 10, 2) # Does work print "Randrange 7:", random.randrange(0, 12, 2) print # random.random() # Returns a random number between 0 and 1, including 0 print "Random 1:", random.random() print "Random 2:", random.random() print "Random 3:", random.random() print "--------" # It is possible to generate random decimal values by # performing mathematical operations on random integers # Random numbers from 0 to 5, excluding 5 x = random.randrange(0, 10) print "Ex. 1:", x / 2.0 #-> 1 decimal point! # Random angles in the first quadrant (0 - pi/2) import math #max: 1000/1000.0 -> 1.0 #min: 0/1000.0-> 0.0 x = random.randrange(0, 10001) #max: 10000/10000.0 -> 1.0 #values are 3 decimals: 9459/1000.0 -> 9.459 #min: 0/10000.0-> 0.0 x = (x / 10000.0) * (math.pi / 2) print "Ex. 2:", x print # Random angles between e and e ** 2 x = random.randrange(0, 10001) x = (x / 10000.0) * (math.e ** 2 - math.e) + math.e print "e:", math.e print "e ** 2:", math.e ** 2 print "Ex. 3:", x print # The general formula - play with the values to test it out # How many unique random values can be generated number_of_possibilities = 59 # First and last values start = 12 stop = 15 # If you want to include stop and start x = random.randrange(0, number_of_possibilities + 1) # If you don't want to include stop #x = random.randrange(0, number_of_possibilities) # If you don't want to include start #x = random.randrange(1, number_of_possibilities + 1) # If you don't want to include either one #x = random.randrange(1, number_of_possibilities) # Calculation x = (x / float(number_of_possibilities)) * (stop - start) + start print "Formula A:", x print # If you want to include start and not stop, you can also # use random.random() to get an unlimited number of # possibilities start = 100 stop = 144 x = random.random() x = x * (stop - start) + start print "Formula B:", x #---------------------------------- # More Operations # Errors # Misspelling the module names can cause an error. #import randm # Forgetting to import the correct module before using it # causes and error. #print math.pi # Importing the wrong one doesn't help import random #print math.pi import math print "Ex. 1:", math.pi print # Naming a variable or function the same name as a module can # also be problematic. print "Ex. 2:", random.randrange(5) random = 4 print "Ex. 3:", random # Random is no longer a module; it is now a variable. #print "Error:", random.randrange(5) print print "Ex. 3:", math.e def math(): return 4 print "Ex. 4:", math() #print "Error:", math.e # This can technically be fixed by re-importing the modules, # but that would be an example of absolutely atrocious # programming, so don't do it. It is only done here since # this program is supposed to give examples of errors # anyway. import math import random print "--------" # Misspelling the methods or constant calls of the modules # also causes an error. Remember that CodeSkulptor is case # sensitive, meaning that the issue could be an incorrectly # capitalized letter. random.randrange(2,4) #random.randomrange(2,4) #random.randRange(2, 4) math.sqrt(4) #math.squarert(4) math.pi #math.pie # Just like with regular functions, you must use the expected # parameters when calling module functions. #random.randint(9) #random.randrange("HELLO") # Note that while the following does not produce a program- # crashing error, it does produce a result called 'Not a # Number' which is not very helpful and cannot be used # the same way other numbers can. #print math.sqrt("4") #print math.sqrt("4") + 2 #print math.sqrt("i")
abeec7de2b7217064bd1190e59f316a27a7b6b7d
heysushil/python-practice-set
/numpy/iteration.py
1,856
4.0625
4
# numpy ''' npiter EXAMPLE: import numpy as np arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) # range(star,end,diff) # np.nditer(start:end, ::number postion) # if(2 <= 3) = IN nditer 1ST ARGUMENT 0 SHOWING STARING POINT AND 2 SHOWING N-1 SAME AS RANGE [0,2] = HERE 2 IS EXCULUDED FROM RANGE # ::2 NOT DIFFRENCE IT'S ARRAY VALUE POSTION LIKE AS [1,2,3,4,5]. RESULT 1,3,5 for x in np.nditer(arr[0:2, ::2]): print(x) Iterating SUBMETHODS: nditer() = NORAMAL ITERATE SAME LIKE NESTED FOR LOOP op_dtypes() = IT CHANGE THE DATA TYPE OF ARRAY TO OTHER. LIKE op_dtypes('S') => array => stirng ndenumerate() = GIVES INDEX AND VALUE BOTH JOINING: concatenate() - USE SUB METHOD concatenate() LIKE concatenate((ARR1,ARR2), axis=1) MATRIX: stack() - - EXAMPLE = stack(arr1,arr2): SHOW NORAML MATRIX SIDE BY SIDE - EXAMPLE = stack((arr1,arr2), axis=1): CONCATENATE ARR1 AND ARR2 WITH USE OF AXIS=1 EXAMPLE: 1ST MARTIX = [1 2 3] = [00 01 02] (2*3) = (3*2) 2ND MARTIX = [4 5 6] [10 11 12] (2*3) = (3*2) OUTPUT: [1 4] [2 5] [3 6] hstack() - horizontal line or FOR ROW - np.hstack((arr1, arr2)) vstack() - vertical line or FOR COLUMN - np.vstack((arr1, arr2)) dstack() - DIRECT CONCATENATE 2 MATRIXES NO NEED OF AXIS - EXAMPLE: arr = np.dstack((arr1, arr2)) SPLIT: array_split(): EXAMPLE: newarr = np.array_split(arr, 3) : SPLIT 3 ARRAYS OF 2'S EACH newarr = np.array_split(arr, 3, axix=1): CONCATENATE ARRYS newarr = np.hsplit(arr, 3): DIRECT CONCATENATE ARRAYS OUTPUT: [1 4 7 10 13 16] [2 5 8 11 14 17] [3 6 9 12 15 18] '''
0699321f82fc31d0c7e546f9664828c2488e0345
gwy15/leetcode
/src/463.岛屿的周长.py
1,953
3.59375
4
# # @lc app=leetcode.cn id=463 lang=python3 # # [463] 岛屿的周长 # from typing import List from utils import * # @lc code=start class Solution: def islandPerimeter(self, grid: List[List[int]]) -> int: m = len(grid) if m == 0: return 0 n = len(grid[0]) # find the first land si, sj = -1, -1 for i in range(m): for j in range(n): if grid[i][j] == 1: si, sj = i, j break if (si, sj) != (-1, -1): break perimeter = 0 visited = [ [False for _ in range(n)] for __ in range(m) ] def dfs(x, y): nonlocal perimeter # (x,y) is not visited assert grid[x][y] visited[x][y] = True # check neighbors neighbors = [ (x-1, y), (x+1, y), (x, y-1), (x, y+1) ] for nx, ny in neighbors: if 0 <= nx < m and 0 <= ny < n: # neighbor is water if grid[nx][ny] == 0: perimeter += 1 continue # unvisited land elif not visited[nx][ny]: dfs(nx, ny) else: # out of border perimeter += 1 # start at (i,j) dfs(si, sj) return perimeter # @lc code=end if __name__ == '__main__': def test(input, expected): calc = Solution().islandPerimeter(input) if calc != expected: print(f'case failed: `{input}`') print(f' calc = `{calc}`') print(f' expected = `{expected}`') exit(1) test( [[0, 1, 0, 0], [1, 1, 1, 0], [0, 1, 0, 0], [1, 1, 0, 0]], 16 )
3c378233462324a64ec7dc929ed144d037a00d03
Hui-Yao/program_yao
/python_note/01_学习总结/01_常见数据类型及其方法/03_元组方法.py
679
3.90625
4
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Author = Hui_Yao '''元组的增删改查: 创建:在创建一个元祖时,逗号比空格重要 删:只能直接删除整个元组,不能删除内部元素;元组内陆嵌套了可变对象另当别论 查:索引,分片 ''' print(type((123)),type((123,))) #未加逗号是int,加了逗号是tuple print('元组方法'.center(50,'*')) tiger = (123,'tiger','run') xi1 = tiger.count(123) #1.count(value)——统计元组中value的个数 print(xi1) tiger.index('tiger') #2.index(value[,start[.end]])——从左边开始寻找,返回第一个value项的index;可以指定搜索范围
e64e989e24706073deeb9ace266f98d83b72a91b
kristogj/alg_dat
/leetcode/self_dividing_numbers.py
555
3.53125
4
class Solution(object): def selfDividingNumbers(self, left, right): """ :type left: int :type right: int :rtype: List[int] """ res = [] for x in range(left, right + 1): if self.check(x): res.append(x) return res def check(self, x): s = set(str(x)) if "0" in s: return False for num in s: if x % int(num) != 0: return False return True print(Solution().selfDividingNumbers(47,85))
03c6eea9a943340e7e3b95a8b85e8f31b29e5484
LoicGrobol/python-im
/exos/chifoumi.py
1,750
3.953125
4
# -*- coding: utf-8 -*- # chifoumi tout nul fait en cours de Python import random def draw(coups): """ Coup aléatoire au chifoumi pas d'arguments """ coup = coups[random.randint(0,2)] return coup def rules(player_1, player_2): """ implémentation naïve des règles du chifoumi args: player_1 (str), player_2 (str) return: 0 if equality, 1 if player_1 wins, 2 if player_2 wins """ if player_1 == player_2: return 0 else: if player_1 == "pierre": if player_2 == "ciseaux": return 1 else: return 2 elif player_1 == "feuille": if player_2 == "pierre": return 1 else: return 2 else: if player_1 == "feuille": return 1 else: return 2 coups = ["pierre", "feuille", "ciseaux"] emojis = {'pierre': "\u270A", 'feuille': "\u270B", 'ciseaux': "\u270C"} result = ['égalité', 'victoire', 'défaite'] final_result = {'égalité': 0, 'jeckel': 0, 'heckel': 0} for i in range(3): print("tour {}".format(i + 1)) heckel = draw(coups) jeckel = input("Vous êtes Jeckel.\nÀ vous de jouer [pierre, feuille, ciseaux] : ") if not(jeckel in coups): raise ValueError("Tricheur !") winner = rules(jeckel, heckel) print("Heckel : {} {}, Jeckel : {} {}, {}".format(heckel, emojis[heckel], jeckel, emojis[jeckel], result[winner])) if winner == 0: final_result["égalité"] += 1 elif winner == 1: final_result["jeckel"] += 1 else: final_result["heckel"] += 1 print("Victoire finale de {}".format(max(final_result, key=final_result.get)))
367ca331e3b8ca2a6ea68491d62a4fda15ed1dc0
kenzielizg/Cypher
/PythonApplication1.py
23,834
4.125
4
#Im too lazy to do full comments now from math import floor from math import ceil #Called in sumHandleFloat, pascalString, pascalCypher, fibonacciString, fibonacciCypher, wordLengthCypher def isAlphaNum(char, cyphNums=True): """ Checks if character is letter or number, returns bool char: single character cyphNums: if true, numbers return true, otherwise false """ #Equivalent string method str.isalnum() if (char >= 'A' and char <= 'Z') or (char >= 'a' and char <='z') or (cyphNums and char >= '0' and char <= '9'): return True return False def filterString(text, incNums=True): """ filters out spaces, punctuation, and optionally number from string as well as capitalizing. text: string incNums: bool, True includes number in result returns filtered string """ #Requires: isAlphaNum newString='' #iterate through string for char in text: if isAlphaNum(char, incNums): #appending next char, newString = newString + char.upper() return newString def shift(char, factor): """ Takes a character and its shift factor. character will not be shifted outside of its given set: uppercase letters, lowerecase letters, or 0-9. it will cycle. char: single alphanumeric to be shifted, not meant for other symbols factor: signle char or int used to shift char. char examples: 'a' =1, 'A' = 1, '3'= 3 int factors are not transformed. returns shifted character """ #Convert to Unicode char = ord(char) #Checking if factor is valid string if ( type(factor)==str and len(factor)==1 ): #to unicode factor = ord(factor) #unicode to correct value, 'a' = 1 instead of 97 if(factor >= 48 and factor <= 57): factor = factor - 48 elif(factor >= 65 and factor <=90): factor = factor - 64 else: factor = factor -96 #applying shift and cycling if needed if (char >= 48 and char <= 57): char = char + factor while char < 48: char = char + 10 while char > 57: char = char - 10 return chr(char) elif (char >= 65 and char <= 90): char = char + factor while char < 65: char = char + 26 while char > 90: char = char - 26 return chr(char) else: char = char + factor while char < 97: char = char + 26 while char > 122: char = char - 26 return chr(char) def caesar(text, factor, cyphNums=True, standardFormat=True, incNums=True): """ Simple Caesar cypher, all text shifted by the same value text: string to be encrypted factor: number to shift text by cyphNums: determines if the numbers are also shifted standardFormat: all caps, not spaces or punctuation, false keeps capitalization, spacing, and punctuation incNums: wether numbers are included or removed in standard format returns encrypted text """ #Requires: filterString, isAlphaNum #Can be treated as special case of vigenere if standardFormat: text = filterString(text, incNums) cypherText = '' for char in text: if isAlphaNum(char, cyphNums): cypherText = cypherText + shift(char, factor) else: cypherText = cypherText + char return cypherText def vigenere(text, keyword, cyphNums=True, standardFormat=True, incNums=True, revKey=False, revText=False): """ Encrypts text by using an overlayed keyword to determine each chatacter's shift text: string to be encrypted keyword: world that will be used to encrypt cyphNums: whether or not numbers get shifted standardFormat: whether all caps, not spaces, no punctuation format it used incNums: Whether numbers get taken out of text returns encrypted text pairs (revKey,revText): (0,0): normal vigener, full word applied at beginning (1,0): keyword applied backwards (1,1): keyword applied with full word applied at end (identical to 0,0 if text length is evenly divisible by keyword) (0,1): keyword applied backwards with full word applied to end """ #Requires: filterString, isAlphaNum, shift if standardFormat: text = filterString(text, incNums) if revKey: keyword = keyword[::-1] if revText: text = text[::-1] keylength = len(keyword) cypherText = '' n = 0 for char in text: if isAlphaNum(char, cyphNums): #get and shift by correct letter of keyword cypherText = cypherText + shift(char, keyword[n % keylength] ) #incrementing index n = n + 1 else: cypherText = cypherText + char if revText: cypherText = cypherText[::-1] return cypherText def keyAlphabet(generator, original= 'abcdefghijklmnopqrstuvwxyz'): """ Generates a keyalphabet using a given word. Fallout76's method. removes letter in given word from alphabet then appending said alphabet to given word generator: the word used to make the keyalphabet. A word with repeat letters will shrink the set space making decryption more difficult to impossible. original: defaults to the alphabet; however maybe changed to anything to include other characters. returns the new alphabet """ if len(generator) > len(original): generator = generator[:len(original)] #idk if i actually need this part ^^^ #Im pretty sure I dont but I dont feel like testing it #loop goes through letters in generator and removes from alphabet for char in generator: #str.index(substr) gives error if substring not found. try except handles it try: i = original.index(char) #replace with .find(char)? except: #continue to next iteration of loop continue #if index found in original, use it to split into two substrings and # combine wihtout the letter # also pretty sure there a string method for this # str.replace(old, new) original = original[:i] + original[i+1:] return generator + original def alphaToKey(char, keyAlpha, basicAlpha): """ Uses keyalphabet and basicAlphabet (original) to encrypt the char. Goes from basic to key char: single char to be changed keyAlpha: new letters basicAlpha: old letters returns new char """ #find the location of char in normal alphabet and gets char at that index # in the key alphabet return keyAlpha[basicAlpha.index(char)] def oneToOneAlpha(text, generator, standardFormat=True, incNums=True, basicAlpha = 'abcdefghijklmnopqrstuvwxyz'): """ Encrypted form one alphabet to another text: string to be encrypted Generator: creates the key alphabet to code into, fo76 method standardFormat: whether all caps, not spaces, no punctuation format it used incNums: Whether numbers get taken out of text basicAlpha: original alphabet returns encrypted text """ #Requires: filterString, keyAlphabet, alphaToKey if standardFormat: text = filterString(text, incNums) keyAlpha = keyAlphabet(generator, basicAlpha) cypherText = '' for char in text: #cap to keep track is char was uppercase cap = False #if uppercase cap set true and char put in lowercase if char <= 'Z' and char >= 'A': cap = True char = char.lower() #if checks if char was in the original alphabet, but its saved as lowercase # so any caps are put into lowercase, so a bunch of extra stuff if char in basicAlpha: newChar = alphaToKey(char, keyAlpha, basicAlpha) #tertiary operator in python #if cap is true newChar set to uppercase vertion, lowercase otherwise newChar = newChar.upper() if cap else newChar cypherText = cypherText + newChar else: #tertiary for same thing char = char.upper() if cap else char cypherText = cypherText + char return cypherText def fibonacciString(root, length, floatHandling=0): """ Makes a fibonacci sequence from the root number, and then turns it into a string. root: maybe be int or float floatHandling: determines how floats are delt with when added to string 0: decimal part dropped 1: unchanged 2: floor 3: round 4: ceil returns fibonacci string """ #Requires: sumHandleFloat, filterString penultNum = root ultNum = root #adding first two digits of sequence with floatHandling, we want first element of its output fibString = str( sumHandleFloat(penultNum,0,floatHandling)[0] ) + str( sumHandleFloat(0,ultNum,floatHandling)[0] ) #while loop to make sure the fibonacci sequence is long enough while len(filterString(fibString)) < length: #for loop does so while conditional function get called 10x less # does that help? idk but I felt rude for n in range(10): #next number is found by adding previous two #nextNumList is a list of length two, the first elemetn is to be used in the string # the second element is for calculations nextNumList = sumHandleFloat(penultNum, ultNum, floatHandling) #the second to last number is set to the last number penultNum = ultNum #the last number is get to element 0 ultNum = nextNumList[1] #new number is added to string fibString = fibString + str(nextNumList[0]) #continues going forward in list return filterString(fibString) def sumHandleFloat(penultNum, ultNum, floatHandling=0): """ Adds two numbers and uses chosen method to deal with floats penultNum: number to be added ultNum: number to be added floatHandling: determines how floats are delt with when added to string 0: decimal part dropped 1: unchanged 2: floor 3: round 4: ceil returns list [0]: handled sum, [1]: unchanged sum """ #Requires: math.floor, math.ceil nextNum = penultNum + ultNum #used to handle rounding issues from base conversion, for round in return statement #Converts number string, reverses string, finds index of decimal point, which is equal # to number of digits maxDecimals = str(penultNum)[::-1].find('.') nextNumDecimals = str(ultNum)[::-1].find('.') #tertiary operator to make sure the highest number of decimals is saved maxDecimals = maxDecimals if maxDecimals > nextNumDecimals else nextNumDecimals #if the number was no decimals then '.' won't be found and return -1 # we need it to be 0 instead if maxDecimals == -1: maxDecimals = 0 #python ghetto switch statement actually a dictionary switch = { 1: nextNum, 2: floor(nextNum), 3: round(nextNum), 4: ceil(nextNum) } #return list, first is meant to be used in string and has the floatHandling applied, the other # is the mathematically accurate result for calculating new values return [round( switch.get(floatHandling, int(nextNum)), maxDecimals ), round(nextNum, maxDecimals)] def fibonacciCypher(text, root, floatHandling=0, pattern=1, inversePattern=False, cyphNums=True, standardFormat=True, incNums=True): """ Encrypts text using fibonacci-like series a key text: string to be encrypted root: number used to generate fibonacci sequence string floatHandling: determines how floats are delt with when added to string 0: decimal part dropped 1: unchanged 2: floor 3: round 4: ceil pattern: creates a pattern for positive or negative shift using mod. example with 0 representing positive and 1 representing negative: pattern 1: 0000000000 pattarn 2: 0101010101 pattern 3: 0110110110 inversePattern: flips the sights given by pattern cyphNums: whether or not numbers get shifted standardFormat: whether all caps, not spaces, no punctuation format it used incNums: Whether numbers get taken out of text returns encrypted text """ #Requires: filterString, fibonacciString, seriesCypher if standardFormat: text = filterString(text, incNums) length = len(text) fibString = fibonacciString(root, length, floatHandling) cyphText = seriesCypher(text, fibString, floatHandling, pattern, inversePattern, cyphNums, standardFormat, incNums) return cyphText def seriesCypher(text, series, floatHandling=0, pattern=1, inversePattern=False, cyphNums=True, standardFormat=True, incNums=True, pattern2=1, pattern3=1): """ Encrypts text using any series of numbers as a key, treats each digit as the shift value text: string to be encrypted series: a string of numbers, equal to or longer than the text floatHandling: determines how floats are delt with when added to string 0: decimal part dropped 1: unchanged 2: floor 3: round 4: ceil pattern: creates a pattern for positive or negative shift using mod. example with 0 representing positive and 1 representing negative: pattern 1: 0000000000 pattarn 2: 0101010101 pattern 3: 0110110110 inversePattern: flips the sights given by pattern cyphNums: whether or not numbers get shifted standardFormat: whether all caps, not spaces, no punctuation format it used incNums: Whether numbers get taken out of text returns encrypted text """ #Requires: filterString, isAlpha if standardFormat: text = filterString(text, incNums) cyphText = '' index=0 for char in text: #only shift alphanumeric if isAlphaNum(char, cyphNums): #gets shift value and applied pattern using % operator pattBool = index%pattern==0 or (pattern2!=1 and index%pattern2==0) or (pattern3!=1 and index%pattern3==0) value = int(series[index]) if pattBool else -int(series[index]) #if inversePattern is true this will inverse values if inversePattern: value = -value char = shift(char, value) #incrementing index = index + 1 cyphText = cyphText + char return cyphText def pascalString(root, length, floatHandling=0): """ Creates a string of numbers based on the pascal triangle using the root number root: a number to generate all numbers length: length the string must be at least equal to floatHandling: determines how floats are delt with when added to string 0: decimal part dropped 1: unchanged 2: floor 3: round 4: ceil returns series string """ #Requires: sumHandleFloat, filterString #get number decimals rootLength = str(root)[::-1].find('.') if rootLength == -1: rootLength = 0 currLine = [root, root] nextLine = [] #pascal's will always start with the root repeated three times #this starts the string with the root floathandled and repreated three times pascString = str( sumHandleFloat(root,0,floatHandling)[0] )*3 #This entire loop could definitely be written better while len( filterString(pascString) ) < length: #for cuz I felt rude making the while do everything ¯\_(ツ)_/¯ for n in range(5): #index to go through each line index=1 #nextline will always begin with root nextLine = nextLine + [ root ] #get length of current line lenCurrLine = len(currLine) #loop through line while index < lenCurrLine: #add numbers to get numbers for next line sum = round(currLine[index-1] + currLine[index] ,rootLength ) #add it to next line nextLine = nextLine + [ sum ] #increment index = index + 1 #nextline will always end in root nextLine = nextLine + [ root ] #next become current currLine = nextLine #loop to add new values to string and apply floathandling for val in currLine: val = sumHandleFloat(val,0,floatHandling)[0] pascString = pascString + str(val) #reset nextline nextLine = [] #filter the string to get rid of decimals pascString = filterString(pascString) return pascString def pascalCypher(text, root, floatHandling=0, pattern=1, inversePattern=False, cyphNums=True, standardFormat=True, incNums=True): """ Encrypts text using pascal-like series a key text: string to be encrypted root: number used to generate pascal sequence string floatHandling: determines how floats are delt with when added to string 0: decimal part dropped 1: unchanged 2: floor 3: round 4: ceil pattern: creates a pattern for positive or negative shift using mod. example with 0 representing positive and 1 representing negative: pattern 1: 0000000000 pattarn 2: 0101010101 pattern 3: 0110110110 inversePattern: flips the sights given by pattern cyphNums: whether or not numbers get shifted standardFormat: whether all caps, not spaces, no punctuation format it used incNums: Whether numbers get taken out of text returns encrypted text """ #Requires: filterString, pascalString, seriesCypher if standardFormat: text = filterString(text, incNums) pascString = pascalString(root, len(text), floatHandling) cypherText = seriesCypher(text, pascString, floatHandling, pattern, inversePattern, cyphNums, standardFormat, incNums) return cypherText def filterStringSpaced(text, incNums=True, toUpper=True): """ Used to filter a string but keeps spaces text: string to be filtered incNums: whether number stay or are filtered, False filters numbers toUpper: whether or not string is put into uppercase returns filted string """ #Requires: isAlphaNum newString='' #like the other one but with spaces too, and also choice of uppercase for char in text: if isAlphaNum(char, incNums) or char == ' ': if toUpper: char = char.upper() newString = newString + char return newString def findSpaces(text, filterPunc=True, incNums=True): """ find the indices of the spaces in a string and returns a list of them, the last element of the list is the length of the string text: string to be searched filterPunc: will look at text as if no punctuaion incNums: whether of not numbers are included """ #Requires: filterStringSpaced if filterPunc: text = filterStringSpaced(text, incNums, toUpper=True) spaceIndices = [] index = -1 #pseudo do-while cuz python doesn't have one while True: #finds the index of space and loops to find next index = text.find(' ', index+1) #when one cannot be found, str.find() returns -1 so the loop breaks if index == -1: break spaceIndices = spaceIndices + [index] #length text added as last element for reasons spaceIndices = spaceIndices + [len(text)] return spaceIndices def wordLengths(text, filterPunc=True, incNums=True): """ Determines the length of all words in a string text: string filterPunc: whether or not punctuation is counted toward to the length incNums: whether or not numbers are counted as words or part of words returns list of lengths in order """ #Requires: findSpaces #Add -1 as first element to help get length of first word spaceIndices = [-1] + findSpaces(text, filterPunc, incNums) wordLen = [] #for range numSpaces = len(spaceIndices) #iterating through list of spaces, taking differences between adjacent elements -1 # to get the lengths of the words. length 0 is ignored and indicates a double space for n in range(1,numSpaces): length = spaceIndices[n] - spaceIndices[n-1] - 1 if length != 0: wordLen = wordLen + [length] return wordLen def listToString(list): """ Turns a list into a string list: the list returns the string """ #gg ez string = '' for element in list: string = string + str(element) return string def wordLengthCypher(text, floatHandling=0, pattern=1, inversePattern=False, cyphNums=True, standardFormat=False, incNums=True, filterPunc=True): """ Encrypts text using lengths of words as series key text: string to be encrypted floatHandling: determines how floats are delt with when added to string 0: decimal part dropped 1: unchanged 2: floor 3: round 4: ceil pattern: creates a pattern for positive or negative shift using mod. example with 0 representing positive and 1 representing negative: pattern 1: 0000000000 pattarn 2: 0101010101 pattern 3: 0110110110 inversePattern: flips the sights given by pattern cyphNums: whether or not numbers get shifted standardFormat: whether all caps, not spaces, no punctuation format it used incNums: Whether numbers get taken out of text filterPunc: whether or not punctuation is filtered out returns encrypted text """ #Requires: wordLengths, listToString, math.ceil, seriesCypher #too lazy to check a bunch of cases right now wordLenList = wordLengths(text, filterPunc) wordLenString = listToString(wordLenList) wordLenString = wordLenString * ceil( len(text)/len(wordLenString) ) cyphText = seriesCypher(text, wordLenString, floatHandling, pattern, inversePattern, cyphNums, standardFormat, incNums) return cyphText class mutableKey(): def __init__(self, key='', alpha='abcdefghijklmnopqrstuvwxyz'): self.key = key self.alpha = alpha #adds a letter to the kay def add(self, char): self.key = self.key + char #finds index of letter in key def ind(self, char): return self.key.find(char) #removes letter from key and its pair in alpha def rem(self, keyChar, alphaChar): self.key = self.key.replace(keyChar,'') self.alpha = self.alpha.replace(alphaChar,'') #gets the corresponding letter #goes from key to alpha def get(self, char): index = self.ind(char) newChar = self.alpha[index] self.rem(char, newChar) return newChar def pair(self, char): index = self.ind(char) if index == -1: return char newChar = self.alpha[index % (len(self.alpha)+1) ] return newChar def mutKeyCharCypher(text, generator, standardFormat=True, incNums=True, basicAlpha='abcdefghijklmnopqrstuvwxyz'): """ Encrypts with continuously changing alphabets, if a character is not included in the generator or basicAlpha then it will not be encrypted text: string to be encoded generator: creates key alphabet with fo76 method standardFormat: if true string returns as only uppercase alphanumerics incNums: whether or not numbers are included in standard format basicAlpha: the alphabet shifted into """ if standardFormat: text = filterString(text, incNums) cypherText = '' #tracker will keep track of what mutableKey a given letter is in tracker = {} #generate keyAlpha to be used keyAlpha = keyAlphabet(generator, basicAlpha) #fill tracker with all character that can be encrypted for char in keyAlpha: tracker[char] = 0 #holds the different mutableKeys, given a number to call by for given char tracker value keyDict = {0: mutableKey(keyAlpha, basicAlpha)} for char in text: #tracking upeprcase cap=False if char.isupper(): cap=True char = char.lower() #if character belongs to set it will be encrypted if char in keyAlpha: #get char's mutableKey level n = tracker[char] #increment char's value tracker[char] = n+1 #get encrypted char by calling the mutableKey it is in calling .get method newChar = keyDict[n].get(char) #if the mutableKey object for level has not been created yet, create it if n+1 not in keyDict: keyDict[n+1] = mutableKey(char, alpha=basicAlpha) else: #if it has then add the next char to the key keyDict[n+1].add(char) #if not encrypted dont do anything, reassign to newChar for gg ez else: newChar = char #if need recap newChar = newChar.upper() if cap else newChar #making new string cypherText = cypherText + newChar return cypherText def invertedKeyAlpha(generator, original='abcdefghijklmnopqrstuvwxyz'): """ Creates keyAlpha using generator that will invert the direction of encryption for cypher it is used in, given it its alpha to alpha type not fully tested """ key = keyAlphabet(generator, original) print(key) newKey = '' for char in original: print(char) index = key.find(char) newKey = newKey + original[index] return newKey def patternTest(len,par=1,par2=1,par3=1): """ To check pattern that will be used in seriesCypher, 1 == positive """ pattern='' for n in range(len): k = 1 if n%par==0 or (par2!=1 and n%par2==0) or (par3!=1 and n%par3==0) else 0 pattern = pattern + str(k) print(pattern) return pattern
7154a2d9b46199e3a5dd7841cc94f163111a10a2
Biddy79/eclipse_python
/Lists_Ranges_and_Tuples/Test_area/__init__.py
728
4.4375
4
sing_in_record = "D.K ", 21, ([]) #unpacking the tuple company, location, time_in_out = sing_in_record print(sing_in_record) #company, location these values cannot be changed as the are tuples #these values can be changed as they are list inside of tuple time_in = float(input(print("Enter Time in: "))) time_out = float(input(print("Enter Time out: "))) #below are two different ways of setting values in a list within a tuple sing_in_record[2].append((time_in)) time_in_out.append((time_out)) #iterating of items in tuple for info in sing_in_record: print(f"{info}", end = "") print("\n") #can also access list in tuple like this print(sing_in_record[2][0]) #or like this print(time_in_out[1])
8e5e4e74c8760257619ab7e1f87dcf3556e0dd6c
Klivanskaya/python_course
/lesson5/task4.py
97
3.84375
4
import string st = list(input('Enter your string: ')) st.reverse() print(st) st.sort() print(st)
45369aa4aa098f41693a810590eaa22652c549c8
taillessscorpion/C4T-BO3
/session7/part4/register3.py
1,577
3.890625
4
print('ĐĂNG KÍ TÀI KHOẢN') uname = input('Tên đăng nhập: ') print('Đã xác nhận thông tin cho tài khoản', uname) while True: password1 = input('Mật khẩu: ') pwc = int(len(password1)) if pwc >= 8: if password1.isalpha(): print('Mật khẩu phải có cả chữ và số. Mời nhập lại.') elif password1.isdigit(): print('Mật khẩu phải có cả chữ và số. Mời nhập lại.') elif password1.isalnum(): password2 = input('Nhập lại mật khẩu: ') if password1 < password2: print('Mật khẩu không khớp nhau. Đề nghị nhập lại.') elif password1 > password2: print('Mật khẩu không khớp nhau. Đề nghị nhập lại.') else: print('Đã xác nhận mật khẩu cho tài khoản', uname) break else: print('Mật khẩu phải có cả chữ và số. Mời nhập lại.') else: print('Mật khẩu phải dài hơn hoặc bằng 8 kí tự. Mời nhập lại.') while True: email = input('Email: ') if email.endswith('.com'): if '@' in email: print('Đăng kí thành công tài khoản', uname) break else: print('Tài khoản email không tồn tài. Mời kiểm tra lại.') else: print('Tài khoản email không tồn tài. Mời kiểm tra lại.')
9705febbc96bd9cb7f424971e4fec101facca8f3
AndrianovaVarvara/algorithms_and_data_structures
/TASK/Хирьянов 1 лекция черепаха/8_sq_spiral.py
195
3.65625
4
import turtle x = 10 turtle.forward (x) turtle.left (90) for i in range (10): turtle.forward (x) turtle.left (90) x += 10 turtle.forward (x) turtle.left (90) input()
062ce4be62326995c5af927418f58e864a107079
CrisperDarkling/Richard_Teach_Python
/lists.py
1,299
4.46875
4
# Create a list # literal print("Literal list 0 to 4") print([0, 1, 2, 3, 4]) # range function # A range needs to be turned into a list to print it's contents print("range 5 as list (0 to 4)") print(list(range(5))) # range function start, stop print("range 3, 8 as list (3 to 7)") print(list(range(3, 8))) #range function start, stop, step print ("range 3, 17, 2 as list (3 to 15)") print(list(range(3, 17, 2))) # List comprehension print("List comprehension i*2 for i in range(10)") print([i*2 for i in range(10)]) #List comprehension with if print("List comprehension i*2 for i in range(10) if i is even") print([i*2 for i in range(10) if i%2==0]) # List Comprehension with Else If print("FizzBuzz for range 1, 20") print(["FizzBuzz" if i%15== 0 else "Fizz" if i%3 == 0 else "Buzz" if i%5 == 0 else i for i in range(1,20)]) # Nested List Comprehension print("Nested List Comprehension (i, j) in i range 3, j range 5") print ([(i, j) for i in range(3) for j in range(5)]) print("Nested List Comprehension (i, j, i==j) in i range 3, j range 5") print ([(i, j, i==j) for i in range(3) for j in range(5)]) print("Nested List Comprehension (i, j, i+j==4) in i range 3, j range 5") print ([(i, j, i+j==4) for i in range(3) for j in range(5)])
c361fc47bfb61b9c4b01ccfcff4c9d40b5245ea5
cvlopes88/Sprint-Challenge--Intro-Python
/src/oop/oop1.py
983
4.0625
4
# Write classes for the following class hierarchy: # [Vehicle]->[FlightVehicle]->[Starship] # | | # v v # [GroundVehicle] [Airplane] # | | # v v # [Car] [Motorcycle] # # Each class can simply "pass" for its body. The exercise is about setting up # the hierarchy. # # e.g. # # class Whatever: # pass # # Put a comment noting which class is the base class # setting up main class here class Vehicle: def __init__(self, name, typeOfVehicle): self.name = name self.typeOfVehicle = typeOfVehicle def whatVehicle(self): return f'{self.name} is a {self.typeOfVehicle}' car = Vehicle('Car', 'GroundVehicle') print(car.whatVehicle()) motorcycle = Vehicle('Motorcycle', 'GroundVehicle') print(motorcycle.whatVehicle()) airplane = Vehicle('Airplane', 'FlightVehicle') print(airplane.whatVehicle()) starship = Vehicle('Starship', 'FlightVehicle i think :)') print(starship.whatVehicle())
fcda9b9fd249acc5f4eea5d91435dee691e3a7f8
atwenzel/mutread
/source/plotting.py
1,177
3.578125
4
"""Contains all the scripts for plotting data. Plotting package use is matplotlib, available at http://matplotlib.org/. Every script should accept any number of data sets in implicitly paired lists, such that data at index i in the xdata list should correspond to data at index i in the ydata list.""" #Global import matplotlib.pyplot as plt import numpy as np #Local def plot_hist(xdata, ylabels): """Plots a histogram of n data sets where n == len(xdata) == len(ydata)""" fig = plt.figure(figsize=(6,3)) #plt.hist(xdata, 2, normed=True) #plt.show() ##weights = np.ones_like(xdata)/float(len(xdata)) ##plt.hist(xdata, bins=100, weights=weights) ##plt.show() counter = 0 for dataset in xdata: density, bins = np.histogram(dataset, bins=100, density=True) unity_density = density/density.sum() bincenters = 0.5*(bins[1:]+bins[:-1]) plt.plot(bincenters, unity_density, label=ylabels[counter]) counter += 1 plt.legend(loc='lower right', frameon=False, numpoints=1) plt.show() if __name__ == "__main__": print("This file defines plotting scripts using the matplotlib plotting library")
e76a0105058be7d8aad6e00a7233f57fb67f31bf
daniel-reich/turbo-robot
/czLhTsGjScMTDtZxJ_8.py
780
4.125
4
""" In mathematics, primorial, denoted by “#”, is a function from natural numbers to natural numbers similar to the factorial function, but rather than successively multiplying positive integers, the function only multiplies **prime numbers**. Create a function that takes an integer `n` and returns its **primorial**. ### Examples primorial(1) ➞ 2 # First prime number = 2 primorial(2) ➞ 6 # Product of first two prime numbers = 2*3 = 6 primorial(6) ➞ 30030 ### Notes n >= 1. """ def primorial(n): count = 0 fin = 1 cur = 2 while count<n: if is_prime(cur): count+=1 fin*=cur cur+=1 return fin ​ def is_prime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True
74fa381cecc57150b8aefc99b4c99ea490daa5b0
GoncalezTI/Curso-de-Python-3-Mundo-01
/PythonExercicios/ex016.py
596
4.28125
4
# 016 - Crie um programa que leia um número real qualquer pelo # teclado e mostre na tela a sua porção inteira. '''MODO 1 import math num = float(input('Digite um valor: ')) print('O valor digitado foi {} e a sua porção inteira ' 'é {}'.format(num, math.trunc(num))) MODO 2 from math import trunc num = float(input('Digite um valor: ')) print('O valor digitado foi {} e a sua porção inteira ' 'é {}'.format(num, trunc(num)))''' # MODO 3 num = float(input('Digite um valor: ')) print('O valor digitado foi {} e a sua porção inteira ' 'é {}'.format(num, int(num)))
971d15ec70a6e89c917c3487703610bf70c50ed2
samargunners/LPTHW
/Firstgame.py
2,246
3.890625
4
# which bike is for you. def start(): print("You need to decide which bike is perfect for you.") print("No problem, we will help you select") choice = int(input("How old are you?: ")) if choice in range (18, 36): excitingage() elif choice in range (36, 51): seniorrider() elif choice in range (51, 99): tooold() else: underage() def excitingage(): print("You seem to be a yound rider") print('You have three options to select from Naked Bikes, Sports Bike and Caferacer') choice = input('What do you select:') if choice == "Naked Bike": nakedbikes() elif choice == "Sports Bike": sportsbike() else: caferacer() def seniorrider(): print("you seem to be an experienced rider ") print("you can either select Cruiser or Tourer") choice = input("what do you select:") if choice == "Cruiser": print("congratulations you won Goldwing") elif choice == "Tourer": print("congratulations you won BMW 1300 GS") else: print("you should quit riding now.") def tooold(): print("It's time for you to put your boots down and relax") def underage(): print("you need to be of a legal age") def nakedbikes(): print("This is an interesting choice i think you like long commutes") print("Which manufacturer do you want to go with Yamaha, KTM or Ducati") choice = input("Specify your choice manufacturer") if choice == "Yamaha": print("The best bike for you is Yamaha XSR 900") elif choice == "KTM": print("your dream bike should be KTM Super duke 1290") else: print("Bro Ducati Diavil is the bike to go for") def sportsbike(): print("so you like track riding eh!!") choice = input("Which bike do you want supersport, superbike or 250s") if choice == "supersport": print("Congrats you have selected the best bike possible, YAMAHA YZF R6") elif choice == "superbike": print("only buy this if you are willling to go to track, YAMAHA YZF R1") else: print("CBR 250 should be your starting bike") def caferacer(): print("You evil genius. Go way to go about your custom bike.") start()
2f07a30cd6ca7532942735f1bbeff0a8bcdaa32b
MrHamdulay/csc3-capstone
/examples/data/Assignment_6/fndjas001/question1.py
552
4.1875
4
"""A program that takes a list of names and prints them right aligned Jason Findlay 23/04/2014""" Name=input("Enter strings (end with DONE):\n") names=[] Count=0 length=0 #fill list while Name!="DONE": if Name=="DONE": break else: names.append(Name) Name=input() #find longest string for i in range(len(names)): if len(names[i])>length: length=len(names[i]) #print list of names print() print("Right-aligned list:") for i in range(len(names)): print(names[i].rjust(length))
efebe95c7d27e4b4c2e71e05b00e8580507ccb66
rajat27jha/Neural-Nets
/First_model.py
6,956
4.15625
4
# tensor is just an array and flow means manipulations # here w are going to use Mnist dataset beacuse its in the right format # an imp work in ML to find a right datset taht suits a perticular model, here mnist data set suits prefectly # training: 60000 sets, testing: 10000 sets # mnist contain 28 by 28 hand written images # we pass that to neural nets it will figure out the model # here features are the pixel values that will contain 0 and 1 ie whitespace or something is there # this will be a feed forward neural net ie we are going to pass data straight through # the func of optimizer is to make the cost func less by backpropagating and manipulating weights import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data ''' input > weight > hidden layer 1 (activation function) > weights > hidden layer 2 > (activation function) > weights > output layer compare output to intended output > cost or lost func (cross entropy) optimization func (optimizer) > minimize cost (AdamOptimizer....SGD, AdaGrad) backpropagation feed forward + backprop = epoch (ex 10-15 times) ''' mnist = input_data.read_data_sets('/tmp/data', one_hot=True) # first parameter asks for the directory of train_data # one hot helps in multi class function # here we r going to hv 10 classes from 0-9 # one hot means only one pixel or element is active and rest are not # for example if we were supposed to do i 0=0, 1=1, 2=2 etc # but one hot will does like this 0=[1,0,0,0,0,0,0,0,0,0] # 1=[0,1,0,0,0,0,0,0,0,0] # 2=[0,0,1,0,0,0,0,0,0,0] # 3=[0,0,0,1,0,0,0,0,0,0] n_nodes_h1 = 500 n_nodes_h2 = 500 n_nodes_h3 = 500 # three hidden layers and 500 nodes in each, they can be different n_classes = 10 n_batches = 100 # this will take 100 features at a time and feed directly to neural net, they will get manipulated and then next batch x = tf.placeholder('float', [None, 784]) # input data, sec para is matrix ie height*width y = tf.placeholder('float') # label # placeholdering variable # Placeholder simply allocates block of memory for future use. # Later, we can use feed_dict to feed the data into placeholder. By default, # placeholder has an unconstrained shape, which allows you to feed tensors of different shapes in a session. # its not necessary but we can define these so it will be very specific ie 28*28=784 pixels wide # sec para is shape, if any data that is not of this tensorflow will raise an error # placeholders are data that are going to be shoved to the network def print_shape(obj): print(obj.get_shape().as_list()) # To get the shape as a list of ints, do tensor.get_shape().as_list() def neural_network_model(data): # formula is: (input_data*weights + baises) hidden_1_layer = {'weight': tf.Variable(tf.random_normal([784, n_nodes_h1])), 'baises': tf.Variable(tf.random_normal([n_nodes_h1]))} # weight is key and it has values of tensorflow variables # ie a big array/tensor of random nos. of shape 784 for all uniques weights # baises are something that are added after the weights # its imp because in act. func as if all data is zero so weights multiplied will also be 0 # and no neuron will ever fire # 784 is input ie range and nodes(output) will get random weights within range (2D array) # random normal means not repeated # they actually the dimensions of weight matrix, in other words its just connecting input # to hidden layer one, adding some random weights in between ex adjacency matrix hidden_2_layer = {'weight': tf.Variable(tf.random_normal([n_nodes_h1, n_nodes_h2])), 'baises': tf.Variable(tf.random_normal([n_nodes_h2]))} # sq. brackets is just for arrays hidden_3_layer = {'weight': tf.Variable(tf.random_normal([n_nodes_h2, n_nodes_h3])), 'baises': tf.Variable(tf.random_normal([n_nodes_h2]))} output_layer = {'weight': tf.Variable(tf.random_normal([784, n_classes])), 'baises': tf.Variable(tf.random_normal([n_classes]))} print_shape(data) l1 = tf.add(tf.matmul(data, hidden_1_layer['weight']), hidden_1_layer['baises']) # matmul is matrix multiplication # now we will apply activation func print_shape(l1) l1 = tf.nn.relu(l1) # relu is rectified linear print_shape(l1) l2 = tf.add(tf.matmul(l1, hidden_2_layer['weight']), hidden_2_layer['baises']) print_shape(l2) l2 = tf.nn.relu(l2) print_shape(l2) l3 = tf.add(tf.matmul(l2, hidden_3_layer['weight']), hidden_3_layer['baises']) print_shape(l3) l3 = tf.nn.relu(l3) print_shape(l3) output = tf.add(tf.matmul(l3, output_layer['weight']), output_layer['baises']) # in output layer there will be no adding return output # out is one hot array def train_neural_network(x): prediction = neural_network_model(x) cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(prediction, y)) # softmax_cross_entropy_with_logits will calculate the difference bet expected output # and obtained one using logits as both are in one hot format # learning_rate=0.001 optimizer = tf.train.AdamOptimizer().minimize(cost) # cycles feed forward + backprop hm_epochs = 10 # training of network starts here with tf.Session() as sess: # context manager, see documentation sess.run(tf.initialize_all_variables()) # its just a session will help it run i dunno what exactly it does for epoch in range(hm_epochs): epoch_loss = 0 for _ in range(int(mnist.train.num_examples/n_batches)): # here we hv total no. of samples and we are dividing it by batches for no. of cycles # _ is just a shorthand for a variable that we just not care about epoch_x, epoch_y = mnist.train.next_batch(n_batches) # it will make chunks magically _, c = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: epoch_y}) # c is cost, in this session we are going to run the optimizer with cost # as the session runs it will feed x with x's epoch_loss += c print('Epoch ', epoch, 'completed out of ', hm_epochs, 'loss:', epoch_loss) # training ends correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1)) # it will be a bool # argmax will return the index of the max value from the array # first argument is the tensor and second argument is axis which has be 1(i dunno) accuracy = tf.reduce_mean(tf.cast(correct, 'float')) # tf.reduce_mean is equivalent to numpy mean # casting to float was imp to find mean print("Accuracy: ", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})) # i dunno what actually it does # maybe it will match out to input, features to labels train_neural_network(x)
ad4b565fdd126f577b83806f0d0c7d772415811f
donmariolo/Introduction-to-Python
/tema5_3.py
1,391
4.15625
4
# -*- coding: utf-8 -*- """ Created on Wed May 25 17:31:45 2016 @author: marioromero """ exponentes = range(1, 11) exp_list = list(exponentes) #Que tenemos en la lista? (en lenguaje natural). print(exponentes) print(exp_list) #A~nadir a la lista de exponentes [18, 19]. print("-------------------------------------------------------") exp_list = exp_list + [18,19] print(exp_list) #Para cada elemento de la lista, imprimir por pantalla 2 elevado a x. print("-------------------------------------------------------") for i in exp_list: print("{} elevado a {} = {}".format(2,i,2**i)) #Para cada elemento de la lista, imprimir por pantalla su #cuadrado. print("-------------------------------------------------------") for j in exp_list: print("{} elevado a {} = {}".format(j,2,j**2)) #Hacer que el ejercicio anterior muestre los resultados en orden #inverso (es decir, hay que iterar sobre los exponentes hacia #atras). print("-------------------------------------------------------") for j in exp_list[::-1]: print("{} elevado a {} = {}".format(j,2,j**2)) #Para cada elemento de la lista, comprobar si 2 ** x es un #numero par. print("-------------------------------------------------------") for i in exp_list: if((2**i) %2 == 0): print("{} elevado a {} = {} es PAR".format(2,i,2**i)) else: print("{} elevado a {} = {} NO es PAR".format(2,i,2**i))
b41040278dedcd9e81f0f249ae3c90b1e79e72f2
usac201602491/Proyectos980
/Parciales/Parcial1/Problema1.py
583
3.609375
4
N = 48 # Hasta donde se quiere encontrar el resultado de las sumas def cuadrados(num): respuesta = 0 # Resta de las sumas suma1 = 0 # Suma de valores suma2 = 0 # Suma de valores al cuadrado for i in range(0,N+1): suma1=suma1+i # Suma los valores de i suma2=suma2+(i*i) # Suma los valroes cuadrados de i suma1=suma1*suma1 # Saca el cuadrado de la suma de valores print(suma1) print(suma2) respuesta=suma1-suma2 # Hace la resta de las sumas print(respuesta) cuadrados(N)
40f550e5540800e32b0c00fe953b59de23281b9f
akwls/PythonTest
/Part14. 리스트 더 알아보기/list_index.py
218
3.65625
4
def safe_index(my_list, value): # 함수를 완성하세요 if value in my_list: return my_list.index(value) else: return None print(safe_index([1,2,3,4,5], 5)) print(safe_index([1,2,3], 5))
b3a13d461e7f10de1659e609733c812335719bed
vradja/leetcode
/Two Pointer/15. 3Sum.py
1,427
3.65625
4
class Solution: # iterative method def threeSum(self, arr): triplets = set() duplicate = dict() arr.sort() # better sort here than sorting each tuple in two_sum for index, value in enumerate(arr[:-2]): if value not in duplicate: self.two_sum(arr[index + 1:], -value, triplets) else: duplicate[value] = index return triplets def two_sum_1(self, arr, target, triplets): left, right = 0, len(arr) - 1 while left < right: # here equal to is not needed, since we want 2 distinct numbers. left_value, right_value = arr[left], arr[right] two_sum = left_value + right_value if target == two_sum: triplets.append((-target, left_value, right_value)) # move left and right since we found a match left += 1 right -= 1 elif two_sum < target: left += 1 else: right -= 1 def two_sum(self, arr, target, triplets): d = dict() for index, value in enumerate(arr): complement = target - value if complement in d: triplets.add((-target, complement, value)) else: d[value] = index sol = Solution() print(sol.threeSum([-3, 0, 1, 2, -1, 1, -2])) # print(search_triplets([-5, 2, -1, -2, 3]))
a1be667bc45b3560a13d581fd0b8ddebaa375636
AndreisSirlene/Python-Exercises-Curso-em-Video-World-1-2-and-3
/World1/challenge003.py
118
3.875
4
number1= int(input('First Number= ')) number2= int(input ('Second Number= ')) print('The sum is',number1+number2,'.')
2d0e762bba357cbd140e5c445c63880847dd2e66
patidarjp87/python_core_basic_in_one_Repository
/65.cheaksubsettuple.py
335
4.125
4
print("program to cheak whether a tuple is a subset of another tuple or not \n Enter super tuple") t1=eval(input()) t2=eval(input("Enter child tuple\n")) for x in t2: for y in t1: if x==y: break else: print(t2,"is not a subset of",t1) break else: print(t2,"is a subset of ",t1) input()
5367ca049ba14dff592593bd6cc189b5c0d9a467
albert118/Automated-Finances
/src/core/timeManips.py
3,322
3.609375
4
""" .. module:: timeManips :platform: Unix, Windows :synopsis: The time manipulation utility functions. .. moduleauthor:: Albert Ferguson <albertferguson118@gmail.com> """ # third party libs import numpy as np import pandas as pd # python core import math import os import sys import pickle from datetime import datetime def timeManips_groupbyTimeFreq(data: pd.DataFrame, time='D'): """Reindex for time by retyping. Retype and apply a PeriodIndex, selecting the M (monthly) opt. as a default.\ Use the groupby function of a dataframe and the column we want to groupby, return a sum\ Info on sorting:\ https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html\ https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.asfreq.html\ .. note:: This is a destructive method. **Args:** data(pd.DataFrane): A dataframe with the data to index by time. time(str): Options are 'Y', 'M' and 'D'. Defined by pd.PeriodIndex.\ See: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html\ See: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.PeriodIndex.html\ **Returns:** data(pd.DataFrame): The dataframe grouped by time. """ try: data.Date = pd.to_datetime(data.Date, dayfirst=True, infer_datetime_format=True, errors="ignore") data = data.groupby(pd.PeriodIndex(data.Date, freq=time), axis = 0).sum() data.Date = pd.Series(data.index) data.sort_values(by=["Date"], ascending=True, inplace=True, kind="mergesort") data.Date = data.Date.dt.to_timestamp() # .to_timestamp must be accessed via .dt class? except AttributeError: data = pd.to_datetime(data, dayfirst=True, infer_datetime_format=True, errors="ignore") data = pd.DataFrame(data).groupby(pd.PeriodIndex(data, freq=time), axis = 0).sum() data = pd.Series(data.index) data.sort_values(ascending=True, inplace=True, kind="mergesort") data = data.dt.to_timestamp() # .to_timestamp must be accessed via .dt class? data = data.tolist() finally: return data def timeManips_timestampConvert(data: list): """Retype for timestamp type. **Args:** data(list): The data of time-esque data. **Returns:** data(list): The data correctly typed. """ data = pd.to_datetime(data) data.sort_values(ascending=True) data = pd.to_datetime(data) # .to_timestamp must be accessed via .dt class? data = data.tolist() return data def timeManips_strConvert(value: str) -> str: """Convert a string to a datetime formatted string. **Args:** input(str): A string to convert to consistent format. **Returns:** output(str): A datetime string formatted as %d/%m/%Y.\ Given an invalid string or unknown format, the input is returned as is. """ output = value if '/' or '-' not in value: return value outstyle_str = "%d/%m/%Y" try: output = datetime.strptime(value, "%d/%m/%Y") except ValueError: output = datetime.strptime(value, "%d-%m-%Y") else: output = datetime.strftime(output, outstyle_str) return output
ac2c53f9abf2ce6aab25b467a8a933d8613b1ffa
Sanjana-cell/Python-Programs
/Dictionary/RemoveKeyInDictionary.py
272
3.859375
4
sample={} num=(int(input("Enter the size of dictionary"))) for i in range(1,num+1): sample.update({i:i*i}) print("Before removing the key",sample) key=(int(input("Enter the key to remove"))) if key in sample: del sample[key] print("After removing the key",sample)
d9d8485d0993fbae54b55449ea7cb77bb8398d26
moce96/CPO
/src/immutable.py
1,901
3.84375
4
def size(n): if n is None: return 0 else: return 1 + size(n.next) def cons(head, tail): """add new element to head of the list""" return Node(head, tail) def remove(n, element): assert n is not None, "element should be in list" if n.value == element: return n.next else: return cons(n.value, remove(n.next, element)) def head(n): assert type(n) is Node return n.value def tail(n): assert type(n) is Node return n.next def reverse(n, acc=None): if n is None: return acc return reverse(tail(n), Node(head(n), acc)) def mempty(): return None def mconcat(a, b): if a is None: return b tmp = reverse(a) res = b while tmp is not None: res = cons(tmp.value, res) tmp = tmp.next return res def to_list(n): res = [] cur = n while cur is not None: res.append(cur.value) cur = cur.next return res def from_list(lst): res = None for e in reversed(lst): res = cons(e, res) return res def iterator(lst): cur = lst def foo(): nonlocal cur if cur is None: raise StopIteration tmp = cur.value cur = cur.next return tmp return foo class Node(object): def __init__(self, value, next): """node constructor""" self.value = value self.next = next def __str__(self): """for str() implementation""" if type(self.next) is Node: return "{} : {}".format(self.value, self.next) return str(self.value) def __eq__(self, other): """for write assertion, we should be abel for check list equality (list are equal, if all elements are equal).""" if other is None: return False if self.value != other.value: return False return self.next == other.next
39927ca56f12825e90de0499ee7749c962fb4948
homezzm/leetcode
/LeetCode/中等/树/1261. 在受污染的二叉树中查找元素.py
3,360
4.03125
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right from collections import deque class FindElements(object): """ 给出一个满足下述规则的二叉树: root.val == 0 如果 treeNode.val == x 且treeNode.left != null,那么treeNode.left.val == 2 * x + 1 如果 treeNode.val == x 且 treeNode.right != null,那么treeNode.right.val == 2 * x + 2 现在这个二叉树受到「污染」,所有的treeNode.val都变成了-1。 请你先还原二叉树,然后实现FindElements类: FindElements(TreeNode* root)用受污染的二叉树初始化对象,你需要先把它还原。 bool find(int target)判断目标值target是否存在于还原后的二叉树中并返回结果。 """ def __init__(self, root): """ :type root: TreeNode """ if not root: return self.treeVals = set() def dfs(node, val): if not node: return node.val = val self.treeVals.add(val) dfs(node.left, 2 * node.val + 1) dfs(node.right, 2 * node.val + 2) dfs(root, 0) # 自己写的递归 # root.val = 0 # self.treeVals = [root.val] # # def dfs(node): # if not node: return # # if node.left: # node.left.val = 2 * node.val + 1 # self.treeVals.append(node.left.val) # if node.right: # node.right.val = 2 * node.val + 2 # self.treeVals.append(node.right.val) # dfs(node.left) # dfs(node.right) # # dfs(root) # 层次遍历搞定 # root.val = 0 # # q = deque() # q.append(root) # # self.treeVals = [root.val] # # while q: # node = q.popleft() # if node.left: # node.left.val = 2 * node.val + 1 # q.append(node.left) # self.treeVals.append(node.left.val) # if node.right: # node.right.val = 2 * node.val + 2 # q.append(node.right) # self.treeVals.append(node.right.val) def find(self, target): """ :type target: int :rtype: bool """ return target in self.treeVals if __name__ == '__main__': # root = TreeNode(val=-1, left=None, right=TreeNode(val=-1, left=TreeNode(val=-1, left=TreeNode(val=-1, left=None, # right=None), # right=None), right=None)) root = TreeNode(val=0, left=TreeNode(val=1, left=None, right=None), right=TreeNode(val=-1, left=TreeNode(val=-1, left=None, right=None), right=TreeNode(val=-1, left=None, right=TreeNode(val=0, left=None, right=None)))) obj = FindElements(root) print(obj.treeVals) # print(obj.find(2)) # return True # print(obj.find(3)) # return False # print(obj.find(4)) # return False # print(obj.find(5)) # return True
cdf047f0d67dcd900aba8ac7b4cff6fcbe4c2938
JoaoAreias/Brilliant
/miller_rabin.py
1,011
3.765625
4
""" Miller-Rabin primality test """ from math import log def gcd(x, y): return y if not (x%y) else gcd(y, x%y) def miller_rabin(n): # Value checks if not (type(n) is int): raise ValueError("input must be an integer") if n < 2: return False if n == 2: return True # Step 1: Determine k and m such that n-1 = (2^k)m k = round(log(gcd(n-1, 2**1024), 2)) m = (n-1) // (2**k) while not (m%2): k += round(log(gcd(m, 2**1024), 2)) m = (n-1) // (2**k) # Step 2: Choose a shuch that 1 < a < n-1 a = 2 # Step 3: Compute b0 = a^m mod n and b_{n} = b_{n-1}^2 mod n b = pow(a, m, n) if b == 1 or b == n-1: return True S = set([b]) while True: b = pow(b, 2, n) if b == 1 or b in S: return False elif b == n-1: return True S.add(b) if __name__ == '__main__': print("Starting Miller-Rabin") print(miller_rabin(7337488745629403488410174275830423641502142554560856136484326749638755396267050319392266204256751706077766067020335998122952792559058552724477442839630133))
d8402839449ea51f6e6391754525198cdd84e9ae
srthakor/ga-learner-dsmp-repo
/Project:-Student-Management-System/code.py
990
3.75
4
# -------------- # Code starts here class_1=['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio'] class_2=['Hilary Mason','Carla Gentry','Corinna Cortes'] new_class=class_1+class_2 print(new_class) new_class=class_1+class_2+['Peter Warden'] print(new_class) del new_class[5] print(new_class) # Code ends here # -------------- # Code starts here courses={'Math':65,'English':70,'History':80,'French':70,'Science':60} total=sum(courses.values()) print(total) percentage=((total)/(500)*100) print(percentage) # Code ends here # -------------- mathematics={'Geoffrey Hinton':78,'Andrew Ng':95,'Sebastian Raschka':65,'Yoshua Benjio':50,'Hilary Mason':70,'Corinna Cortes':66,'Peter Warden':75} topper= max(mathematics,key=mathematics.get) print (topper) # -------------- # Given string topper = 'andrew ng' print(topper.split()[0:2]) last_name=topper[7:9] #print(last_name) first_name=topper[0:6] #print(first_name) full_name=(last_name +" "+first_name) print(full_name) full_name.upper() certificate_name=full_name.upper() print (certificate_name) # Code ends here
41646f22cd1ebbdbabae811b14c97000e18a9187
minseunghwang/algorithm
/programmers_re/해시/2.py
559
3.5625
4
def solution(phone_book): l = len(phone_book) phone_book.sort() print(phone_book) for i in range(l-1): for j in range(i+1,l): print(phone_book[i], phone_book[j]) if len(phone_book[i]) <= len(phone_book[j][:len(phone_book[i])]): if phone_book[i] == phone_book[j][:len(phone_book[i])]: return False return True phone_book = ['12','123','1235','567','88'] phone_book = ['123','456','789','78','45'] # phone_book = ['12','123','1235','567','88'] print(solution(phone_book))
a082da7d7d2f0d80bf7f33eeca73ca35e9939376
pogross/bitesofpy
/47/password.py
540
3.65625
4
import string import re PUNCTUATION_CHARS = list(string.punctuation) used_passwords = set("PassWord@1 PyBit$s9".split()) def validate_password(password): pattern = re.compile( # lowercase alphabetical, uppercase alphabetical, numeric, special character, # 6-12 length r"^(?=.*[a-z]{2,})(?=.*[A-Z])(?=.*[0-9])(?=.*[\~\!\@\#\$\%\^\&\*\(\)\_\+\=\-\`\>\<\_])(?=.{6,12})" ) if pattern.match(password) and password not in used_passwords: used_passwords.add(password) return True return False
4cb685007944e387bed456c138b662d41d095dbb
Anitha710/265441_Daily_Commits
/functions.py
621
4.125
4
def my_fun(): print("spam") print("spam") print("spam") my_fun() #use of return def max(x, y): if x>=y: return x else: return y print(max(9, 12)) z= max(17, 5) print(z) # Docstrings def shout(word): """ print a word with an exclamation mark following it. """ print(word + "!") shout("spam") # Modules import random for i in range(5): value = random.randint(1,6) print(value) #example def print_nums(x): for i in range(x): print(i) return print_nums(10) def func(x): res = 0 for i in range(x): res += i return res print(func(4))
5c84904c2dc75f8d0ffe2fe48cb78d4fb7973b80
fedeh7/Shogi
/interface_shogi.py
2,832
3.703125
4
from shogi import Shogi, Rook, Lance, Pawn class Interface(): def __init__(self): self.game = Shogi() self.turn_count = 0 # Inicia el loop del juego def start_playing(self): while self.game.is_playing: self.turn_count += 1 self.input_origin_coordinates() self.input_destiny_coordinates() print( f"### Congratulations! {self.game.playerturn} Wins " f"in {self.turn_count} turns! ###".title()) # Loop para el ingreso de coordenadas para seleccionar una pieza def input_origin_coordinates(self): input_correct = False while not input_correct: print(self.print_board()) if self.game.error != "": print(f"---{self.game.error}---") row = input("Enter the Origin Row value(0-9): ") column = input("Enter the Origin Column value: ") if row == "exit" or column == "exit": self.game.is_playing = False if self.game.play_origin(row, column): input_correct = True return # Loop para el ingreso de coordenadas para el destino de una pieza # Si es valido, Pregunta si promocionar la pieza o no def input_destiny_coordinates(self): input_correct = False promote = "" while not input_correct: print(self.print_board()) if self.game.error != "": print(f"---{self.game.error}---") row = input("Enter the Destination Row value(0-8): ") column = input("Enter the Destination Column value(0-8): ") if self.game.play_destination(row, column): input_correct = True if self.game.board[int(row)][int(column)].set_for_promotion: while promote != "y" and promote != "n": promote = input( "Do you want to promote the piece?(y/n): ").lower() if promote != "y" and promote != "n": print("Enter 'y' or 'n'") if promote == "y": self.game.board[int(row)][int(column)].promote() return # Imprime el tablero, el turno actual, y el jugador actual en pantalla def print_board(self): screen = self.game.board_print() symbol = "" if self.game.playerturn == "white": symbol = "(\u039b)" elif self.game.playerturn == "black": symbol = "(V)" turn_indicator = ( f"\n======== #{self.turn_count} " f"{self.game.playerturn}{symbol} Turn ========\n".title()) screen += turn_indicator return screen if __name__ == "__main__": interface = Interface() interface.start_playing()
04bb9b942978bffdc2619925f05a00fb9dc557af
FinOCE/CP1404
/prac_05/word_occurences.py
345
3.875
4
words = {} text_raw = input("Text: ") text_array = text_raw.split(" ") for word in text_array: try: words[word] += 1 except KeyError: words[word] = 1 if '' in words: words.pop('') for word in sorted(words.keys()): max_length = max([len(word) for word in words]) print(f"{word:{max_length}} : {words[word]}")
12f4b2ebb6f5eae34ed8ed83d6a4e72ad6fff13a
weitaishan/algorithm-basics
/Python/初级算法/数组_4_存在重复元素.py
1,722
3.609375
4
# *_*coding:utf-8 *_* ''' 存在重复元素 给你一个整数数组 nums 。如果任一值在数组中出现 至少两次 ,返回 true ;如果数组中每个元素互不相同,返回 false 。 示例 1: 输入:nums = [1,2,3,1] 输出:true 示例 2: 输入:nums = [1,2,3,4] 输出:false 示例3: 输入:nums = [1,1,1,3,3,4,3,2,4,2] 输出:true 提示: 1 <= nums.length <= 105 -109 <= nums[i] <= 109 ''' from typing import List class Solution: def containsDuplicate(self, nums: List[int]) -> bool: ''' 方法一:先排序,然后在依次比较 复杂度分析 时间复杂度:O(NlogN),其中 N 为数组的长度。需要对数组进行排序。 空间复杂度:O(logN),其中 N 为数组的长度。注意我们在这里应当考虑递归调用栈的深度。 ''' if len(nums) <= 1: return False nums.sort() for i in range(len(nums) - 1): if nums[i] == nums[i + 1]: return True return False def containsDuplicate2(self, nums: List[int]) -> bool: # 方法二:使用集合,判断长度 if len(set(nums)) != len(nums): return True return False def containsDuplicate3(self, nums: List[int]) -> bool: ''' 方法三:哈希表 复杂度分析 时间复杂度:O(N),其中 N 为数组的长度。 空间复杂度:O(N),其中 N 为数组的长度。 ''' s = set() for i in nums: if i in s: return True s.add(i) return False nums = [1,2,3,4,1] print(Solution().containsDuplicate3(nums))
d248d52cb70f5f8ab30393f559fd546db44ff5eb
junjaytan/python-data-structures
/CTCI/7_oo_solutions.py
1,533
4.34375
4
# 7.1 class Card(object): """ abstract data type for card object """ def __init__(self, suit, value) # probably want to ensure that values are allowed if suit not in ["spade", "heart", "club", "diamond"]: raise self.suit = suit self.value = value class DeckOfCards(object): def __init__(self): """ initializes a list of 52 cards in the deck """ # e.g., self.deck = [Card("Space", "1"), Card()] def shuffle(self): """ shuffle cards """ def pop(self): #remove the top card return self.deck.pop() def peek(self): """ view the top card in the deck but don't remove """ class CardGame(object): def __init__(self): """ initializes the 52 cards in the deck """ # e.g., self.deck = [Card("Space", "1"), Card()] def shuffle(self): """ shuffle cards """ class Poker(CardGame): """ poker game methods could include: draw fold initialize_opponents """ class Blackjack(CardGame): """ methods could include: hit """ # 7.4 class PlayerBase(object): """ abstract base class for a player, used by both human and computer controlled players """ def get_turn(self): """ """ class ComputerPlayer(PlayerBase): def set_difficulty(self): """ :return: """ class ChessPiece(object): """ abstract class for chess piece""" class King(ChessPiece): class ChessPiecePosition(object): """ """
9dd6520e6513fe2b558b08e47447e789747a8dbc
IanCBrown/practice_questions
/power.py
252
4.0625
4
def exponent(a, b): total = 1 for i in range(b): total = multiply(total, a) return total def multiply(a, b): total = 0 for i in range(b): total += a return total print(multiply(5,3)) print(exponent(5, 3))
a066445887e9a5107b7e50511cefb7b18654fe0f
supvigi/python-first-project
/Tasks/2020_12_05/If/If24.py
125
3.859375
4
import math x = int(input("Put in the X: ")) if x > 0: print(2 * math.sin(x)) else: print("Your result is", 6 - x)
d7652e6410dcda0bee7443d329fab052b03135a7
baric6/ctf-python-ceaser-cipher
/decode.py
377
3.546875
4
#by baric #this is a basic shift chipher the password is shifted +7 #shift -7 to get the password counter = 0 vals = list('tfzbwlyzljylawhzzdvyk') ################################################### asciiVals = [] for chars in vals: asciiVals.append(ord(chars)-7) #print(asciiVals) newVal = [] for c in asciiVals: newVal.append(chr(c)) print("".join(newVal))
b66329b05b21d70dc4e6eaca9875d07c06e96e86
Gummy27/Prog
/Assignment 1/Basic/question_5.py
208
4.375
4
d = float(input("What is the diameter?")) import math radius = d / 2 volume = (4/3)*math.pi*(radius**3) volume_of_half_sphere = volume / 2 print("The volume of the half-sphere is", volume_of_half_sphere)
237662b004176ce1d070a1dbdaeed745e9c788bd
diegopnh/AulaPy2
/Aula 06/Ex003.py
143
3.90625
4
a = int(input('Digite um valor: ')) b = int(input('Digite outro valor: ')) s = a + b print('A soma entre {} e {} é igual a {}'.format(a,b,s))
7b9dd19c72141cefcde272c8af48579568b449c0
dlondonmedina/intro-to-programming-python-code
/4-1/car-all.py
1,584
4.3125
4
# define Car template class Car: def __init__(self, year, make, model, color, max_speed): self.__year = year self.__make = make self.__model = year self.__color = color self.__max_speed = max_speed self.__current_speed = 0 print("You now have a car with these features:") print("year: ", self.__year) print("make: ", self.__make) print("model: ", self.__model) print("color: ", self.__color) print("max_speed: ", self.__max_speed) print("current speed: ", self.__current_speed) def start(self): print('Car starting') def stop(self): print('Car stopping') def move_forward(self): print('Moving forward') def move_reverse(self): print('Moving in reverse') def set_speed(self, speed): self.__current_speed = speed print('Moving at this speed now:', self.__current_speed) def brake(self): if self.__current_speed > 0: self.__current_speed = self.__current_speed - 1 def park(self): print('Parking') def get_speed(self): return self.__current_speed # function to instantiate the class def main(): year = input('Enter the car year: ') color = input('Enter the car color: ') make = input('Enter the car make: ') model = input('Enter the car model: ') max_speed = input('Enter the car\'s max speed:') # instantiate a car mycar = Car(year, make, model, color, max_speed) # call methods on car mycar.start() # call main main()
b022e908ed5af3394d37eec7fb5b6cd453aef941
AdamSierzan/Learn-to-code-in-Python-3-basics
/2. Python_data_types/9.1.2 Data_types_Boleans.py
986
4.1875
4
#let's put to variables num1 = float(input("type the first number:")) num2 = float(input("type the second number:")) #now we can use the if statement, we do it like this # if (num1 > num2) #in the parentesis it is expecting the true or false valuable, in most programming languages we use curly braces, # and everything in the curly braces is the part of the "if", but not in python, in python we use colon ":" #the ":" makes automaticly an indetetion, so everything starting with indetetion is the part of if statemtnt if (num1 > num2): print(num1, "is grater than", num2) elif (num1 == num2): print(num1, "is equal than", num2) #so if this is true it's going to execute this code else: print(num1, "is smaller than", num2) #Here's how it works, if first statement is true, it's going to ignore the other two statements, # if it's not ttrue it's going to continue in structute, if second statemnt is not true it's going to exectue the third one, #which will be exectued
f201e5f6d2c9903a6929a2c92d1ceaebf51f20ed
csyuanm/py-dashen
/learning/lf/chapter5/2-voting.py
2,592
4.21875
4
#coding=utf-8 #5.3 if语句 print('****************') print('5.3 if语句') #5.3.1 简单的if语句 #最简单的if语句只有一个测试和一个操作: #if conditional_test: #do something(若测试结果为True,则执行紧跟if语句后面的代码;结果为False,则不执行) age = 19 if age >= 18: print("You are old enough to vote!") age = 19 if age >= 18: print("You are old enough to vote!") print("Have you redistered to vote yet?") #5.3.2 if-else语句 #通常需要在条件测试通过时执行一个操作,在没有通过时执行另一个操作。可使用if-else语句。 age = 17 if age >= 18: print("You are old enough to vote!") print("Have you redistered to vote yet?") else: print("Sorry, you are too young to vote.") print("Please register to vote asd soon as you turn 18!") #5.3.3 if-elif-else结构(检查超过两个的情况) #仅适用于只有一个条件满足的情况 #Python只执行结构中的一个代码块,它一次检查每个条件测试,直到遇到通过了的条件测试。 #测试通过后,执行紧跟在它后面的代码,并跳过余下的测试。 age= 12 if age < 4: print("Your admission cost is $0.") elif age < 18: print("Your admission cost is $5.") else: print("Your admission cost is $10.") age= 12 if age < 4: price = 0 elif age < 18: price = 5 else: price = 10 print("Your admission cost is $" + str(price) + ".") #5.3.4 使用多个elif板块(可根据需要使用任意数量的elif板块) age= 12 if age < 4: price = 0 elif age < 18: price = 5 elif age < 65: price = 10 else: price = 5 print("Your admission cost is $" + str(price) + ".") #5.3.5 省略else代码块 if age < 4: price = 0 elif age < 18: price = 5 elif age < 65: price = 10 elif age >= 65: price = 5 print("Your admission cost is $" + str(price) + ".") #5.3.6 测试多个条件 requested_toppings = ['mushrooms','extra cheese'] #三个if测试独立存在 if 'mushrooms' in requested_toppings: #检查顾客是否点了“mushrooms” print("Adding mushrooms.") if 'pepproni' in requested_toppings: #不管前一个测试是否通过,都将进行这个测试 print('Adding pepperoni.') if 'extra cheese' in requested_toppings: #不管前两个测试的结果如何,都将进行这个测试 print('Adding extra cheese.') print("\nFinished making your pizza!")
519d1ac902437a8d3788c1b14549115f13aed6b9
ellemcfarlane/bioinformatics
/DistanceBetweenLeaves/distance_between_leaves.py
3,658
4.09375
4
# Elle McFarlane from collections import deque from collections import defaultdict import heapq def distance_between_leaves(n, weighted_tree): """ Computes the distance between leaves in a weighted tree. :param n: number of leaves :param weighted_tree: adjacency list with n leaves :return: A n x n matrix (di, j), where di, j is the length of the path between leaves i and j. Example: n = 4, weighted_tree = 0->4:11 1->4:2 2->5:6 3->5:7 4->0:11 4->1:2 4->5:4 5->4:4 5->3:7 5->2:6 sample output: 0 13 21 22 13 0 12 13 21 12 0 13 22 13 13 0 """ distances = [] # get distance from each leaf to all other vertices for leaf in range(n): # dists include to internal nodes, so only take the leaves dists 0-n distances.append(distances_from(n, leaf, weighted_tree)[0:n]) return distances def distances_from(n, vertex, weighted_tree): """ Calculates (shortest) distances from vertex to all other vertices in weighted_tree :param n: number of leaves :param vertex: start vertex to get distances from :param weighted_tree: adjacency list :return: list of distances from vertex """ # leaves plus internal nodes total_vertices = len(weighted_tree) if vertex >= n or vertex < 0: return None # initially set all dists to infinite except for starting node, which is 0 dist dist_from_source = [float('inf')] * total_vertices dist_from_source[vertex] = 0 # add source to fringe fringe = [(dist_from_source[vertex], vertex)] # keep track of vertices whose min distance from source is already found min_found = set() # dijkstra's algorithm to find shortest distance from source to all other vertices while fringe: dist_from_parent, closest_vertex = heapq.heappop(fringe) # skip if min dist for node already found ( if closest_vertex in min_found: continue children = weighted_tree[closest_vertex] min_found.add(closest_vertex) # update distances from closest_vertex to its children and add to fringe for child in children: child_vert = child[0] child_dist_from_parent = child[1] dist_calc = dist_from_parent + child_dist_from_parent if dist_calc < dist_from_source[child_vert]: dist_from_source[child_vert] = dist_calc heapq.heappush(fringe, (dist_from_source[child_vert], child_vert)) return dist_from_source def driver(path): """loads input file data into distance_between_leaves""" with open(path, 'r') as file: n = int(next(file)) adj_list = defaultdict(list) for line in file: data = line.strip().split("->") if len(data) >= 2: parent = data[0] child_data = data[1] parent = int(parent) child_vertex, child_weight = (int(elm) for elm in child_data.split(":")) adj_list[parent].append((child_vertex, child_weight)) dists = distance_between_leaves(n, adj_list) # space out numbers a bit and print as proper matrix print('\n'.join([''.join(['{:<4}'.format(item) for item in row]) for row in dists])) #driver("smalltest.txt") driver('rosalind_ba7a.txt')
453c0a775ba63c1d6a1f70921db703cb2f731fbd
Jmueller87/learningpython
/mypolygon.py
3,270
4.375
4
# This was a textbook project. The goal was to write functions using # the turtle program that draw certain shapes and designs. # I don't know the official solutions, but # these various functions I wrote drew what they were intended to. import math import turtle bob = turtle.Turtle() print(bob) def polygon(length,n): #This function draws polygons with n sides c = 360/n for i in range(n): bob.fd(length) bob.lt(c) def circle(r): #This function draws circles with radius r d = (2*math.pi*r)/360 polygon(d,360) def basic_arc(r,angle): #This function draws an arc n = float(r*angle*(math.pi/180)) s = 0 i = angle/n while s < n: bob.fd(1) bob.lt(i) s += 1 continue def arc_seg(r,angle): #This function draws an arc segment (not an assignment) bob.fd(r) bob.lt(90) basic_arc(r,angle) bob.lt(90) bob.fd(r) def pizza(r,angle,c): #This funtion was part of a different project n = float(r*angle*(math.pi/180)) i = angle/n while True: s = 0 arc(r,angle) if s>= n: bob.lt(c) continue def petals(a,c,n): #This function draws symetrical petal patterns b = 180-(c/2) i = 0 while i < n: n = float(a*c*(math.pi/180)) s = 0 i = c/n while s < n: bob.fd(1) bob.lt(i) s += 1 continue bob.lt(b) i += 1 continue def triangles(length,angle): #This function draws a polygon made of triangles deg = angle*(math.pi/180) a = math.pi - (2*deg) b = (length*math.sin(a))/(math.sin(deg)) c = 180 - angle while True: bob.fd(length) bob.rt(c) bob.fd(b) bob.rt(c) bob.fd(length) bob.rt(180) continue def spiral(a,angle): #This function draws a spiral c = 360 while True: r = a/angle d = (2*math.pi*r)/c bob.fd(1) bob.lt(d) a += 1 c -= 1 if c == 1: break continue def letter_a(): #This function draws the letter A bob.lt(70) bob.fd(100) bob.rt(140) bob.fd(50) bob.rt(110) bob.fd(35) bob.rt(180) bob.fd(35) bob.rt(70) bob.fd(50) bob.lt(70) bob.fd(10) def letter_b():#Letter B (adjustments needed to basic_arc to work) bob.lt(90) bob.fd(94) bob.rt(90) basic_arc(23,180) bob.lt(180) bob.fd(10) basic_arc(24,180) bob.fd(10) bob.lt(183.3) bob.fd(43) def letter_c(): #Letter C (adjustments needed to basic_arc to work) bob.fd(57) bob.rt(180) bob.fd(10) basic_arc(47,180) bob.fd(20) def letter_d(): #Letter D (adjustments needed to basic_arc to work) bob.fd(10) basic_arc(47,180) bob.fd(10) bob.rt(89.5) bob.fd(94) bob.rt(180) bob.fd(94) bob.lt(90) bob.fd(67) #polygon(100,7) #circle(100) #basic_arc(100,90) #arc_seg(100,60) #petals(100,60,200) #triangles(100,70) #spiral(1000,60) #turtle.mainloop()
faa9fca2c29afc2bfd4b3717d98e52e3ef063f9e
klimek91/battleships
/new.py
1,489
4.125
4
from random import randint board = [] for x in range(0, 5): board.append(["O"] * 5) def print_board(board): for row in board: print(" ".join(row)) print_board(board) def random_row(board): return randint(0, len(board) - 1) def random_col(board): return randint(0, len(board[0]) - 1) ship1_row = random_row(board) ship1_col = random_col(board) print ('Ship1 row and col: ',ship1_row,ship1_col) while True: ship2_row = random_row(board) ship2_col = random_row(board) if ship2_row != ship1_row and ship2_col != ship1_col: break print("Ship2 row and col: ",ship2_row,ship2_col) hit_count=0 for turn in range(4): print("Turn", turn + 1) guess_row = int(input("Guess Row: ")) guess_col = int(input("Guess Col: ")) if guess_row == ship1_row and guess_col == ship1_col or guess_row == ship2_row and guess_col == ship2_col: hit_count+=1 print("Congratulations! You sank my battleship!") board[guess_row][guess_col] = "*" if hit_count==2: print_board(board) print("Congratulations! You sank both battleships! You won!!!") break print_board(board) else: if guess_row not in range(5) or guess_col not in range(5): print("Oops, that's not even in the ocean.") elif board[guess_row][guess_col] == "X": print("You guessed that one already.") else: print("You missed my battleship!") board[guess_row][guess_col] = "X" if (turn == 3): print("Game Over") print_board(board)
d6efd1bdad058c2b2efa936769624fce846ff34d
hsuanhauliu/leetcode-solutions
/medium/construct-binary-tree-from-inorder-and-postorder-traversal/solution.py
1,121
4.09375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: """ Recursion reversed-pos-order traversal. Traverse in reversed-pos-order allows us to construct the tree in the order of root, right, left, so we will be able to construct the tree from top to bottom. Given the root node, we can split the in-order list to two lists. The left list contains all elements in the left subtree and the right list contains all elements in the right subtree. Time: O(n) Space: O(n) """ def construct(ino, pos): if not ino: return None root = TreeNode(pos.pop()) split = ino.index(root.val) root.right = construct(ino[split+1:], pos) root.left = construct(ino[:split], pos) return root return construct(inorder[:], postorder[:])
0f31bc774bd8ce63b835a71186f6b79d40069479
Yukikazari/kyoupuro
/.提出一覧/AtCoder/除夜の鐘/arc019/a/main.py
248
3.640625
4
#!/usr/bin/env python3 #import #import math #import numpy as np #= int(input()) S = list(input()) dic = {"O": 0, "D": 0, "I": 1, "Z": 2, "S": 5, "B": 8} for i in range(len(S)): if S[i] in dic: S[i] = str(dic[S[i]]) print("".join(S))
cfe38dc15fd91be35f083f8e3577863cdced21a6
zagrosbingol/Localfile-Invasion
/lfiencoding.py
752
3.53125
4
#/usr/bin/python3 import hashlib as hash import base64 import myencodings def welcome(): print("Please choose from the following options on what encoding you want?\n") #List creation mylist = ["base64", "urlencoding", "hex", "nullbyte", "All of the above"] print("1.\t", mylist[0],"\n", "2.", mylist[1], "\n", "3.\t", mylist[2]) choice = input("") if choice == mylist[0]: #Calls the base64 function myencodings.basesixty() elif choice == mylist[1]: #call the url encoding function print("Payload is: ") myencodings.urlencoding() elif choice == mylist[2]: myencodings.hex() else: exit() welcome()
8116814f9832ee37506f3206ec5a7cef0ff55823
ravi4all/Python_WE_Jan_2
/NativeDataTypes/03-Tuples.py
481
3.6875
4
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> tup = (1,2,3,4,5,6,7,10) >>> tup = (1,2,3,4,5,6,7,10,'hi','hello') >>> tup[0] 1 >>> tup[-1] 'hello' >>> tup[0:5] (1, 2, 3, 4, 5) >>> tup[0] = 'Hi' Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> tup[0] = 'Hi' TypeError: 'tuple' object does not support item assignment >>>
3f4114c44cfd1cfeb61593934be1e5f91e06a80a
funny1dog/CTCI_python
/chapter_17/p17_4.py
1,548
3.640625
4
from typing import List # Method: Count expected evens and odds, tehnically O(log_2(n^2)) # Time: O(n) # Space: O(n) def get_bit(a: int, bit_nr: int) -> int: shifted_a = a >> (bit_nr) return shifted_a & 0b1 def find_mssing(arr: List[int], n: int) -> int: return find_missing_helper(arr, list(range(len(arr))), 0, n) def find_missing_helper( arr: List[int], list_indexes: List[int], bit_offset: int, n: int ) -> int: if n == 0: return 0 odds = [] evens = [] for i in list_indexes: bit_now = get_bit(arr[i], bit_offset) if bit_now: odds.append(i) else: evens.append(i) expected_odds = 0 expected_evens = 0 for i in range(n + 1): if i & 0b1: expected_odds += 1 else: expected_evens += 1 if len(evens) < expected_evens: bit_now = 0 rest = find_missing_helper(arr, evens, bit_offset + 1, n >> 1) else: bit_now = 1 rest = find_missing_helper(arr, odds, bit_offset + 1, n >> 1) # print(f"Bit now is {bit_now}, rest {rest}," # f" evens: {evens} (expected {expected_evens})," # f" odds: {odds} (expected {expected_odds})") return (rest << 1) | bit_now if __name__ == "__main__": exs = [ ([0, 1, 2], 3), ([1, 2, 3, 4, 5, 6, 7, 8], 8), ([0, 1, 2, 3, 5], 5), ([1, 2, 3, 4, 5, 6, 7, 8, 0], 9), ] for arr, n in exs: print(f"In arr {arr}, with limit {n}, missing is {find_mssing(arr,n)}")
b64a4a01798b7b45da0a563d4ead5078261942aa
thehalovex/PythonCBT
/ifthenelse1.py
268
4.0625
4
name = input('Please tell me your name: ') rawAge = input('Please tell me your age: ') age = int(rawAge) if age >= 20: print(name, 'you are allowed in!') print('What would you like to drink?') else: print('Unfortunately', name, 'you are not allowed in.')
be3322c3002ca4e06c7605d80d49a1da96286ca5
kapilnavgurukul/python-logical
/list1.py
152
3.71875
4
list1 = [1, 342, 75, 23, 98] list2 = [75, 23, 98, 12, 78, 10, 1] new_list=[] for i in list1: if i in list2: new_list.append(i) print (new_list)
03fe56a51dc37653742e46ceb59d32986e4ba988
HermesBoots/holbertonschool-higher_level_programming
/0x0A-python-inheritance/4-inherits_from.py
417
3.921875
4
#!/usr/bin/python3 """Module to check if object is from subclass of given type""" def inherits_from(obj, a_class): """Determine whether obj is an instances of a subclass of a_class Args: obj: instance to check a_class: class to check Returns: True if obj is instance of subclass of a_class, else False """ return isinstance(obj, a_class) and type(obj) is not a_class
a4126ce9f5468eaf9e2475cba1812c54aecca15d
zalecodez/Miniflow
/f.py
554
3.96875
4
""" Given the starting point of any `x` gradient descent should be able to find the minimum value of x for the cost function `f` defined below. """ import random from gd import gradient_descent_update def f(x): return x**2 + 5 def df(x): #Derivative of f with respect to x return 2*x x = random.randint(0, 10000) learning_rate = 0.1 epochs = 100 for i in range(epochs+1): cost = f(x) gradx = df(x) print("EPOCH {}: Cost = {:.3f}, x = {:.3f}".format(i, cost, gradx)) x = gradient_descent_update(x, gradx, learning_rate)
f03771b1c88d56f8df3c37b06beab03b85286e44
vanuir/ESOF
/M5/Criar_Tabela/Criar_Tabela.py
398
3.53125
4
# 02_create_schema.py import sqlite3 #conectando... conn = sqlite3.connect("C:\M5\criando_uma_tabela\clients.db") #definindo um cursor cursor = conn.cursor() #crindo a tabela (schema) cursor.execute(""" CREATE TABLE clientes ( id, nome, idade, cpf, email, fone, cidade, uf, criado_em );""") print('Tabela criada com sucesso.') #desconectando... conn.close()
322fd88737758a18ae3c8ef02bb71792c2d90dab
jmmL/misc
/test2.py
365
4.03125
4
def main(): string_to_mangle = input("Enter a string:\n") def piggy(pig_string): if pig_string[0] == "a" or "e" or "i" or "o" or "u": pig_string += "way" return pig_string else: pig_string += "-" + pig_string[0] + "ay" return pig_string[1:] print(piggy(string_to_mangle)) main()
0b992423b613c14b7886f9f3e98db46e5ecfddb9
dwalley/ObsoleteRouteFinder
/dheaps.py
8,682
3.609375
4
# heaps module import math class dheaps(): def __init__(self,d,n,heap_type='max',less_than=None,greater_than=None): ###create an object of type dheap with length n, with each parent having up to d children### self.heap_size = 0 # maximum index for which there is data self.max_children = d self.length = n #size of the list holding the data self.heap_array = [] # internal representation, all elements of heap_array must be comparable self.lt_function = less_than self.gt_function = greater_than self.heap_type = heap_type # or could 'min' for i in range(0,n): self.heap_array.append(0) def lt(self,a,b): if self.lt_function == None: if self.heap_type == 'max': # None is negative infinity return a < b else: # heap type in min and None is positive infinity if a == None: return False elif b == None: return True else: return a < b else: return self.lt_function(a,b) def gt(self,a,b): if self.gt_function == None: if self.heap_type == 'max': # None is negative infinity return a > b else: # heap type in min and None is positive infinity if a == None: return True elif b == None: return False else: return a > b else: return self.gt_function(a,b) def set_value(self,i,value): assert type(i) == type(1) or type(i) == type(None) if i == None: return None elif i >= 1 and i <= self.length: # we are setting a value in an existing part of the heap self.heap_array[i-1] = value if i > self.heap_size: self.heap_size = i return value else: # we need to extend the heap for j in range(self.length,i): self.heap_array.append(0) self.heap_array[i-1] = value self.heap_size = i self.length = i return value def value(self,i): assert type(i) == type(1) or type(i) == type(None) if i == None: return None elif i >= 1 and i <= self.heap_size: return self.heap_array[i-1] else: raise heapIndexError def parent_index(self,i): assert type(i) == type(1) assert i >= 1 and i <= self.heap_size if i >1: return (i+self.max_children-2)//self.max_children else: return None def ith_child_index(self,n,i): # return the index of the ith child of nth element assert type(i) == type(1) assert type(n) == type(1) assert i >= 1 and i <= self.max_children and n >= 1 ## print 'getting',i,'child of',n,'element' if n*self.max_children - self.max_children + i + 1<= self.heap_size: return n*self.max_children - self.max_children + i + 1 else: return None def heapify(self,k): # assumes the child dtrees of element k are valid heaps of type heap_type # but self.value(k) might not satisify the heap criteria if self.heap_type == 'max': extreme_index = k extreme_value = self.value(k) for j in range(1,self.max_children+1): temp_index = self.ith_child_index(k,j) if temp_index != None: if self.lt(extreme_value,self.value(temp_index)): # we found a bigger element, keep track of it extreme_value = self.value(temp_index) extreme_index = temp_index if extreme_index == k: # we did not find any larger elements among the children return None else: # we did find a larger element, swap it up the tree and recurr pushing our initial element down self.set_value(extreme_index,self.value(k)) self.set_value(k,extreme_value) self.heapify(extreme_index) elif self.heap_type == 'min': extreme_index = k extreme_value = self.value(k) for j in range(1,self.max_children+1): temp_index = self.ith_child_index(k,j) if temp_index != None: if self.gt(extreme_value,self.value(temp_index)): # we found a smaller element, keep track of it extreme_value = self.value(temp_index) extreme_index = temp_index if extreme_index == k: # we did not find any larger elements among the children return None else: # we did find a smaller element, swap it up the tree and recurr pushing our initial element down self.set_value(extreme_index,self.value(k)) self.set_value(k,extreme_value) self.heapify(extreme_index) else: raise heapTypeError def build_heap(self): for k in range(self.heap_size//self.max_children,0,-1): self.heapify(k) def heap_sort(self): self.build_heap() old_heap_size = self.heap_size for i in range(old_heap_size,1,-1): temp = self.value(i) self.set_value(i,self.value(1)) self.set_value(1,temp) self.heap_size -= 1 self.heapify(1) if self.heap_type == 'max': self.heap_type = 'min' elif self.heap_type == 'min': self.heap_type = 'max' else: raise heapTypeError self.heap_size = old_heap_size return self.heap_array def heap_maximum(self): if self.heap_type == 'max': return self.value(1) elif self.heap_type == 'min': # flip the heap to a max heap and return the first value self.heap_sort() return self.value(1) else: raise heapTypeError def heap_extract_max(self): if self.heap_size < 1: return None else: if self.heap_type == 'max': heap_max = self.value(1) self.set_value(1,self.value(self.heap_size)) self.set_value(self.heap_size,heap_max) self.heap_size -= 1 self.heapify(1) return heap_max elif self.heap_type == 'min': self.heap_sort() heap_max = self.value(1) self.set_value(1,self.value(self.heap_size)) self.set_value(self.heap_size,heap_max) self.heap_size -= 1 self.heapify(1) return heap_max else: raise heapTypeError def heap_change_key(self,i,key): if self.heap_type == 'max': gt_result = self.gt(self.value(i),key) if gt_result: # we are decreasing the key in a max heap self.set_value(i,key) self.heapify(i) else: # we are increasing the key in a max heap self.set_value(i,key) j = self.parent_index(i) while j != None and self.lt(self.value(j),self.value(i)): #bubble value up the heap as necessary temp = self.value(j) self.set_value(j,self.value(i)) self.set_value(i,temp) i = j j = self.parent_index(j) elif self.heap_type == 'min': if self.lt(self.value(i),key): self.set_value(i,key) self.heapify(i) else: self.set_value(i,key) j = self.parent_index(i) while j != None and self.gt(self.value(j),self.value(i)): #bubble value up the heap as necessary temp = self.value(j) self.set_value(j,self.value(i)) self.set_value(i,temp) i = j j = self.parent_index(j) else: raise heapTypeError def heap_insert(self,key): self.heap_size += 1 self.set_value(self.heap_size,None) self.heap_change_key(self.heap_size,key)
2ac581b3551aa9e67ec836d823ebe17466fa3f1b
BibekKoirala/DynamicProgramming
/Fibonacci_Tabulation.py
299
3.890625
4
# Fibonacci series using Tabulation # Time complexity Big O of this method is n LookupTable = [None for i in range(6)] def fib_tab(n): LookupTable[0]=0 LookupTable[1]=1 for i in range(2,6): LookupTable[i] = LookupTable[i-1] + LookupTable[i-2] fib_tab(5) print(LookupTable)
278b55cfd3a7e992853ad60b5419cba5e8e6266b
akalya23/gkj
/20.py
91
3.59375
4
ap=input() ap=int(ap) fact=1 for i in range(1,ap+1): fact=fact*i i=i+1 print(fact)
076c8188b5914ed062e437bc4acb11591b3ff04d
UX404/Leetcode-Exercises
/#374 Guess Number Higher or Lower.py
710
4.1875
4
''' We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I'll tell you whether the number is higher or lower. You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0): -1 : My number is lower 1 : My number is higher 0 : Congrats! You got it! Example : Input: n = 10, pick = 6 Output: 6 ''' class Solution: def guessNumber(self, n: int) -> int: lh, rh = 1, n while lh <= rh: mid = (lh + rh) // 2 judge = guess(mid) if judge == 1: lh = mid + 1 elif judge == -1: rh = mid - 1 else: return mid
340269441ced53fda4fbc7a5ae61ce655a8f41e3
hexinping/PythonCode
/practice/py_xml.py
4,457
3.734375
4
# -*- coding: UTF-8 -*- ''' xml 解析 http://www.runoob.com/python/python-xml.html python有三种方法解析XML,SAX,DOM,以及ElementTree 1.SAX (simple API for XML ) python 标准库包含SAX解析器,SAX用事件驱动模型,通过在解析XML的过程中触发一个个的事件并调用用户定义的回调函数来处理XML文件。 2.DOM(Document Object Model) 将XML数据在内存中解析成一个树,通过对树的操作来操作XML 3.ElementTree(元素树) ElementTree就像一个轻量级的DOM,具有方便友好的API。代码可用性好,速度快,消耗内存少。 注:因DOM需要将XML数据映射到内存中的树,一是比较慢,二是比较耗内存,而SAX流式读取XML文件,比较快,占用内存少,但需要用户实现回调函数(handler)。 https://blog.csdn.net/weixin_39909877/article/details/78842536 ''' from xml.dom.minidom import parse import xml.dom.minidom def elements_func(root, attrName): attrs = root.getElementsByTagName(attrName) if not attrs: print attrName + "属性不存在" else: for attr in attrs: print attrName+": %s" % attr.childNodes[0].data def dom_read_fun(): # 使用minidom解析器打开 XML 文档 DOMTree = xml.dom.minidom.parse("movies.xml") collection = DOMTree.documentElement # 查找“shelf”属性 if collection.hasAttribute("shelf"): print "Root element : %s" % collection.getAttribute("shelf") # 在集合中获取所有电影 movies = collection.getElementsByTagName("movie") for movie in movies: print "*****Movie*****" if movie.hasAttribute("title"): print "Title: %s" % movie.getAttribute("title") # print movie.nodeName, movie.nodeValue #获取某个标签下的某个元素 getElementsByTagName elements_func(movie, "type") elements_func(movie, "format") elements_func(movie, "year") elements_func(movie, "rating") elements_func(movie, "stars") elements_func(movie, "description") #------------------------------------------------------------------------- #https://www.jb51.net/article/74942.htm XML_FILE = "movies.xml" from tools.ElementTree_XML import ElementTree_Class as EleClass def elementTree_func(): # 1. 读取xml文件 eleObj = EleClass(XML_FILE) tree = eleObj.read_xml() # 2. 属性修改 # A. 找到父节点 nodes = eleObj.find_nodes("movie") #拿到所有的movie节点 for node in nodes: # 拿到movie节点的子节点list children = node._children for child in children: print "tag = %s, value = %s" % (child.tag,child.text) # B. 通过属性准确定位子节点 tchilds = nodes[0]._children result_nodes = eleObj.get_node_by_keyvalue(tchilds, {"year": "2003"}, True) for node in result_nodes: print node.tag,node.text attrs = result_nodes[0].attrib for key, value in attrs.items(): print "属性1:", key, value # C. 修改节点属性 为什么文件内容不变 打出来的值明明变了啊 ==》文件内容不会变 我理解为只拿到了一份数据拷贝 eleObj.change_node_properties(result_nodes, {"title": "2221"}) for key, value in attrs.items(): print "属性2:", key, value # D. 删除节点属性 eleObj.change_node_properties(result_nodes, {"title": ""}, True) # 3. 节点修改 remindNode = nodes[0] # A.新建节点 newTag = "person" if not eleObj.check_node_isExist(remindNode,newTag): a = eleObj.create_node(newTag, {"age": "15", "money": "200000"}, "this is the firest content") # B.插入到父节点之下 remindNode.append(a) if eleObj.check_node_isExist(remindNode, "description"): # 4. 删除节点 # 定位父节点 # 准确定位子节点并删除之 eleObj.del_node_by_tagkeyvalue(nodes, "description", {"sequency": "chain1"}) # 5. 修改节点文本 # 定位节点 text_nodes = eleObj.get_node_by_keyvalue(eleObj.find_nodes("movie/description"), {"sequency": "chain1"}) eleObj.change_node_text(text_nodes, "new text") # 6. 输出到结果文件 eleObj.write_xml(XML_FILE) if __name__ == "__main__": print "xml 解析------" # dom_read_fun() elementTree_func()
727fc808aaf69cefbf4bc7a3fe7ab62ac264cde5
DS-Veritas/CS-A111X_Car_Dealer_System
/Buyers.py
1,134
3.78125
4
# -*- coding: utf-8 -*- """ Created on Fri Nov 22 11:38:18 2019 @author: Jeheon Kim """ from Cars import Car class Buyer: def __init__(self, name): self.__bid_list = [] self.__name = name # Buyer can make an offer to a single car they like the most # Buyer's name and offered amount will be saved in the auctionList dictionary def offer(self, bidder_name, car_info, bid_amount, auctionList): if auctionList.get(car_info) is None: auctionList[car_info] = [[bidder_name, float(bid_amount)]] else: auctionList.get(car_info).append([bidder_name, float(bid_amount)]) # Also, adds a bidded car to the buyer's bid_list self.__bid_list.append(car_info) def get_name(self): return self.__name def get_bid_list(self): return self.__bid_list # Won't be used in the simulation but buyer prints its bidded car def __str__(self): for car in self.__bid_list: print("You have bid for {}.".format(car.get_model_name()))
559d622908ae527112a98a2c22fd172fdaeba07c
dapazjunior/ifpi-ads-algoritmos2020
/Fabio_01/Fabio01_Parte01/f1_p1_q15_area_triangulo.py
240
3.828125
4
# Entrada base = float(input('Digite a medida da base do triângulo: ')) altura = float(input('Digite a medida da altura do triângulo: ')) # Processamento area = (base * altura) / 2 # Saida print(f'A área do triângulo é {area:.2f}.')
65afff46431ef801710e67889b69c172f0e742bf
fossabot/IdeaBag2-Solutions
/Numbers/Change Return Program/change_return_program.py
2,797
4.21875
4
#!/usr/bin/env python3 """A program for calculating optimal change. Title: Change Return Program Description: Develop a program that has the user enter the cost of an item and then the amount the user paid for the item. Your program should figure out the change and the number of quarters, dimes, nickels, pennies needed for the change. """ from pprint import pprint def calculate_change(price: float, paid: float) -> dict: """Return the optimal amount of currency to be given back as change.""" change_dictionary = { "one_hundred": 0, "fifty": 0, "twenty": 0, "ten": 0, "five": 0, "two": 0, "one": 0, "half": 0, "quarter": 0, "dime": 0, "nickel": 0, "penny": 0 } change = round(paid - price, 2) while change > 0: if round(change - 100.0, 2) >= 0: change = round(change - 100.0, 2) change_dictionary["one_hundred"] += 1 elif round(change - 50.0, 2) >= 0: change = round(change - 50.0, 2) change_dictionary["fifty"] += 1 elif round(change - 20.0, 2) >= 0: change = round(change - 20.0, 2) change_dictionary["twenty"] += 1 elif round(change - 10.0, 2) >= 0: change = round(change - 10.0, 2) change_dictionary["ten"] += 1 elif round(change - 5.0, 2) >= 0: change = round(change - 5.0, 2) change_dictionary["five"] += 1 elif round(change - 2.0, 2) >= 0: change = round(change - 2.0, 2) change_dictionary["two"] += 1 elif round(change - 1.0, 2) >= 0: change = round(change - 1.0, 2) change_dictionary["one"] += 1 elif round(change - 0.5, 2) >= 0: change = round(change - 0.5, 2) change_dictionary["half"] += 1 elif round(change - 0.25, 2) >= 0: change = round(change - 0.25) change_dictionary["quarter"] += 1 elif round(change - 0.1, 2) >= 0: change = round(change - 0.1, 2) change_dictionary["dime"] += 1 elif round(change - 0.05, 2) >= 0: change = round(change - 0.05) change_dictionary["nickel"] += 1 elif round(change - 0.01, 2) >= 0: change = round(change - 0.01, 2) change_dictionary["penny"] += 1 return change_dictionary def _start_interactively(): """Start the program interactively through the command line.""" while True: price = float(input("Please input the original price: ")) paid = float(input("Please input how much was paid: ")) pprint(calculate_change(price, paid)) print("") if __name__ == "__main__": _start_interactively()
08da510a25d46094341e4f32f926358d598672e1
legendronyang/python-exercise
/20160421_Convert.py
2,077
3.765625
4
#!/usr/bin/python # -*- coding: utf-8 -*- ''' 6. ZigZag Conversion https://leetcode.com/problems/zigzag-conversion/ ''' class Solution(object): def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ if numRows == 1: return s elif numRows == 2: rStr1, rStr2 = '', '' for i in range(len(s)): if i%2: rStr2 += s[i] else: rStr1 += s[i] return rStr1 + rStr2 else: length, indexList = len(s), [] for i in range(numRows): indexList.append([]) for i in range(1, length + 1): if i % (2 * numRows - 2) == 0: indexList[numRows - 1 - 1].append(i) elif i % (2 * numRows - 2) <= numRows : indexList[i % (2 * numRows - 2) - 1].append(i) else: indexList[i % (2 * numRows - 2) - numRows ].append(i) newList, rStr = [] , '' for i in range(len(indexList)): newList += indexList[i] for i in newList: rStr += s[i-1] return rStr def myUnitTest(self, s, n): return Solution.convert(self, s, n) mySolution = Solution() mySolution.convert("PAYPALISHIRING", 3) import unittest class Test_Solution_myUnitTest(unittest.TestCase): def test_myUnitTest(self): self.assertEqual(mySolution.myUnitTest("PAYPALISHIRING", 3), "PAHNAPLSIIGYIR") self.assertEqual(mySolution.myUnitTest("A", 1), "A") self.assertEqual(mySolution.myUnitTest("ABC", 2), "ACB") self.assertEqual(mySolution.myUnitTest("ABCDE", 3), "AEBDC") self.assertEqual(mySolution.myUnitTest("ABCDE", 4), "ABECD") suite = unittest.TestLoader().loadTestsFromTestCase(Test_Solution_myUnitTest) unittest.TextTestRunner(verbosity=2).run(suite)
b78199569f7449c4b35b7058bea56747cff4b079
anku255/fyle-backend-coding-test
/bankService/db/db_helpers.py
461
3.53125
4
import psycopg2 import os import psycopg2 from psycopg2.extras import NamedTupleCursor def connectToDB(): try: # Connect to an existing database conn = psycopg2.connect("dbname={} user={}".format( os.environ.get('DB_NAME'), os.environ.get('DB_USER'))) # Open a cursor to perform database operations cur = conn.cursor() return conn, cur except Exception as e: print("Some error occurred while connecting to the database")
c1246ebbc0ab665c7316d1f7f4c1f66deee484c2
axnessbatch/Srilatha
/large.py
138
3.625
4
a=[1,2,3,4,5] b=[] c=[] for x in a: if(x%2==0): b.append(x) else: c.append(x) print(b) print(c) print(b[-1]) print(c[-1])
0f986c9e5ab687a752298000176c992d8d7084e4
kkzh2313/python
/test3-从头到尾打印链表 (2).py
775
4.0625
4
#输入一个链表,从尾到头打印链表每个节点的值。 class Listnode: def __init__(self,x=None): self.val=x self.next=None class Solution: def printListFromTailToHead(self,listnode): if listnode.val == None: return None l=[] head=listnode while head : l.insert(0,head.val) ####insert方法将数值插入给定的位置 head=head.next return l node1=Listnode(10) node2=Listnode(11) node3 = Listnode(13) node1.next = node2 node2.next = node3 singleNode = Listnode(12) test = Listnode() S = Solution() print(S.printListFromTailToHead(node1)) print(S.printListFromTailToHead(test)) print(S.printListFromTailToHead(singleNode))
1054c23741242fb35d45143e10c1ceabb42d75f1
charshal12/my-python-project
/conditions.py
1,317
4.34375
4
# We use conditions for below few reasons # 1. Its should make sense(-negative output) # 2.The program should not get crashed # Conditionals # Equals: a == b # Not Equals: a != b # Less Than : a < b # Less Than or Equal To : a <= b # Greater Than: a > b # Greater Than or equal to : a >= b # By validating user input validation calculation_to_unit_1 = 24 name_of_unit_1 = "Hours" def days_to_unit_params(num_of_days): condition_check = num_of_days > 0 print(type(condition_check)) if num_of_days > 0: # evaluates condition in 'if' return f"{num_of_days} days are {num_of_days * calculation_to_unit_1} {name_of_unit_1}" # if positive , return this elif num_of_days == 0: return "You entered ZERO, please enter positive number!" def validate_and_execute(): if user_input.isdigit(): user_input_number = int(user_input) # -10(int data type) calculated_value = days_to_unit_params(user_input_number) # passes value into function print(calculated_value) else: print("Your number is not an input, Dont ruin my program!") user_input = input("Hey user, enter a number of day and it will be converted to hours!\n") # -10(string data type) validate_and_execute() # check the data type print(type(30.23)) print(type(9)) print(type("Hello!"))
0026327ddecf564fc36ff0cc51e3cf7bbaa71993
curow/Problem-Solving
/leetcode/55/backtracking.py
387
3.578125
4
from functools import lru_cache class Solution: def canJump(self, nums: List[int]) -> bool: final = len(nums) - 1 @lru_cache(maxsize=None) def jump(current_pos): if current_pos >= final: return True k = nums[current_pos] return any([jump(current_pos + i) for i in range(k, 0, -1)]) return jump(0)
c85f92929e97131cc1d15b7ed996957e4d253aae
Emiya2098212383/Lesson02-
/03-string.py
323
4.09375
4
# 练习三 print("-----华丽分割线-----") # 用户输入两串文字后合并输出 # 注:input() 返回一个字符串 text1 = input('输入第一串文本:') text2 = input('输入第二串文本:') # 求和 text3 = text1 + text2 # 显示计算结果 print ('新的字符串相加结果为:') print (text3)
e9bde898d9eb5a2d21a5d3996ba342b09082466a
Angel-cuba/Python-UDEMY
/seccion-3/op-logicos.py
599
4.1875
4
# #Operador not # print(not False) # #operador And # print(False and True) # #operador or # print(True or False) # #Example # c = "Python" # print(len(c)) # if len(c) > 8: # print('es mayor') # else: # print('es menor') print("Sistemas de becas") kilo = int(input("Cuanto kilometro para caminar hacia la escuela: ")) cantidad = int(input("Cuanto hay en la familia: ")) ingreso = int(input("Cantidad de dinero en la familia: ")) if kilo < 10 and cantidad < 3 and ingreso > 2000: print("Derecho a tener beca") else: print("No ha beca para ti")
b24da069d551b8a9b04fde4bd5893347dac7fae4
Matheuspaixaocrisostenes/Python
/ex005.py
146
3.984375
4
n = int(input(' digite um numero: ')) a = n - 1 s = n + 1 print(' analisando o valor {} seu antecessor é {} e seu sucessor é {}'.format(n,a,s))