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
2d8a39820a8626d45f71447343e9eadd4a6549c9
Jackiecoder/Leetcode
/Python/Stack/71. Simplify Path.py
1,294
3.515625
4
class Solution: def simplifyPath(self, path: str) -> str: stack = collections.deque() for p in path.split('/'): if p == '..': if stack: stack.pop() elif p and p != '.': stack.append(p) return '/' + '/'.join(stack) ''' # many / -> one / # if . between two /, skip it # if .. between two /, drop last directory # stack store path # if while /, i --> # name = a # if name == '.': do nothing # elif name == '..': pop stack # else: stack.append(name) # recover: '/' + '/'.join(stack) # time O(n), space O(n) stack = collections.deque() index = 0 n = len(path) while index < n: while index < n and path[index] == '/': index += 1 name = '' while index < n and path[index] != '/': name = name + path[index] index += 1 if name == '.': continue elif name == '..': if stack: stack.pop() elif name: stack.append(name) return '/' + '/'.join(stack) '''
3fa4ac89d0b1c5c42b63192edf2a277467a0fe99
zackhsi/venmo
/venmo/types.py
180
3.796875
4
''' Argument types ''' import argparse def positive_float(s): if float(s) <= 0: raise argparse.ArgumentTypeError('{} is not positive'.format(s)) return float(s)
24f1e3b64447a89da394208102c1f458ab32be89
Loukei/Python-notes
/comprehensions 推導式/comprehensions.py
1,363
4.65625
5
''' 整理各種python表達式,生成list set dict的技巧 itertools --- 为高效循环而创建迭代器的函数 https://docs.python.org/zh-cn/3/library/itertools.html ''' from typing import List # List comprehensions print([ i for i in range(10)]) ''' [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ''' print([i for i in range(10) if i % 2 == 1]) ''' 加入判斷式輸出 [1, 3, 5, 7, 9] ''' print([i*2 for i in range(10)]) ''' 輸出的資料不一定要與來源一樣 [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] ''' print([j for i in range(2, 8) for j in range(i*2, 50, i)]) ''' 等同以下效果 li:List[int] = [] for i in range(2,8): for j in range(i*2, 50, i): li.append(j) print(li) ''' print([(i,j) for i in range(5) for j in range(3)]) ''' (i,j)組成的list,i = 0-4,j = 0-2 ''' # Set print( {i for i in range(4)} ) ''' {0, 1, 2, 3} ''' print( {c for c in "Hallo world"} ) ''' {'o', ' ', 'l', 'a', 'd', 'w', 'H', 'r'} ''' print({x for x in 'abracadabra' if x not in 'abc'}) ''' {'d', 'r'} ''' # Dict mca = {'a':0,'b':1,'c':3,'d':5,'e':7} # print({v:k for k,v in mca.items()}) ''' 反轉mca的key與value {0: 'a', 1: 'b', 3: 'c', 5: 'd', 7: 'e'} ''' names = ['John','Peter','Hanry','Lilith','kurt'] print({k:names[k] for k in range(5)}) ''' 將list的值結合索引輸出新的dict {0: 'John', 1: 'Peter', 2: 'Hanry', 3: 'Lilith', 4: 'kurt'} '''
7094753de3ef5ec9bcf89cb26651d8adfcf246d1
kamdarkarnavee/CompetitiveCoding
/prefix_to_postfix.py
524
3.703125
4
def prefixtopostfix(prefixes): ans = [] for prestr in prefixes: postfix = [] for i in range(len(prestr)-1, -1, -1): current = prestr[i] if current != '+' and current != '-' and current != '*' and current != '/': postfix.append(current) else: op1 = postfix.pop() op2 = postfix.pop() postfix.append(op1+op2+current) ans.extend(postfix) return ans print(prefixtopostfix(['+23', '*4-34']))
716bf4babddfc29a5ac749a1e57bd379879bcf55
GregYoung-Python/Cinema-Theater
/cinema_project.py
970
4.03125
4
movies = { "Lost Ark": [10,3], "Star Wars": [10,3], "Buster Scruggs": [18,3], "Nemo": [10,3], "Miami Vice": [18,3], "Bat Man": [18,3] } while True: choice = input("What movie would you like to watch?: ").strip().title() if choice in movies: age = int(input("What is your age?: ").strip()) if age >= movies[choice][0]: num_seats = movies[choice][1] if num_seats > 0: print("Enjoy the movie!") movies[choice][1] = movies[choice][1] -1 else: print("Sorry we are sold out at this time, please try later!") else: print("Sorry you are not old enough to see this movie!") else: print("Sorry we don't have that movie!")
969d25701495362d1d1e8a8c1fecdf2704aeb6ba
stepanLys/algoritms_sa31
/2/search_chars.py
673
3.828125
4
#! /usr/bin/env python # charset: utf-8 import os MB = 104857600 def wordIndex(s, n): string = ' '.join(str(x) for x in s[:n-1]) length = len(string) return ('In this string - \t ' + string + ' \t\n ' + str(length) + ' chars') def main(): f = open('big.txt', 'r') file = f.read().split(' ') index = int(input('Please, input word index: ')) file_size = os.path.getsize(f.name) # print(file_size, MB) if file_size <= MB and index <= len(file) and index > 0 and len(file) > 0: print(wordIndex(file, index)) else: print('Error!!!') f.close() if __name__ == '__main__': main()
10f8c28fc8328f8e169bce5c3105b5bac7279459
ThallesTorres/Curso_Em_Video_Python
/Curso_Em_Video_Python/ex043.py
1,065
4.0625
4
# Ex: 043 - Desenvova uma lógica que leia o peso e a altura de uma pessoa, # calcule seu IMC e mostre seu status, de acordo com a tabela abaixo: # Abaixo de 18.5 - Abaixo do Peso, Entre 18.5 e 25 - Peso Ideal, # 25 até 30 - Sobrepeso, 30 até 40 - Obesidade, Acima de 40 - Obesidade Mórbida. print(''' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- --Seja bem-vindo! --Exercício 043 -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ''') print('--Calculo IMC') print('--Preencha os Dados') peso = float(input('Peso (Kg): ')) altura = float(input('Altura (m): ')) imc = peso / altura ** 2 if imc < 18.5: categoria = 'abaixo do peso' elif imc < 25: categoria = 'peso ideal' elif imc < 30: categoria = 'sobrepeso' elif imc < 40: categoria = 'obesidade' else: categoria = 'obesidade mórbida' print('') print(f'IMC: {imc:.1f}\n' f'Categoria: {categoria.capitalize()}') print(''' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- --Obrigado pelo uso! --Desenvolvido por Thalles Torres -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
318b8481d81889780e6a5c67e17ce1a5e023699a
DmitriChe/pydev_hw2
/variables.py
1,412
3.640625
4
# (МОДУЛЬ 1) # 1. В проекте создать новый модуль variables.py # 2. Выбрать объект для описания из списка: овощ, еда, сотрудник, игрушка (так же можно придумать свой) # 3. Объявить переменные основных типов данных для описания этого объекта: # Например объект школьник: # имя (тип строка), возраст (тип целое число), класс (тип целое число), отличник или нет (логический тип) # Минимально 4 переменные для типов (строка, число, число с плавающей точкой, логический тип) # 4. В конце модуля с помощью функции type вывести тип для каждой из объявленных переменных animal = 'snake' is_dangerous = True length = 13.5 name = 'Anaconda' weight = 200 legs = 0 areal = ['Brazil', 'Venezuela', 'Paraguay', 'Uruguay', 'Bolivia'] print(f'animal_type is {type(animal)}') print(f'is_dangerous_type is {type(is_dangerous)}') print(f'length_type is {type(length)}') print(f'name_type is {type(name)}') print(f'weight_type is {type(weight)}') print(f'legs_type is {type(legs)}') print(f'areal_type is {type(areal)}')
952468efa74f39b827e406b3e1a73467d2b9be38
shivamvku/class_8000
/ex1.py
887
3.65625
4
# l = [1,2,3,4,5,6,7,8,9,10] # a = [[1,2],[3,4]] # b = [[4,5],[6,7]] # # sum= [5,7,9,11] # # a[0][0]+b[0][0] ==== 5 # # a[0][1]+b[0][1]====== 7 # # a[1][0]+b[1][0] ====== 9 # # a[1][1]+b[1][1] === 11 # c =[] # for i in range(len(a)): # for j in range(len(a[i])): # s = (a[i][j]+b[i][j]) # c.append(s) # print(c) # a = (1,2,3,4) # print(a.index(4)) # genrator objects # packeing of tuple # t = [a for a in range(0,11)] # print(t) # t = (a for a in range(0,11)) # print(t) # print(next(t)) # print(next(t)) # print(next(t)) # print(next(t)) # for a in t: # print(a) # enumerator # ================== # enumerate()-------------- enumerator object it contais the tuple of index nuber and value at that index l = ['apple','Nokia','samsung'] enum = enumerate(l) print(type(enumerate)) # print(enum) # print(next(enum)) # for a in enum: # print(a) print([a for a in enum])
60dd173a7403b8610c303fabc1a4c9b723b0aead
Coalin/Daily-LeetCode-Exercise
/82_Remove-Duplicates-From-Sorted-Lists-II.py
1,606
3.8125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ exist = [] dup = [] new_head = ListNode(0) new_head.next = head pre = new_head while head: if head.val in exist: dup.append(head.val) else: exist.append(head.val) head = head.next cur = pre.next new_head.next = cur while cur: if cur.val in dup: pre.next = cur.next else: pre = cur cur = cur.next return new_head.next # 第一次提交出错的原因: # 第二个while中仍使用了head,而head早已走到了最后 # 20220326 Exercise # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: if not head: return head dummy = ListNode(0) dummy.next = head cur = dummy while cur.next and cur.next.next: if cur.next.val == cur.next.next.val: x = cur.next.val while cur.next and cur.next.val == x: cur.next = cur.next.next else: cur = cur.next return dummy.next
a2d55ebb81ba64e5d26ec69cbd68f450515782f8
Ham1dul/Learning-Python
/fraction_oop_overloading/OOP_Fractions.py
1,909
3.84375
4
# -*- coding: utf-8 -*- """ Created on Sat Mar 25 20:02:51 2017 @author: Hamidul """ class fraction(object): """ number represented as fraction""" def __init__(self, num, denom): """ initialize as number , denominatior""" assert type(num) == int and type(denom) == int self.num = num self.denom = denom def __str__(self): """returns fraction string""" return str(self.num) + '/' + str(self.denom) def __add__(self, other): """ add fraction by criss cross mult then add for top strait mult for bottom""" top = self.num * other.denom + self.denom * other.num bott = self.denom * other.denom return fraction(top,bott) def __sub__(self,other): """ sub frac by criss cross mult then add for top straight mult for bottom""" top = self.num*other.denom - self.denom*other.num bott = self.denom*other.denom return fraction (top,bott) def __mul__(self,other): """multiplies fraction""" top = self.num*other.num bott = self.num*other.num return fraction(top,bott) def __truediv__(self,other): """divide self by other""" top = self.num*other.denom bott = self.denom*other.num return fraction(top,bott) def __float__(self): """convert number to float""" return self.num/self.denom def inverse(self): """num and denom""" return fraction(self.denom,self.num) fraction_x = fraction(1,2) fraction_y = fraction(1,4) print(fraction_x) #initialize print(fraction_y) print(fraction_x-fraction_y) #subtract print(fraction_x+fraction_y) #add print(fraction_x*fraction_y) #mult print(float(fraction_x)) #convert print(fraction_x.inverse()) #inverse print(fraction_x / fraction_y) #divide
0d2b8cbc266cbc5d77c7ab677a7c49b42a6c8efb
MichaelAuditore/prime_code
/permutations2.py
843
4.09375
4
#!/usr/bin/python3 import itertools """ Modulo con una funcion que permite imprimir todas las permutaciones entre 1 y un digito dado """ def print_permutations(perm): """imprime las permutaciones como str""" for p in perm: if p is not perm[len(perm) - 1]: print(''.join([str(n) for n in p]), end=",") else: print(''.join([str(n) for n in p])) def get_permutations(number): """ Metodo que obtiene todas las permutaciones posibles entre 1 y el numero ingresado. """ if number > 0 and number < 10: my_list = [i for i in range(1, number + 1)] permutations = list(itertools.permutations(my_list, len(my_list))) print_permutations(permutations) else: print("Ingrese un numero entre 1 y 9") if __name__ == "__main__": get_permutations(4)
54d72107164d05ceccf625a683a6ff7b7777fae2
AmigaTi/Python3Learning
/builtins/bins-modules/bins-datetime.py
7,111
3.546875
4
#!/usr/bin/python # -*- coding: utf-8 -*- import re import time from datetime import datetime, timedelta, timezone # 获取当前日期和时间 # 注意到datetime是模块,datetime模块还包含一个datetime类, # 通过from datetime import datetime导入的才是datetime这个类 # 如果仅导入import datetime,则必须引用全名datetime.datetime now = datetime.now() print(now) # 2016-08-25 01:10:22.345052 print(type(now)) # <class 'datetime.datetime'> print('------------------------------------------') # 获取指定日期和时间 # 用指定日期时间创建datetime dt = datetime(2016, 8, 25, 1, 16) print(dt) # 2016-08-25 01:16:00 print('------------------------------------------') # datetime转换为timestamp # 在计算机中,时间实际上是用数字表示的。 # 我们把1970年1月1日 00:00:00 UTC+00:00时区的时刻称为epoch time, # 记为0(1970年以前的时间timestamp为负数), # 当前时间就是相对于epoch time的秒数,称为timestamp。 # 可以认为: # timestamp = 0 = 1970-1-1 00:00:00 UTC+0:00 # 对应的北京时间为: # timestamp = 0 = 1970-1-1 08:00:00 UTC+8:00 # timestamp的值与时区毫无关系 # 计算机存储的当前时间是以timestamp表示的, # 因为全球各地的计算机在任意时刻的timestamp都是完全相同的(假定时间已校准) dt = datetime(2016, 8, 25, 1, 16) ts = dt.timestamp() # 把datetime转换为timestamp print(ts) # 1472058960.0 print('------------------------------------------') # timestamp转换为datetime # 要把timestamp转换为datetime,使用datetime提供的fromtimestamp()方法 # timestamp是一个浮点数,没有时区的概念,而datetime是有时区的 # 格林威治标准时间与北京时间差了8小时 ts = 1472058960.0 dt = datetime.fromtimestamp(ts) # 本地时间,即北京东八区时区时间 print(dt) # 2016-08-25 01:16:00 dt = datetime.utcfromtimestamp(ts) # UTC标准时区的时间 print(dt) # 2016-08-24 17:16:00 print('------------------------------------------') # str转换为datetime # 注意转换后的datetime是没有时区信息的 +++准确地说时区默认为本地 date_str = '2016-8-25 01:16:16' format_str = '%Y-%m-%d %H:%M:%S' dt = datetime.strptime(date_str, format_str) print('str -> datetime') print(dt) # 2016-08-25 01:16:16 t = time.gmtime(time.time()) print(t) # China Standard Time ''' time.struct_time(tm_year=2018, tm_mon=5, tm_mday=6, tm_hour=19, tm_min=41, tm_sec=23, tm_wday=6, tm_yday=126, tm_isdst=0) ''' # ------------------------------------------------- date_str = 'Wed, 27 May 2015 11:00 am CST'[:-4] # 去掉CST时区信息 format_str = r'%a, %d %b %Y %I:%M %p' # %Z无法正确解析 dt = datetime.strptime(date_str, format_str) print(dt) # 2015-05-27 11:00:00 print(dt.day) # 27 print(dt.tzname()) # None print('------------------------------------------') # datetime转换为str now = datetime.now() format_str = '%a, %b %d %H:%M' dt = now.strftime(format_str) print(dt) # Thu, Aug 25 01:35 print('------------------------------------------') # datetime加减 # 对日期和时间进行加减实际上就是把datetime往后或往前计算, # 得到新的datetime。加减可以直接用+和-运算符, # 不过需要导入timedelta这个类 now = datetime.now() print(now) # 2016-08-25 01:38:30.323599 now = now + timedelta(hours=10) print(now) # 2016-08-25 11:38:30.323599 now = now - timedelta(days=1) print(now) # 2016-08-24 11:38:30.323599 now = now + timedelta(days=2, hours=12) print(now) # 2016-08-26 23:38:30.323599 print('------------------------------------------') # 本地时间转换为UTC时间 # 本地时间是系统设定时区的时间 # 北京时间是UTC+8:00时区的时间 # UTC时间是UTC+0:00时区的时间 tz_utc_8 = timezone(timedelta(hours=8)) # 创建时区UTC+8:00 now = datetime.now() print(now) # 2016-09-05 16:14:18.856846 print(now.timestamp()) # 1473063258.856846 dt = now.replace(tzinfo=tz_utc_8) # 强制设置为UTC+8:00 print(dt) # 2016-09-05 16:14:18.856846+08:00 print(dt.timestamp()) # 1473063258.856846 print('------------------------------------------') # 时区转换 # 以先通过utcnow()拿到当前的UTC时间, # 再转换为任意时区的时间 # 时区转换的关键在于,拿到一个datetime时, # 要获知其正确的时区,然后强制设置时区,作为基准时间。 # 利用带时区的datetime,通过astimezone()方法,可以转换到任意时区。 # 注:不是必须从UTC+0:00时区转换到其他时区, # 任何带时区的datetime都可以正确转换,例如peking_dt到tokyo_dt的转换。 # 拿到UTC时间,并强制设置时区为UTC+0:00 utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc) print(utc_dt) # 2016-08-24 17:50:44.691602+00:00 # astimezone()将转换时区为北京时间 peking_dt = utc_dt.astimezone(timezone(timedelta(hours=8))) print(peking_dt) # 2016-08-25 01:50:44.691602+08:00 # astimezone()将转换时区为东京时间 tokyo_dt = utc_dt.astimezone(timezone(timedelta(hours=9))) print(tokyo_dt) # 2016-08-25 02:50:44.691602+09:00 # astimezone()将peking_dt转换时区为东京时间 tokyo_dt2 = peking_dt.astimezone(timezone(timedelta(hours=9))) print(tokyo_dt2) # 2016-08-25 02:50:44.691602+09:00 print('======================================') # ====================================================== # 一个datetime类型有一个时区属性tzinfo,但是默认为None, # 所以无法区分这个datetime到底是哪个时区, # 除非强行给datetime设置一个时区 # 假设获取了用户输入的日期和时间如2015-1-21 9:01:30, # 以及一个时区信息如UTC+5:00,均是str, # 编写一个函数将其转换为timestamp def to_timestamp(dt_str, tz_str): dt = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S') # 默认时区属性为None或者说为本地 m = re.match(r'^UTC([-|+]\d{1,2}):\d{2}$', tz_str) # 创建匹配对象,并设置提取的分组 tz_utc_x = timezone(timedelta(hours=int(m.group(1)))) # 创建UTC X:00时区 dt = dt.replace(tzinfo=tz_utc_x) # 将dt强制设置为UTC X:00时区 return dt.timestamp() # 把datetime转换为timestamp # 测试 print('Get the testing result: ') t1 = to_timestamp('2015-6-1 08:10:30', 'UTC+7:00') assert t1 == 1433121030.0, t1 t2 = to_timestamp('2015-5-31 16:10:30', 'UTC-09:00') assert t2 == 1433121030.0, t2 print('Pass') ''' Get the testing result: Pass '''
6e91099259b3af86fbd9ac3929a6099334040e21
barrysheppard/B8IT105-CA5
/calculator.py
5,075
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Description : This includes functions for a calculator # Author : Barry Sheppard - Student Number 10387786 # Date : 20181110 # Version : 0.1 # Notes : For CA5. Updated from CA1 # Python version : 3.6.5 ############################################################################### # The math module is used for mathematical functions and math.pi import math # numbers is used to get the number.Real object type for comparison import numbers # For reduce function from functools import reduce def CheckIsNumber(input): return isinstance(input, numbers.Real) def Add(first, second=0): ''' This returns the multiplication of two or more numbers ''' if type(first) == list: return reduce(lambda x, y: x+y, first) if (isinstance(first, numbers.Real) and isinstance(second, numbers.Real)): return first + second raise TypeError('The Add function only takes numbers') def CosineDegrees(first): ''' This returns the cosine of one or more numbers in degrees''' if type(first) == list: return list(map(lambda x: math.cos(x*(math.pi / 180)), first)) if isinstance(first, numbers.Real): return math.cos(first*(math.pi / 180)) raise TypeError('The Cosine function only takes numbers') def Cube(first): ''' This returns the first number cubed ''' if type(first) == list: return list(map(lambda x: x ** 3, first)) if isinstance(first, numbers.Real): return first ** 3 raise TypeError('The Cube function only takes numbers') def Divide(first, second=1): ''' Returns the first number divided one or more numbers sequentially ''' if type(first) == list: return reduce(lambda x, y: x/y, first) if (isinstance(first, numbers.Real) and isinstance(first, numbers.Real)): if second == 0: raise ZeroDivisionError('Cannot divide by Zero') return first / second raise TypeError('The Divide function only takes numbers') def Exponent(first, second=1): ''' Returns first number to the power one or more numbers sequentially ''' if type(first) == list: return reduce(lambda x, y: x ** y, first) if (isinstance(first, numbers.Real) and isinstance(first, numbers.Real)): return first ** second raise TypeError('The Exponent function only takes numbers') def Multiply(first, second=1): ''' This returns the multiplication of one or more numbers ''' if type(first) == list: return reduce(lambda x, y: x * y, first) if (isinstance(first, numbers.Real) and isinstance(first, numbers.Real)): return first * second raise TypeError('The Multiply function only takes numbers') def SineDegrees(first): ''' This returns the sine of the input number in degrees''' if type(first) == list: return list(map(lambda x: math.sin(x*(math.pi / 180)), first)) if isinstance(first, numbers.Real): return math.sin(first*(math.pi / 180)) raise TypeError('The SineDegrees function only takes numbers') def SquareRoot(first): ''' This the square root of one or more numbers ''' if type(first) == list: return list(map(lambda x: math.sqrt(x), first)) if isinstance(first, numbers.Real): return math.sqrt(first) raise TypeError('The SquareRoot function only takes numbers') def Square(first): ''' This returns square of one or more numbers ''' if type(first) == list: return list(map(lambda x: x ** 2, first)) if isinstance(first, numbers.Real): return first ** 2 raise TypeError('The Square function only takes numbers') def Subtract(first, second=1): ''' This returns the first number less one ore more numbers ''' if type(first) == list: return reduce(lambda x, y: x - y, first) if isinstance(first, numbers.Real): return first - second raise TypeError('The Subtract function only takes numbers') def TangentDegrees(first): ''' This returns the tangent of the input number in degrees This will raise a ZeroDivisionError for angles of 90 or 270 ''' # Tan of 90 or 270 degrees will result in an error # This also applies to angles larger than 360 + 90 etc, so we need to use # the modulus for the remainder. # As the conversion to radians isn't exact due to the computer not # having an exact number for pi, the check needs to be in place to avoid # the code returning the tan for a value very close to 90 or 270 degrees # Without this check, the math.tan function will return a result that is # very high as a number very close to 90 or 270 degress will have a result. if type(first) == list: return list(map(lambda x: math.tan(x*(math.pi / 180)), first)) if isinstance(first, numbers.Real): if first % 360 in [90, 270]: raise ZeroDivisionError('Tan of 90 or 270 are undefined') return math.tan(first*(math.pi / 180)) raise TypeError('The TangentDegrees function only takes numbers')
80388f252fc35105d77d13a460d02e319ae657de
abhisheksahu92/Programming
/Solutions/anagram.py
1,373
3.640625
4
def funWithAnagrams(text): #Solution 1 d = {} for x in text: temp = ''.join(sorted(x.lower())) if temp not in d.keys(): d[temp] = [x] else: d[temp].append(x) for k,v in d.items(): if len(v) > 1: print(v) #Solution 2 # d = {} # a = [] # for x in text: # s = ''.join(sorted(list(x))) # if s not in d.keys(): # d[s] = '' # a.append(x) # a.sort() # print(a) #Solution 3 # x = 0 # y = 1 # while True: # if x < len(text): # if y < len(text): # print(text[x].lower(),text[y].lower()) # if sorted(text[x].lower()) == sorted(text[y].lower()): # text.remove(text[y]) # else: # y = y + 1 # else: # x = x + 1 # y = x + 1 # else: # print(sorted(text)) # break if __name__ == '__main__': # ['code','aaagmnrs','anagrams','doce'],['poke','pkoe','okpe','ekop'] list_of_values = [['If', 'input', 'is', 'string', 'Hello', 'then', 'string', 'combinations', 'like', 'lleHo', 'LLehO', 'should', 'be', 'considered', 'as', 'anagram']] for li in list_of_values: print(f'Input is {li}') funWithAnagrams(li)
25816c1922a80a827396548486e7598a70727529
Xenia-Io/DD2424-Deep_Learning
/Assignment_4/rnn/main.py
11,011
3.6875
4
""" Created by Xenia-Io @ 2021-05-03 Implementation of a vanilla recurrent neural network to synthesize English text character by character. Assignment 4 of the DD2424 Deep Learning in Data Science course at KTH Royal Institute of Technology """ from collections import OrderedDict import matplotlib.pyplot as plt import numpy as np import random class DataLoader(): """A class that loads and process the dataset""" def __init__(self, filename): """Load the dataset Args: filename (str): filename of the text to be loaded """ self.filename = filename def load_dataset(self): """Load a text file and preprocess it for the RNN model Returns: data (dict) with the following columns: - book_data : the text as a long string (str) - book_chars : dict of unique characters in the text (book_data) - vocab_len : vocabulary size - char_to_ind : mapping of characters to indices - ind_to_char : mapping of indices to characters """ book_data = open(self.filename, 'r', encoding='utf8').read() book_chars = list(set(book_data)) data = {"book_data": book_data, "book_chars": book_chars, "vocab_len": len(book_chars), "char_to_ind": OrderedDict((char, idx) for idx, char in enumerate(book_chars)), "ind_to_char": OrderedDict((idx, char) for idx, char in enumerate(book_chars))} return data class RNN(): """A vanilla RNN model""" def __init__(self, data, m=100, eta=0.1, seq_length=25, sigma= 0.01): """ Build the RNN model Args: b (np.ndarray) : bias vector of length (m x 1) c (np.ndarray) : bias vector of length (K x 1) U (np.ndarray) : input-to-hidden weight matrix of shape (m x K) V (np.ndarray) : hidden-to-output weight matrix of shape (K x m) W (np.ndarray) : hidden-to-hidden weight matrix of shape (m x m) m (int) : dimensionality of hidden state eta (float) : learning rate seq_length(int) : the length of the sequence that the model uses to traverse the text data (dict) : get info from the loaded text file """ self.m, self.eta, self.seq_length = m, eta, seq_length self.vocab_len = data['vocab_len'] self.ind_to_char = data['ind_to_char'] self.char_to_ind = data['char_to_ind'] self.book_data = data['book_data'] self.b = np.zeros((m, 1)) self.c = np.zeros((self.vocab_len, 1)) self.U = np.random.normal(0, sigma, size=(m, self.vocab_len)) self.W = np.random.normal(0, sigma, size=(m, m)) self.V = np.random.normal(0, sigma, size=(self.vocab_len, m)) def compute_softmax(self, x): e = x - np.max(x) return np.exp(e) / np.sum(np.exp(e), axis=0) def evaluate_classifier(self, h, x): """ Forward-pass of the classifier Args: h (np.ndarray): hidden state sequence X (np.ndarray): sequence of input vectors, where each x has size (dx1) Returns: a (np.ndarray): linear transformation of W and U + bias b h (np.ndarray): tanh activation of a o (np.ndarray): linear transformation of V + bias c p (np.ndarray): softmax activation of o """ a = np.matmul(self.W, h) + np.matmul(self.U, x) + self.b h = np.tanh(a) o = np.matmul(self.V, h) + self.c p = self.compute_softmax(o) return a, h, o, p def synthesize_text(self, h, ix, n): """ Generate text based on the hidden state sequence Input vectors are one-hot-encoded Args: n (int) : length of the sequence to be generated h0 (np.ndarray) : hidden state at time 0 idx (np.ndarray) : index of the first dummy input vector Returns: text (str): a synthesized string of length n """ # The next input vector xnext = np.zeros((self.vocab_len, 1)) # Use the index to set the net input vector xnext[ix] = 1 # 1-hot-encoding txt = '' for t in range(n): _, h, _, p = self.evaluate_classifier(h, xnext) # At each time step t when you generate a # vector of probabilities for the labels, # you then have to sample a label from this PMF ix = np.random.choice(range(self.vocab_len), p=p.flat) xnext = np.zeros((self.vocab_len, 1)) xnext[ix] = 1 # Lecture 9, page 22 txt += self.ind_to_char[ix] return txt def compute_gradients(self, inputs, targets, hprev): """ Analytically computes the gradients of the weight and bias parameters """ n = len(inputs) loss = 0 # Dictionaries for storing values during the forward pass aa, xx, hh, oo, pp = {}, {}, {}, {}, {} hh[-1] = np.copy(hprev) # Forward pass for t in range(n): xx[t] = np.zeros((self.vocab_len, 1)) xx[t][inputs[t]] = 1 # 1-hot-encoding aa[t], hh[t], oo[t], pp[t] = self.evaluate_classifier(hh[t-1], xx[t]) loss += -np.log(pp[t][targets[t]][0]) # update the loss # Dictionary for storing the gradients grads = {"W": np.zeros_like(self.W), "U": np.zeros_like(self.U), "V": np.zeros_like(self.V), "b": np.zeros_like(self.b), "c": np.zeros_like(self.c), "o": np.zeros_like(pp[0]), "h": np.zeros_like(hh[0]), "h_next": np.zeros_like(hh[0]), "a": np.zeros_like(aa[0])} # Backward pass for t in reversed(range(n)): grads["o"] = np.copy(pp[t]) grads["o"][targets[t]] -= 1 grads["V"] += grads["o"]@hh[t].T grads["c"] += grads["o"] grads["h"] = np.matmul(self.V.T , grads["o"] )+ grads["h_next"] grads["a"] = np.multiply(grads["h"], (1 - np.square(hh[t]))) grads["U"] += np.matmul(grads["a"], xx[t].T) grads["W"] += np.matmul(grads["a"], hh[t-1].T) grads["b"] += grads["a"] grads["h_next"] = np.matmul(self.W.T, grads["a"]) # Drop redundant gradients grads = {k: grads[k] for k in grads if k not in ["o", "h", "h_next", "a"]} # Clip the gradients for grad in grads: grads[grad] = np.clip(grads[grad], -5, 5) # Update the hidden state sequence h = hh[n-1] return grads, loss, h def compute_gradients_num(self, inputs, targets, hprev, h, num_comps=20): """ Numerically computes the gradients of the weight and bias parameters """ rnn_params = {"W": self.W, "U": self.U, "V": self.V, "b": self.b, "c": self.c} num_grads = {"W": np.zeros_like(self.W), "U": np.zeros_like(self.U), "V": np.zeros_like(self.V), "b": np.zeros_like(self.b), "c": np.zeros_like(self.c)} for key in rnn_params: for i in range(num_comps): old_par = rnn_params[key].flat[i] # store old parameter rnn_params[key].flat[i] = old_par + h _, l1, _ = self.compute_gradients(inputs, targets, hprev) rnn_params[key].flat[i] = old_par - h _, l2, _ = self.compute_gradients(inputs, targets, hprev) rnn_params[key].flat[i] = old_par # reset parameter to old value num_grads[key].flat[i] = (l1 - l2) / (2*h) return num_grads def check_gradients(self, inputs, targets, hprev, num_comps=20): """ Check similarity between the analytical and numerical gradients """ grads_ana, _, _ = self.compute_gradients(inputs, targets, hprev) grads_num = self.compute_gradients_num(inputs, targets, hprev, 1e-5) print("Gradient checks:") for grad in grads_ana: num = abs(grads_ana[grad].flat[:num_comps] - grads_num[grad].flat[:num_comps]) denom = np.asarray([max(abs(a), abs(b)) + 1e-10 for a,b in zip(grads_ana[grad].flat[:num_comps], grads_num[grad].flat[:num_comps]) ]) max_rel_error = max(num / denom) print("The maximum relative error for the %s gradient is: %e." % (grad, max_rel_error)) print() def main(): # Book position tracker, iteration, epoch e, n, epoch = 0, 0, 0 num_epochs = 30 smooth_loss_lst = [] # Load dataset loader = DataLoader("goblet_book.txt") data = loader.load_dataset() # Build model rnn = RNN(data) rnn_params = {"W": rnn.W, "U": rnn.U, "V": rnn.V, "b": rnn.b, "c": rnn.c} mem_params = {"W": np.zeros_like(rnn.W), "U": np.zeros_like(rnn.U), "V": np.zeros_like(rnn.V), "b": np.zeros_like(rnn.b), "c": np.zeros_like(rnn.c)} while epoch < num_epochs: # Re-initialization if n == 0 or e >= (len(rnn.book_data) - rnn.vocab_len - 1): if epoch != 0: print("Finished %i epochs." % epoch) hprev = np.zeros((rnn.m, 1)) e = 0 epoch += 1 inputs = [rnn.char_to_ind[char] for char in rnn.book_data[e:e+rnn.vocab_len]] targets = [rnn.char_to_ind[char] for char in rnn.book_data[e+1:e+rnn.vocab_len+1]] grads, loss, hprev = rnn.compute_gradients(inputs, targets, hprev) # Compute the smooth loss if n == 0 and epoch == 1: smooth_loss = loss smooth_loss = 0.999 * smooth_loss + 0.001 * loss smooth_loss_lst.append(smooth_loss) # Check gradients if n == 0: rnn.check_gradients(inputs, targets, hprev) # Print the loss if n % 100 == 0: print('Iteration %d, smooth loss: %f' % (n, smooth_loss)) # Print synthesized text if n % 500 == 0: txt = rnn.synthesize_text(hprev, inputs[0], 200) print('\nSynthesized text after %i iterations:\n %s\n' % (n, txt)) print('Smooth loss: %f' % smooth_loss) # Adagrad for key in rnn_params: mem_params[key] += grads[key] * grads[key] rnn_params[key] -= rnn.eta / np.sqrt(mem_params[key] + np.finfo(float).eps) * grads[key] e += rnn.vocab_len n += 1 # Plot smooth loss plt.plot(smooth_loss_lst) plt.ylabel('Smooth Loss') plt.xlabel('Iterations') plt.show() if __name__ == '__main__': main()
fc4dec58daf28aa215cf52c26bff149d3f666a07
Jeuro/itcc
/exercises/genetic/deap_tutorial_itcc.py
6,613
4.09375
4
'''DEAP example. We try to evolve a list of digits to match a target list of digits, that represents a date. ''' import random from deap import algorithms from deap import base from deap import creator from deap import tools # Date, a target which we want to evolve. #target = [2, 4, 0, 9, 2, 0, 1, 5] target = [0, 1] * 200 # Our evaluation function def eval(individual): '''Evaluate individual. The closer the individual is to the target, the better the fitness. ''' fit = 0 for i in range(len(individual)): fit = fit + abs(individual[i] - target[i]) # Evaluation function has to return a tuple, even if there is only one # evaluation criterion (thats why there is a comma). return fit, def eval2(individual): fit = 0 for i in range(len(individual)): if individual[i] == target[i]: fit += 1 return fit, # We create a fitness for the individuals, because our eval-function gives us # "better" values the closer they are zero, we will give it weight -1.0. # This creates a class creator.FitnessMin(), that is from now on callable in the # code. (Think about Java's factories, etc.) creator.create("FitnessMax", base.Fitness, weights=(1.0,)) # We create a class Individual, which has base type of list, it also uses our # just created creator.FitnessMin() class. creator.create("Individual", list, fitness=creator.FitnessMax) # We create DEAP's toolbox. Which will contain our mutation functions, etc. toolbox = base.Toolbox() # We create a function named 'random_digit', which calls random.randint # with fixed parameters, i.e. calling toolbox.random_digit() is the same as # calling random.randint(0, 9) #toolbox.register('random_digit', random.randint, 0, 9) toolbox.register('random_digit', random.randint, 0, 1) # Now, we can make our individual (genotype) creation code. Here we make the function to create one instance of # creator.Individual (which has base type list), with tools.initRepeat function. tool.initRepeat # calls our just created toolbox.random_digit function n-times, where n is the # length of our target. This is about the same as: [random.randint(0,9) for i in xrange(len(target))]. # However, our created individual will also have fitness class attached to it (and # possibly other things not covered in this example.) #toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.random_digit, n = len(target)) toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.random_digit, n = len(target)) # As we now have our individual creation code, we can create our population code # by making a list of toolbox.individual (which we just created in last line). # Here it is good to know, that n (population size), is not defined at this time # (but is needed by the initRepeat-function), and can be altered when calling the # toolbox.population. This can be achieved by something called partial functions, check # https://docs.python.org/2/library/functools.html#functools.partial if interested. toolbox.register("population", tools.initRepeat, list, toolbox.individual) # We register our evaluation function, which is now callable as toolbox.eval(individual). toolbox.register("evaluate", eval2) # We use simple selection strategy where we select only the best individuals, # now callable in toolbox.select. toolbox.register("select", tools.selBest) def crossover(a, b): i = random.randint(0, len(a)-1) temp = a[:i+1] a[:i+1] = b[:i+1] b[:i+1] = temp return a, b # We use one point crossover, now callable in toolbox.mate. toolbox.register("mate", crossover) #toolbox.register("mate", tools.cxOnePoint) # We define our own mutation function which replaces one index of an individual # with random digit. def mutate(individual): i = random.randint(0, len(individual)-1) individual[i] = toolbox.random_digit() # DEAP's mutation function has to return a tuple, thats why there is comma # after. return individual, def mutate2(individual): i = random.randint(0, len(individual)-1) new_value = random.choice((individual[i] + 1, individual[i] - 1)) if new_value > 9: individual[i] = 0 elif new_value < 0: individual[i] = 9 else: individual[i] = new_value # DEAP's mutation function has to return a tuple, thats why there is comma # after. return individual, def mutate3(individual): for i in individual: if random.random() < 0.05: if individual[i] == 0: individual[i] = 1 else: individual[i] = 0 return individual, # We register our own mutation function as toolbox.mutate toolbox.register("mutate", mutate3) # Now we have defined basic functions with which the evolution algorithm (EA) can run. # Next, we will define some parameters that can be changed between the EA runs. # Maximum amount of generations for this run generations = 300 # Create population of size 100 (Now we define n, which was missing when we # registered toolbox.population). pop = toolbox.population(n=300) # Create hall of fame which stores only the best individual hof = tools.HallOfFame(1) # Get some statistics of the evolution at run time. These will be printed to # sys.stdout when the algorithm is running. import numpy as np stats = tools.Statistics(lambda ind: ind.fitness.values) stats.register("avg", np.mean) stats.register("std", np.std) stats.register("min", np.min) stats.register("max", np.max) # Probability for crossover crossover_prob = 0.5 # Probability for mutation mutation_prob = 0.5 # Call our actual evolutionary algorithm that runs the evolution. # eaSimple needs toolbox to have 'evaluate', 'select', 'mate' and 'mutate' # functions defined. This is the most basic evolutionary algorithm. Here, we # have crossover probability of 0.7, and mutation probability 0.2. algorithms.eaSimple(pop, toolbox, crossover_prob, mutation_prob, generations, stats, halloffame=hof) # Print the best individual, and its fitness print(hof[0], eval2(hof[0])) #fit = [] #for _ in xrange(100): # algorithms.eaSimple(pop, toolbox, crossover_prob, mutation_prob, generations, stats, halloffame=hof) # Print the best individual, and its fitness #print hof[0], eval(hof[0]) # fit.append(eval(hof[0])[0]) #print "Average fitness", sum(fit) / float(len(fit)) import numpy as np #ar = np.asarray(target) ar = np.asarray(hof[0]) img = ar.reshape((20,20)) img[img == 1] = 255 # change each 1 to 255 from skimage import io io.imsave('ga_array.png', img)
3af5f6a1b3b6dfa25e8c154f3e7a99e6d499713a
ugurcan-sonmez-95/HackerRank
/Algorithms/Warmup/Time_Conversion/main.py
363
4.09375
4
### Time Conversion - Solution def timeConversion(hour): if (hour[:2] == '12') and ('AM' in hour): print('00' + hour[2:8]) elif 'AM' in hour: print(hour[:8]) elif (hour[:2] == '12') and ('PM' in hour): print(hour[:8]) elif 'PM' in hour: print(str(int(hour[:2])+12) + hour[2:8]) hour = input() timeConversion(hour)
5a5d631df7c2e808edf58578062cbe22a7663c04
tejasshah2k19/21-python-gen
/oop_inheritance_demo.py
1,107
4.03125
4
# object of one class can access property of another class # A --> add() --> object A , B --> objB -> add( ) # Parent - Base - Super # Child - Derived - Sub #oop-> five types of inheritance # single level [ Empl PartTimeEmpl ] # multi level # multiple # hierarchical # hybrid # code reusability #Calc add() sub() mul() div() #SciCalc sin() sqr() cub() #facebook --> like() #post -> like() , photo -> like() , video -> like(),page -> like()->emojis #Employee id , name #DailyBaseEmpl - wages FullTimeEmpl - salary class Employee: def getData(self): print("enter id and name") self.id = input() self.name = input() class FullTimeEmpl(Employee): def getData(self): #over riding super().getData() #super() -- access prop from parent print("Enter Salary") self.salary = int(input()) def printData(self): print("Id : ",self.id) print("Name : ",self.name) print("Salary : ",self.salary) class A(FullTimeEmpl): pass fte = FullTimeEmpl() fte.getData() fte.printData()
beef545a4bd97d53018ef5ec610252da3a26541e
bwoldemi/Python
/ArgsKwargs.py
593
4.3125
4
# reference https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/ # understanding *argv **kwargs def test_argv(*argv): for arg in argv: print("the variable %s" %arg) test_argv("one","two","three") ''' the variable one the variable two the variable three ''' # kwargs def test_kwargs(**kwargs): if kwargs is not None: for key, value in kwargs.iteritems(): print("key = %s value = %s" %(key, value)) test_kwargs(name="Bereket", lastname="Woldemicael") '''' key = lastname value = woldemicael key = name value = bereket '''''
1c5d78c9aca19fb920d352e37c18323ccaab6f35
gauravtripathi001/EIP-code
/Queue/maximum_sliding_window.py
503
3.71875
4
import collections def max_in_sliding_window(arr, w): deque=collections.deque() res=[] for i in range(len(arr)): while(len(deque)>0 and arr[i]>=arr[deque[-1]]): deque.pop() deque.append(i) if(i-w+1>=0): if(deque[0]<=i-w): deque.popleft() res.append(arr[deque[0]]) return res def main(): arr = [1, 3, -1, -3, 5, 3, 6, 7] w = 3 print(max_in_sliding_window(arr, w)) main()
b1df320f96cecd56a17ad1d3b94ccd3f844ca627
guptaak2/CSC148
/Assignment 1/Tour.py
5,050
3.5625
4
# Copyright 2013, 2014 Gary Baumgartner, Danny Heap, Dustin Wehr # Distributed under the terms of the GNU General Public License. # # This file is part of Assignment 1, CSC148, Fall 2013. # # This is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This file is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this file. If not, see <http://www.gnu.org/licenses/>. from ConsoleController import ConsoleController from GUIController import GUIController from TOAHModel import TOAHModel import math import time def tour_of_four_stools(model: TOAHModel, delay_btw_moves: float=0.5, console_animate: bool=False): """Move a tower of cheeses from the first stool in model to the fourth. model - a TOAHModel with a tower of cheese on the first stool and three other empty stools console_animate - whether to use ConsoleController to animate the tour delay_btw_moves - time delay between moves in seconds IF console_animate == True no effect if console_animate == False """ n = four_stools.number_of_cheeses() origin = 0 helper_one = 1 helper_two = 2 dest = 3 four_stool_hanoi(n, origin, helper_one, helper_two, dest) # Description of solution: # I have created two helper functions: three_stool_hanoi, four_stool_hanoi # The four_stool_hanoi uses three_stool_hanoi recursively to compute a solution # The heart of the solution lies in this line: # i = int(math.ceil(((math.sqrt(8 * n + 1) - 1)/2))) # It represents the number of cheeses to move from the stool depending on the # number of cheeses on that stool. (n = number_of_cheeses) # After it computes that, the code follows the same procedure as described # in the Assignment #1 handout. # It moves (n-i) cheese rounds to an intermediate stool using four_stool_hanoi # i.e. it moves (n-i) from origin to helper_one using dest and helper_two # Then it moves (i) cheeses from origin to helper_two using three_stool_hanoi # Then it moves (n-i) cheeses from helper_one to dest using origin and # helper_two via four_stool_hanoi. # The code follows the same procedure described in Assignment #1 handout, # but with a slightly different approach. # In three_stool_hanoi, it receives parameters from four_stool_hanoi # It receives (i, origin, dest, helper_two) # three_stool_hanoi moves (n-1) cheeses from origin to dest using helper_one # three_stool_hanoi is used to solve the smaller cheese stack from # four_stool_hanoi def three_stool_hanoi(n, origin, dest, helper_one): if n != 0: if CONSOLE_ANIMATE == True: print (four_stools) time.sleep(DELAY_BETWEEN_MOVES) three_stool_hanoi(n-1, origin, helper_one, dest) four_stools.move(origin, dest) three_stool_hanoi(n-1, helper_one, dest, origin) def four_stool_hanoi(n, origin, helper_one, helper_two, dest): i = 0 if n == 1: four_stools.move(origin, dest) if CONSOLE_ANIMATE == True: print (four_stools) time.sleep(DELAY_BETWEEN_MOVES) elif n == 2: four_stools.move(origin, helper_one) if CONSOLE_ANIMATE == True: print (four_stools) time.sleep(DELAY_BETWEEN_MOVES) four_stools.move(origin, dest) if CONSOLE_ANIMATE == True: print (four_stools) time.sleep(DELAY_BETWEEN_MOVES) four_stools.move(helper_one, dest) if CONSOLE_ANIMATE == True: print (four_stools) time.sleep(DELAY_BETWEEN_MOVES) else: i = int(math.ceil(((math.sqrt(8 * n + 1) - 1)/2))) four_stool_hanoi(n-i, origin, helper_two, dest, helper_one) three_stool_hanoi(i, origin, dest, helper_two) four_stool_hanoi(n-i, helper_one, origin, helper_two, dest) # The above code uses a solution provided by my high school teacher. # It is a derivation of the original solution by Ted Roth. # However, I have explained how the solution works. # High School Teacher info: # Mrs. Ouellette, # 5555 Creditview Rd,St. Joseph Secondary School, # Mississauga, ON - L5V 2B9 # (905) - 812 - 1376 if __name__ == '__main__': NUM_CHEESES = 8 DELAY_BETWEEN_MOVES = 0.5 CONSOLE_ANIMATE = True # DO NOT MODIFY THE CODE BELOW. four_stools = TOAHModel(4) four_stools.fill_first_stool(number_of_cheeses=NUM_CHEESES) tour_of_four_stools(four_stools, console_animate=CONSOLE_ANIMATE, delay_btw_moves=DELAY_BETWEEN_MOVES) print(four_stools.number_of_moves())
3534810179c6cf803d21294013bd1f9d211d439a
gHuwk/University
/Third course/5th semester/Analysis of algorithms course/Lab3 - Sorting/main1.py
1,897
3.828125
4
from sort import * import time import random def get_random_array(n): array = [] for i in range(n): array.append(random.randint(0, 20000)) return array def get_best_array(n): array = [] for i in range(n): array.append(i) return array def get_worst_array(n): array = [] for i in range(n): array.append(n - i) return array def get_calc_time(func, arr): t2 = time.process_time() func(arr) t1 = time.process_time() - t2 return t1 def measure_time(get_array, get_array_quick, func, n1, n2, st, it): t_bubble = [] t_shell = [] t_quick = [] for n in range(n1, n2, st): print(n, ' ', time.time()) t = 0 for i in range(it): arr = get_array(n) t += get_calc_time(mysort_bubble, arr) t_bubble.append(t / it) t = 0 for i in range(it): arr = get_array(n) t += get_calc_time(mysort_insert, arr) t_shell.append(t / it) t = 0 for i in range(it): arr = get_array_quick(n) t += get_calc_time(func, arr) t_quick.append(t / it) return (t_bubble, t_shell, t_quick) n1 = int(input("Size\nFrom: ")) n2 = int(input("To: ")) h = int(input("Step:")) if n1 > n2 or n2 == n1 or h == 0: print("Wrong input") exit() else: result = measure_time(get_best_array, get_best_array, mysort_quick_middle, n1, n2 + 1, h, 100) print("\n", result, "\n") result = measure_time(get_worst_array, get_best_array, mysort_quick_end, n1, n2 + 1, h, 100) print("\n", result, "\n") result = measure_time(get_random_array, get_random_array, mysort_quick_middle, n1, n2 + 1, h, 100) print("\n", result, "\n")
f6d3d471d07b0c0137cc0cffbcaf8ea006e1d844
yusupnurkarimah/simple_triangle_numbers
/triangle_numbers_02.py
309
4.09375
4
string = "" bar = int(input("Please enter a number :")) no = bar # Looping rows while bar >= 0: # Looping columns kol = bar while kol > 0: string = string + " " + str(no) + " " kol = kol - 1 string = string + "\n" bar = bar - 1 no = no - 1 print (string)
6af1c7d7a828aad18167aa781cc2a9e72b648f2f
iSumitYadav/python
/Binary_Tree/dia.py
1,720
3.65625
4
class Node(object): def __init__(self, value=None, left=None, right=None): '''self.__left = left self.__right = right self.__value = value''' self.left = left self.right = right self.value = value '''@property def right(self): return self.__right @right.setter def right(self, value): self.__right = value @right.deleter def right(self): del self.__right @property def left(self): return self.__left @left.setter def left(self, value): self.__left = value @left.deleter def left(self): del self.__left''' def get_diameter(node): if not node: return (0, 0) if not isinstance(node, Node): raise Exception(" Invalid param type ") (left_height, left_diameter) = get_diameter(node.left) (right_height, right_diameter) = get_diameter(node.right) current_diameter = 0 if node.right and node.left: current_diameter = left_height + right_height + 1 return (max([left_height, right_height]) + 1, max([left_diameter, right_diameter, current_diameter])) # Case 2: Diameter is not through root # # 1 # 2 # 4 5 # 8 # 9 root = Node(1) root.left = Node(2) root.left.left = Node(4) root.left.right = Node(5) root.left.left.left = Node(8) root.left.left.left.left = Node(9) print ("case 1 : Height : %s Diameter : %s" % get_diameter(root)) # case 2: Diameter through root # 1 # 2 3 # 4 5 6 7 # 8 10 # 9 11 root.right = Node(3) root.right.left = Node(6) root.right.right = Node(7) root.right.left.right = Node(10) root.right.left.right.left = Node(11) print ("case 2 : Height : %s Diameter : %s" % get_diameter(root))
cd695e2ad9f28da024c21c25868f8eab79804fbe
UJHa/Codeit-Study
/(10) 알고리즘 기초 - Sort, Binary Search/06) 2776 암기왕/seonga.py
877
3.640625
4
# 이진탐색을 재귀함수로 구현하면 시간초과 from sys import stdin # 이진탐색 def binary_search(value, lst, start_index = 0, end_index = None): end_index = len(lst) -1 while start_index<= end_index: mid_index = (start_index+end_index)//2 if lst[mid_index] == value: return 1 elif lst[mid_index] > value: end_index = mid_index - 1 elif lst[mid_index] < value: start_index = mid_index + 1 return 0 T = int(stdin.readline()) # 테스트 개수만큼 돌아가야함. for i in range(T): N = int(stdin.readline()) LST1= list(map(int, stdin.readline().split())) M = int(stdin.readline()) LST2= list(map(int, stdin.readline().split())) LST1.sort() for value in LST2: print(binary_search(value, LST1))
cb6a3ef5084aef59e90b43d6de3fbf4e6d1cc728
AmRiyaz-py/Python-Arsenal
/Conditions in python with loop/problem2A6OP.py
218
4.40625
4
''' Program :- Program for understanding of elif Author :- AmRiyaz Last Modified :- April 2021 ''' x = 22 if(x % 2 == 0): print(x) elif(x % 3 == 0): x = x * 2 print(x) ''' Output: 22 '''
2a51dfadbc62d6cc1dfebc955c2f6a1e1439b517
simoneeferreira/pythonCourse
/CoronaPythonExercises/chapter_5/exercise_2.py
1,186
4.0625
4
#test 1 car = 'subaru' print("Is car == 'subaru'? I predict True.") print(car == 'subaru') #Equality print("\nIs car == 'audi'? I predict False.") print(car == 'audi') #Inequality if car != 'audi': print("It's not my car. I have a subaru.") #lower case print(car.lower() == 'subaru') #test 2 age = 20 print("\nIs age == 20? I predict True.") print(age == 20) print("\nIs age == 27? I predict False.") print(age == 27) #numerical test print(age >= 50) print(age <= 40) print(age == 20) print(age != 30 ) #and/or keyword print(age > 10 and age < 15) print(age >= 10 or age <= 15) #test 3 name = 'simone' print("\nIs name == 'simone'? I predict True.") print(name == 'simone') print("\nIs name == 'joana'? I predict False.") print(name == 'joana') #test 4 animal = 'dog' print("\nIs animal == 'dog'? I predict True.") print(animal == 'dog') print("\nIs animal == 'cat'? I predict False.") print(animal == 'cat') #test 5 name = 'joao' print("\nIs name == 'joao'? I predict True.") print(name == 'joao') print("\nIs name == 'marcos'? I predict False.") print(name == 'marcos') #test 6 animals = ['dog', 'cat', 'monkey', 'fish'] print('fish' in animals) print('dog' not in animals)
bef44cfbc96ce4064db4dd4933af4ce9a2b39f6c
bemagee/LearnPython
/PyCarolinas/fizzbuzz.py
707
3.859375
4
""" Generate the first n Fizz Buzz answers. Usage: > python fizzbuzz.py n """ import sys def fizzbuzz(n): """ fizzbuzz(n) -> [first n Fizz Buzz answers] """ answers = [] for x in range(1,n+1): answer = "" if not x%3: answer += "Fizz" if not x%5: answer += "Buzz" if not answer: answer = x answers.append(answer) return answers if __name__ == '__main__': try: if len(sys.argv) != 2: raise ValueError("Incorrect number of arguments") answers = fizzbuzz(int(sys.argv[1])) print(" ".join([str(answer) for answer in answers])) except: print(__doc__)
507c7d8fe564f24f8985f76e8ac8b23da828642f
aseemrb/elevator
/elevator.py
4,904
3.640625
4
#!/usr/bin/env python # -*- coding: utf-8 -*-# speed = 1 opentime = 3000 class Elevator(object): def __init__(self, w, number, SW, SH, floor, direc=''): self.number = number self.opendistance = 0.5 self.direc = direc self.dest = [] self.vel = 0 self.floor = floor self.people = 0 self.capacity = 6 self.timer = 0 self.overloaded = False # state: moving, closed, opening, opened, closing self.state = 'closed' color = '#000000' self.body = w.create_rectangle(100*self.number+2, 20+(9-self.floor.number)*SH/12, 100*(self.number+1)-2, 20+(10-self.floor.number)*SH/12, fill="#333") self.doorway = w.create_rectangle(100*self.number+50, 20+(9-self.floor.number)*SH/12, 100*self.number+50, 20+(10-self.floor.number)*SH/12, fill="#fff") self.x = w.coords(self.body)[0] self.y = w.coords(self.body)[1] # self.label = w.create_text(self.x, self.y-10, text='Elevator'+str(self.number)) def update(self, w, SH, floors): """ Called each frame. """ if self.people>self.capacity: self.overloaded = True if self.state!='opening' and self.state!='opened': self.state='opening' else: self.overloaded = False if self.vel!=0: for i in range(10): # Reached some floor if self.y==20+(9-i)*SH/12: self.floor.elevs.remove(self) w.itemconfig(self.floor.display.body, fill='#6af') if len(self.floor.elevs)==0: w.itemconfig(self.floor.display.bodytext, text='--') self.floor = floors[i] floors[i].elevs.append(self) w.itemconfig(self.floor.display.body, fill='#6fa') # Update text on destination floors for idx in self.dest: if i==0 and self.direc=='up': w.itemconfig(floors[idx].display.bodytext, text='G ↑') elif i>0 and self.direc=='up': w.itemconfig(floors[idx].display.bodytext, text=str(i)+' ↑') elif self.direc=='down': w.itemconfig(floors[idx].display.bodytext, text=str(i)+' ↓') # Reached destination if i in self.dest: self.vel=0 # Remove from destination queue and open doors self.dest.remove(i) if i==0: w.itemconfig(floors[i].display.bodytext, text='G') else: w.itemconfig(floors[i].display.bodytext, text=str(i)) self.state = 'opening' break # Door opening animation if self.state=='opening': if self.floor.number<9: self.floor.upb.on = False if self.floor.number>0: self.floor.dwb.on = False coordslist = w.coords(self.doorway) w.coords(self.doorway, coordslist[0]-self.opendistance, coordslist[1], coordslist[2]+self.opendistance, coordslist[3]) # Move elevator if state is moving elif self.state=='moving': w.move(self.body, 0, self.vel) w.move(self.doorway, 0, self.vel) # Door closing animation elif self.state=='closing': coordslist = w.coords(self.doorway) w.coords(self.doorway, coordslist[0]+self.opendistance, coordslist[1], coordslist[2]-self.opendistance, coordslist[3]) # Door opened if w.coords(self.doorway)[0]<=100*self.number+5: self.state = 'opened' if self.overloaded: return self.timer += 10 if self.timer>=opentime: self.state = 'closing' self.timer = 0 if len(self.dest)==0: self.direc = '' # Door closed if w.coords(self.doorway)[0]>=100*self.number+50: self.state = 'closed' if len(self.dest)>0: if self.dest[0]>self.floor.number: self.direc = 'up' self.vel = -speed self.state = 'moving' elif self.dest[0]<self.floor.number: self.direc = 'down' self.vel = speed self.state = 'moving' if len(self.dest)==0: self.direc='' self.x = w.coords(self.body)[0] self.y = w.coords(self.body)[1] w.update()
bb1268acc2b1d69ceae5e8aa6c5385b0b684e4a3
herambchaudhari4121/NYU_Shanghai_CS
/ICS 101/Xmisc/midterm_spring21/insertSort_student.py
1,831
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Mar 29 14:13:01 2020 @author: xg7 """ ##Problem 1. insertion sort import random random.seed(0) def insertionSort(lst): ###---- delete the following lines and insert your code below ----### for i in range (1,len(lst)): m=i while m>=1 and lst[m]<lst[m-1]: lst[m], lst[m-1] = lst[m-1], lst[m] m -= 1 ###--- end of your code ---### def nInsertionSortOfIdx0(lst, n): ###---- delete the following lines and insert your code below ----### for i in range(n, len(lst), n): m=i while m>=n and lst[m]<lst[m-n]: lst[m], lst[m-n] = lst[m-n], lst[m] m -= n ###--- end of your code ---### ###---Tests of your code.---#### ###---When debugging, you can comments them out temporarily if you want.---### ###---But Do not change them.---### if __name__ == "__main__": #### test of insertionSort() print("-----testing insertionSort()-----") lst1 = [9, 2, 0, 8, 5, 6, 1, 7, 3, 0] print("Before sorted:\n", lst1) insertionSort(lst1) print("The result of insertionSort:\n", lst1) print() lst2 = [random.randint(0, 100) for i in range(10)] print("Before sorted:\n", lst2) insertionSort(lst2) print("The result of insertionSort:\n", lst2) print() ### test of nInsertionSortOfIdx0() print("-----testing nInsertionSortOfIdx0()-----") lst3 = [9, 2, 0, 8, 5, 6, 1, 7, 3, 0] print("Befort sorted:\n", lst3) nInsertionSortOfIdx0(lst3, 4) print("The result of nInsertionSortOfIdxO with n = 4:\n", lst3) print() lst4 = [9, 2, 0, 8, 5, 6, 1, 7, 3, 0] print("Befort sorted:\n", lst4) nInsertionSortOfIdx0(lst4, 6) print("The result of nInsertionSortOfIdxO with n = 6:\n", lst4)
82f3b5ab8798a95f5412a761f048399042e0db7d
patelvini13/python
/py_assessment/Assessment_2_30_December_2019/Assessment_2_10.py
160
3.796875
4
n = int(input("Enter a number : ")) n1 = str(n) def check(n): ans = 0 for i in n: ans = ans + int(i) return ans print(check(n1))
7879c15562c45db156737c4ac74cf95db37db464
khlee12/python-leetcode
/easy/28.Implement_strStr.py
652
3.578125
4
# 28. Implement strStr() # https://leetcode.com/problems/implement-strstr/ class Solution: def strStr(self, haystack: str, needle: str) -> int: if not haystack or haystack is None: if haystack == needle: return 0 return -1 if not needle or needle is None: return 0 # loop, find substring, return index sub_str = ' '+haystack[:len(needle)-1] for i in range(len(needle)-1, len(haystack)): sub_str = sub_str[1:]+haystack[i] if sub_str == needle: return i-len(needle)+1 return -1
7b828fff42455ec3ad4267a43dee38e404819046
Thefloor075/ProjectEuler
/ProjectEuler10.py
584
3.859375
4
#!/usr/bin/python """ The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. """ from math import sqrt def nombre_premier(n): racine = int(sqrt(n)) for i in range(2,racine+1): if n%i==0 and n!=i: return False return True def premier(): n = 3 p = [] while n <= 2000000: if nombre_premier(n) == True: p.append(n) n += 2 else: n += 2 return p def somme(): liste = [2] liste = premier() return sum(liste) print(somme())
0b323fb4eb5f874e3be939ee67471228486f76cb
Blasterai/blasterutils
/generaltools/blaster_date_tools.py
934
3.515625
4
from datetime import timedelta, datetime try: # pip install python-dateutil from dateutil import parser except ModuleNotFoundError: pass def daterange(start_date, end_date): """ Accepts either datetime objects or str in format YYYY-MM-DD for start_date and end_date. Works similar to built-in range(). Source: https://stackoverflow.com/a/1060330/9268478 Usage: >>> for single_date in daterange('2018-12-01', '2018-12-05'): >>> print(single_date) 2018-12-01 00:00:00 2018-12-02 00:00:00 2018-12-03 00:00:00 2018-12-04 00:00:00 :param start_date: :param end_date: :return: generator """ if not isinstance(start_date, datetime): start_date = parser.parse(start_date) if not isinstance(end_date, datetime): end_date = parser.parse(end_date) for n in range(int((end_date - start_date).days)): yield start_date + timedelta(n)
bf7496efc0807b63d538e71fef5dc3f3bc06a9e4
ovbystrova/hse_practicals
/SciComp/Practical2/DRI_caesar.py
602
4.34375
4
from string import ascii_letters as letters def caesar(message: str, shift: int) -> str: """ Basic version of caesar encoding/decoding algo Args: message: str, input message shift: int, amount of shifts Returns: str """ symbols = [letters[(letters.index(char) + shift) % len(letters)] if char in letters else char for char in message] return "".join(symbols) if __name__ == '__main__': message = str(input("Enter a message:\n")) shift = int(input("Enter a number for shift:\n")) print(caesar(message=message, shift=shift))
2e2f64cf9ec5f3bc97db752cbb37b1dbc1917917
cx1802/hello_world
/assignments/XiePeidi_assign2_problem1.py
1,279
3.984375
4
""" Peidi Xie February 12th, 2019 Introduction to Programming, Section 03 Problem 1: Lottery Winnings Calculator """ # ask the user for the total amount they won, the number of people splitting # the winnings, and the tax rate being applied to each person's share total = int(input("How much money did you win? ")) num_ppl = int(input("How many people are splitting the winnings? ")) tax_rate = int(input("What is the tax rate on lottery winnings (i.e. 25 = 25%): ")) # compute the total amount they won, the amount of each person's share, # the tax due on each share, and the final amount each person will take home total1 = float(total) per_won = total1 / num_ppl per_tax = per_won * tax_rate * 0.01 per_takehome = per_won - per_tax # format the computed four variables into two decimal places and add the "comma" separator total2 = format(total1, ",.2f") per_won2 = format(per_won, ",.2f") per_tax2 = format(per_tax, ",.2f") per_takehome2 = format(per_takehome, ",.2f") # output the formatted four variables print() print("In total you won $", end="") print(total2) print("Split", num_ppl, "ways that amounts to $", end="") print(per_won2, "per person") print("Tax per person: $", end="") print(per_tax2) print("Take home amount per person: $", end="") print(per_takehome2)
1d97718ad7c23f925f9fb0228c146af0fd0e8659
Nedashkivskyy/NedashkivskyyV
/Лаб 6 Недашківський.py
1,119
3.890625
4
from collections import namedtuple class Library(object): def __init__(self): self.books = [] def addBook(self, book): self.books.append(book) def searchBookYear(self, year): for book in self.books: if book.year == year: return book def searhBookAuthor(self, author): written_by_author = [] for book in self.books: if book.author == author: written_by_author.append(book) return written_by_author def searchUnderPrice(self,price): books_under_price = [] for book in self.books: if book.price < price: books_under_price.append(book) return books_under_price Book = namedtuple('Book', 'name author year price') library = Library() library.addBook(Book('Harry Potter', 'J. K. Rowling', '1997', 30)) library.addBook(Book('Hobbit', 'J. R. R. Tolkien', '1937', 45)) library.addBook(Book('The Witcher', 'Andrzej Sapkowski', '1993', 20)) library.addBook(Book('Factfulness', 'Hans Rosling', '1985', 15)) print(library.searchBookYear('1937'))
365db48ab4f57fd396f995bdb94bb5257295cd00
joabefs/python-lotomania
/consultaLot.py
806
3.96875
4
import string import sqlite3 import random # Cria uma conexão e um cursor con = sqlite3.connect('loteria.db') cur = con.cursor() s='sorteio' c='concurso' t = input("Digite o concurso => ") #lista armazenará numeros aleatorios para o jogo lista = [] #pp =[] #pi =[] #ip =[] #ii =[] while len(lista) < 50: cur.execute('SELECT * FROM '+ s +' WHERE '+ c +'>= ?', (t,)) #print 'sorteios a partir do concurso', t, 'concursos:' for sorteio in cur.fetchall(): print sorteio n = random.choice(sorteio) #se numero nao estiver na lista e ainda está dentro da capacidade, ele adiciona numero na lista if n not in lista and n < 100 and len(lista)<50: lista.append(n) #ordena a lista com numeros lista.sort() print lista
d6f058f278b058a5610c469e2f668150133bf9b3
raccooncho/TIL
/04_flask/first_app/pick_lotto.py
161
3.53125
4
import random def pick_lotto(): num_list = [str(i) for i in random.sample(range(1, 46), 6)] num = ' '.join(num_list) return num print(pick_lotto())
989c34f0d0f6ae1d4838fa1cd8bc52a2b6c4f5e7
FuriousSheep/100DaysOfCode
/Day_018/Polygons.py
628
4.125
4
from turtle import Turtle, Screen def main(): timmy = Turtle() timmy.shape("turtle") timmy.color("#00FF00") colors = [ "#001100", "#002200", "#003300", "#004400", "#005500", "#006600", "#007700", "#008800", "#009900", "#00AA00" ] n_sides = 3 for _ in range(3, 11): for _ in range(0, n_sides): timmy.forward(100) timmy.right(360/n_sides) timmy.color(colors[n_sides-3]) n_sides += 1 screen = Screen() screen.exitonclick() if __name__ == "__main__": main()
40f8be3fbbe558da60d8f01ae01bd4fb4957f0de
angelospy/aadd-to-my-classes
/classes2.py
948
3.53125
4
class pet: def __init__(self, name, a, h, p): self.name = name self.age = a self.hunger = h self.playful = p def getname(self): return self.name def getage(self): return self.age def gethunget(self): return self.hunger def getplayful(self): return self.playful #sets sets cange the previus string or input def setname(self,xname): self.name = xname def setage(self,age): self.age = age def sethunger(self,hunger): self.hunger = hunger def setplayful(self,play): self.playful = play pet1 = pet('gim',3,False,True) print(pet1.getname()) print(pet1.getplayful()) pet1.setname('snowbal') print(pet1.getname()) print(pet1.name) pet1.name = 'jim' print(pet1.name) #class dog: # def __init__(self): # pet.__init__(self)
93800bea6a87bbb79e805582e1b0ef130153dc2b
AlinesantosCS/vamosAi
/Módulo - 1/Módulo 1-3 - É feijão ou sorvete/mais_variaveis.py
337
3.515625
4
soma = 1024 + 2048 multiplique = 1024 * 2048 divida = 2048/1024 subtraia = 1024 - 2048 print('Soma ->',soma) print('Multiplicação ->',multiplique) print('Divisão ->',divida) print('Subtraia ->',subtraia) num1 = input('Entre com o 1º valor: ') num2 = input('Entre com o 2º valor: ') soma = (num1 + num2) print ("A soma é",soma)
3c7755b7a7e90cbb4c3cc9c81ff05320d6c2999d
erelsgl/numberpartitioning
/src/numberpartitioning/greedy.py
4,423
4
4
from math import inf from typing import Callable, Iterator, List, Optional, Tuple from .common import Partition, PartitioningResult def greedy( numbers: List[int], num_parts: int = 2, return_indices: bool = False ) -> PartitioningResult: """Produce a partition using the greedy algorithm. Concretely, this orders the input numbers in descending order, then adds them to the parts one at a time, each time adding the number to the currently smallest part. Parameters ---------- numbers The list of numbers to be partitioned. num_parts The desired number of parts in the partition. Default: 2. return_indices If True, the elements of the parts are the indices of the corresponding entries of numbers; if False (default), the elements are the numbers themselves. Returns ------- A partition representing by a ``PartitioningResult``. """ sorted_numbers = sorted(enumerate(numbers), key=lambda x: x[1], reverse=True) sums = [0] * num_parts partition: Partition = [[] for _ in range(num_parts)] for index, number in sorted_numbers: smallest = min(range(len(sums)), key=sums.__getitem__) sums[smallest] += number partition[smallest].append(index if return_indices else number) return PartitioningResult(partition, sums) def complete_greedy( numbers: List[int], num_parts: int = 2, return_indices: bool = False, objective: Optional[Callable[[Partition], float]] = None, ) -> Iterator[PartitioningResult]: """Generate partition using the order from the greedy algorithm. Concretely, this searches through all combinations by following the strategy that adds to each part the largest number not yet added to any part, so that smaller parts are prioritized. This is done depth-first, meaning that the smallest of the input numbers are shuffled between different parts before larger input numbers are. New partitions are yielded whenever an improvement is found, according to an optional objective function. Parameters ---------- numbers The list of numbers to be partitioned. num_parts The desired number of parts in the partition. Default: 2. return_indices If True, the elements of the parts are the indices of the corresponding entries of numbers; if False (default), the elements are the numbers themselves. objective The objective function to be minimized. If None (default), this is the difference between the size of the largest part and the smallest part. Yields ------ Partitions represented by a ``PartitioningResult`` whenever a new best is found. """ sorted_numbers = sorted(enumerate(numbers), key=lambda x: x[1], reverse=True) # Create a stack whose elements are partitions, their sums, and current depth to_visit: List[Tuple[Partition, List[int], int]] = [ ([[] for _ in range(num_parts)], [0] * num_parts, 0) ] best_objective_value = inf while to_visit: partition, sizes, depth = to_visit.pop() # If we have reach the leaves of the DFS tree, check if we have an improvement, # and yield if we do. if depth == len(numbers): new_objective_value = ( objective(partition) if objective else max(sizes) - min(sizes) ) if new_objective_value < best_objective_value: best_objective_value = new_objective_value yield PartitioningResult(partition, sizes) else: index, number = sorted_numbers[depth] # Order parts by decreasing size, so smallest part ends up on top of stack. for part_index in sorted( range(len(sizes)), key=sizes.__getitem__, reverse=True ): # Create the next vertex; be careful to copy lists when necessary, but # note that we can reuse all but one part in the existing partition. new_partition = list(partition) new_partition[part_index] = list(new_partition[part_index]) + [ index if return_indices else number ] new_sizes = list(sizes) new_sizes[part_index] += number new_depth = depth + 1 to_visit.append((new_partition, new_sizes, new_depth))
5c504ff0aa43643f2de1d5af13c10fee03556d4b
stflihanwei/python_learning_projects
/PythonCrashcourse/names.py
383
3.8125
4
from PythonCrashcourse.testing.name_function import get_formatted_name print("enter 'q' to exit") while True: first = input("\nGive first name:") if first == 'q': break last = input("Please give me a last name:") if last == 'q': break formatted_name = get_formatted_name(first, last) print("\tNeatly formatted name:" + formatted_name + '.')
7da8ac9ead2af9fd26c41d789f110037467a206d
N3mT3nta/ExerciciosPython
/Mundo 1 - Fundamentos/ex028.py
300
3.515625
4
#Aprimorado no ex058 from random import randint from time import sleep cpu = randint(0, 5) user = int(input('Digite um número de 0 a 5: ')) print('Processando...') sleep() print(f'O computador escolheu {cpu}') print('Você acertou, parabéns!' if user == cpu else f'Você errou! Tente novamente.')
29660c5b789b42ce663a6485f74f6d228255c590
MarianDanaila/Competitive-Programming
/LeetCode_30days_challenge/2021/September/Array Nesting.py
2,294
3.765625
4
from typing import List from collections import deque # Approach 1: Using a set for tracking the visited indexes and a deque class Solution: def arrayNesting(self, nums: List[int]) -> int: n = len(nums) longest_length = 1 visited = set() for i in range(n): if i not in visited: # start bfs dq = deque() dq.append(i) curr_length = 1 visited.add(i) while dq: index = dq.popleft() next_index = nums[index] if next_index not in visited: visited.add(next_index) dq.append(next_index) else: longest_length = max(longest_length, curr_length) curr_length += 1 return longest_length # Approach 2: Using only a set for tracking the visited indexes class Solution: def arrayNesting(self, nums: List[int]) -> int: n = len(nums) longest_length = 1 visited = set() for i in range(n): if i not in visited: # start bfs curr_length = 1 visited.add(i) index = nums[i] while index not in visited: visited.add(index) curr_length += 1 index = nums[index] longest_length = max(longest_length, curr_length) return longest_length # Approach 3: Instead of using a set to keep track of visited nodes, we can change a value from nums array to n # (which is the length of the array). We can also use infinity for example. class Solution: def arrayNesting(self, nums: List[int]) -> int: n = len(nums) longest_length = 1 for i in range(n): if nums[i] != n: curr_length = 1 index = nums[i] nums[i] = n while nums[index] != n: curr_length += 1 next_index = nums[index] nums[index] = n index = next_index longest_length = max(longest_length, curr_length) return longest_length
9c5ab1af62b25b6679796cf5675cea6d25a3db9d
harsilspatel/ProjectEuler
/5. Smallest multiple.py
234
3.828125
4
import functools def lcm(x, y): if x > y: greater = x else: greater = y lcm = greater while (True): if (lcm % x == 0 and lcm % y == 0): break lcm += greater return lcm print(functools.reduce(lcm, range(1,21)))
80275051133f65824cdc323036c8414b57f102cc
atique08642/Basic-Common-Codes
/Automorphic number.py
275
3.90625
4
def automorphic(n): square = n * n while n: if (n%10 != square%10): return False n //= 10 square //= 10 return True number = int(input()) if automorphic(number): print("automorphic") else: print("is NOT AUTOMORPHIC")
ac9d0389f7f93ad9cf4c55c67ce50ed767746a49
jpslat1026/Mytest
/Section1/1.3/16.py
299
3.703125
4
#16.py #by John Slattery on November 15, 2018 # This script shows the Fibonacci sequence def main(): print("This script shows the Fibonacci sequence") howfar = eval(input("how far do you want to go?: ")) a = 1 b = 1 for i in range(0, howfar -2): a, b=b , a+b print(b) main()
034a4f5ea88340ed78fd8715af7f93ba2748c973
toly/pentamino
/pentamino/base.py
7,632
3.75
4
__author__ = 'toly' import itertools class BaseObject(object): """ Base object with show method """ data = None def __str__(self): result = '' for row in self.data: for cell in row: result += '{:3d}'.format(cell) result += '\n' return result def init_board(width, height): row = [0] * width return [list(row) for i in xrange(height)] def set_figure(board, width, height, figure, color, x=0, y=0): new_board = map(list, board) if x < 0 or y < 0 or x + figure.width > width or y + figure.height > height: return for i, j in figure.points: if new_board[y+i][x+j] != 0: return new_board[y+i][x+j] = color return new_board def get_free_cell(board, width, height): for i in xrange(height): for j in xrange(width): if board[i][j] == 0: return j, i def print_board(board): result = '' for row in board: for cell in row: result += '{:3d}'.format(cell) result += '\n' print result def pprint_board(matrix): """ pretty print board board like: [ [1, 2, 2], [2, 2, 2], [2, 3, 3], [2, 4, 3], ] will be printed as: +---+---+---+ | | | +---+ + | | + +---+---+ | | | + +---+ + | | | | +---+---+---+ """ WIDTH_FACTOR = 3 height, width = len(matrix), len(matrix[0]) new_height, new_width = map(lambda x: 2 * x + 1, (height, width)) new_matrix = init_board(new_width, new_height) for y in xrange(height): for x in xrange(width): new_x, new_y = map(lambda n: 2 * n + 1, (x, y)) new_matrix[new_y][new_x] = matrix[y][x] def is_odd(x): return bool(x % 2) for y in xrange(new_height): for x in xrange(new_width): # corners if (x, y) in ((0, 0), (0, new_height - 1), (new_width - 1, 0), (new_width - 1, new_height - 1)): new_matrix[y][x] = '+' continue # top-bottom border lines if is_odd(x) and y in (0, new_height - 1): new_matrix[y][x] = '-' * WIDTH_FACTOR continue # right-left border lines if is_odd(y) and x in (0, new_width - 1): new_matrix[y][x] = '|' continue # verical line or space between cells if not is_odd(x) and is_odd(y): if new_matrix[y][x-1] != new_matrix[y][x+1]: new_matrix[y][x] = '|' else: new_matrix[y][x] = ' ' continue # horizontal line or space between cells if not is_odd(y) and is_odd(x): if new_matrix[y+1][x] != new_matrix[y-1][x]: new_matrix[y][x] = '-' * WIDTH_FACTOR else: new_matrix[y][x] = ' ' * WIDTH_FACTOR continue # inner and border corners or spaces if not is_odd(x) and not is_odd(y): new_matrix[y][x] = '+' if 0 < x < new_width - 1 and 0 < y < new_height - 1: cells = (new_matrix[y-1][x-1], new_matrix[y+1][x-1], new_matrix[y-1][x+1], new_matrix[y+1][x+1], ) if len(set(cells)) == 1: new_matrix[y][x] = ' ' for y in xrange(new_height): for x in xrange(new_width): if type(new_matrix[y][x]) is int: new_matrix[y][x] = ' ' * WIDTH_FACTOR str_rows = [] for row in new_matrix: str_rows.append(''.join(map(str, row))) print '\n'.join(str_rows) + '\n' def reflect_board(board): return board[::-1] def rotate_right(board): height, width = len(board), len(board[0]) new_board = [] for j in xrange(width): new_row = [] for i in xrange(height - 1, -1, -1): new_row.append(board[i][j]) new_board.append(new_row) return new_board def generate_shadows(board): original_board = map(list, board) yield original_board reflected_board = reflect_board(original_board) yield reflected_board for i in xrange(3): original_board = rotate_right(original_board) reflected_board = rotate_right(reflected_board) yield original_board yield reflected_board def board_hash(board): rows = [] for row in board: rows.append(','.join(map(str, row))) return '+'.join(rows) class Figure(BaseObject): data = None width = None height = None shift = None hash_key = None def __init__(self, data): self.data = data self.check_size() self.check_single_color() self.height = len(self.data) self.width = len(self.data[0]) self.shift = self.data[0].index(1) self.hash_key = self.get_key_hash() points = [] for i in xrange(self.height): for j in xrange(self.width): if self.data[i][j]: points.append((i, j)) self.points = tuple(points) def check_size(self): width = None for i in xrange(len(self.data)): next_width = len(self.data[i]) if next_width == 0: raise Exception('Empty row') if not width is None and width != next_width: print self.data raise Exception('Different lengths of rows') width = next_width def check_single_color(self): all_colors = set(itertools.chain(*self.data)) not_null_colors = list(all_colors - {0}) if len(not_null_colors) == 0: raise Exception('Empty figure') if len(not_null_colors) > 1: raise Exception('Too many colors') if not_null_colors[0] != 1: raise Exception('Need only one color: 1') def rotate_right(self): new_data = [] for j in xrange(self.width): new_row = [] for i in xrange(self.height - 1, -1, -1): new_row.append(self.data[i][j]) new_data.append(new_row) return Figure(new_data) def reflection(self): new_data = self.data[::-1] return Figure(new_data) def get_key_hash(self): rows = [] for row in self.data: rows.append(','.join(map(str, row))) return '+'.join(rows) @classmethod def generate_shadows(cls, init_figure_data): init_figure = cls(init_figure_data) result, hashes = [init_figure], [init_figure.hash_key] reflect_figure = init_figure.reflection() if reflect_figure.hash_key not in hashes: result.append(reflect_figure) hashes.append(reflect_figure.hash_key) for i in xrange(3): init_figure = init_figure.rotate_right() reflect_figure = reflect_figure.rotate_right() for figure in [init_figure, reflect_figure]: if figure.hash_key not in hashes: result.append(figure) hashes.append(figure.hash_key) return result @classmethod def generate_figures_dict(cls, figures_raw_list): result = {} for index, figure_raw in enumerate(figures_raw_list): result[index + 1] = Figure.generate_shadows(figure_raw) return result
f799bf4a9e39680a3536ab508507b22a5ca47db0
Handsome2Hu/py
/个人学习/main.py
1,953
3.765625
4
''' a = 1\n def fun(a): a = 2 fun(a) print (a) ''' """ a = [] def fun(a): a.append(1) fun(a) print (a) """ """ a = [1,2,3] print(a) b = a[:] print(b) c = a[1:1] print(c) """ """ a = 1 b = 2 a,b = b,a print (b) """ """ array = [1, 2, 5, 3, 6, 8, 4] print(array[2:]) print(array[2::]) """ """ t = (3.14, 'China', 'Jason', ['A', 'B']) l = t[3] l.append(1) print(t) """ """ d = {1:95,'a':1} print(d[0]) """ ''' a = ['a','b','c','d'] b = [1,2,3,4] c = dict(zip(b,b)) print(c) ''' ''' t = tuple(range(10)) print (t) ''' ''' L = [75, 92, 59, 68] print(sum(L) / 4) ''' ''' sum = 0 x = 1 n = 1 while True: if n <= 20: sum+=x x=x*2 n+=1 else: break print(sum) ''' ''' sum = 0 x = 0 while True: x = x + 1 if x > 100: break if x%2 == 0: continue sum += x print (sum) ''' ''' for x in range(1,9): for y in range(10): if x<y: print(x*10+y) ''' ''' d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 } for key in ['Adam', 'Lisa', 'Bart']: print ("%s: %d"%(key, d[key])) ''' ''' d = { 95: 'Adam', 85: 'Lisa', 59: 'Bart' } d[72] = 'Paul' print(d) ''' ''' d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 } for key in d: print (key + ":",d[key]) ''' ''' months = set(('Feb','Sun')) x1 = 'Feb' x2 = 'Sun' if x1 in months: print( 'x1: ok') else: print( 'x1: error') if x2 in months: print ('x2: ok') else: print( 'x2: error') ''' ''' s = set(['Adam', 'Lisa', 'Paul','a']) L = ['Adam', 'Lisa', 'Bart', 'Paul'] m = set(L) p = s -m q = m -s s = p | q print (p) print (q) print (s) ''' ''' L = range(1,100) print (sum([i*i for i in L])) ''' ''' def average(*args): if len(args) == 0: return 0.0 else: return sum(args)/len(args) print( average()) print( average(1, 2)) print( average(1, 2, 2, 3, 4)) ''' ''' for i in range(1,101): print(i) ''' print ([x for x in range(1,101,7)])
0410ef9fbcd6daea41d871240ed6d9c381db76bc
ErickViz/Quiz09.py
/Problema4.py
181
3.890625
4
#Quiz09 #Problema4 def fibonacci(x): if(x==0) or (x==1): return(x) if(x>1): return fibonacci(x-1)+ fibonacci(x-2) x=int(input("Dame una posición: ")) a=fibonacci(x) print(a)
3a57147c73b969380a5254016d67b6465ebe42a3
yoloshao/yolowork
/re/非贪婪07.py
615
3.765625
4
# 正则中默认使用的是贪婪匹配,尽可能多的匹配字符 import re s = 'nums contains 12 23 34' m = re.match('.+(\d+ \d+ \d+)', s) print(m) print(m.group(1)) # 非贪婪匹配 针对* + ? {} 后面使用? 取消贪婪 m = re.match('.+?(\d+ \d+ \d+)', s) print(m) print(m.group(1)) m2 = re.match('[a-z]+\d+','abc123dfg') print(m2) m3 = re.match('[a-z]+\d+?','abc123dfg') print(m3) s = '<tr><td>123</td></tr><tr><td>erer</td></tr>' l = re.findall('<tr>.*</tr>', s) print(l) # 如果使用分组,将分组中的内容放入列表中返回 l1 = re.findall('<tr>.*?</tr>', s) print(l1)
3408dd72ba6c6204c17e22752c02ca6c6446b2a4
rupshabagchi/shroominen
/model/scrape_mushroom_urls.py
3,793
3.671875
4
# Functions to scrape data from mushroom.world # If called from the command line, the script prints out a json object of mushroom information # example: # python scrape_mushroom_urls.py 'http://www.mushroom.world/show?n=Amanita-virosa' 'http://www.mushroom.world/show?n=Galerina-marginata' # # See the comments above the functions for further documentation # # Tuomo Nieminen 10/2017 from bs4 import BeautifulSoup import requests import sys import re import json # Scrape mushroom url # # scrape_mushroom_url takes as input an url to a page in mushroom.world containing information # related to a single mushroom and returns a python dictionary of information (including image url's) # related to the mushroom. # # @param url An url to a mushroom web page in mushroom.world # # @return # Returns a python dictionary containing the following keys: # - name1: (string) Name of the mushroom. # - name2 (string) Name given in parenthesis. Can be '' if no such name was given # - images: (list) A list of image urls # - info: (dict) A dictionary of information related to the mushroom. # keys: Family, Location, Dimensions, Edibility, Description (dict) # Description keys: General, Cap, Gills, Stem # # @examples # # from bs4 import BeautifulSoup # import requests # # url = 'http://www.mushroom.world/show?n=Galerina-marginata' # mushroom = scrape_mushroom(url) # print(mushroom) # def scrape_mushroom(url): # retrive site data as BeautifullSoup object data = requests.get(url).text soup = BeautifulSoup(data, 'html.parser') # etract and parse name, labels (Family, Location, Dimensions, Edibility, Description) # and content text related to the labels name_content = soup.find(class_ = "caption").find("b").contents names = re.sub('[^A-Za-z0-9( ]+', '', name_content[0]).split("(") names = [n.strip() for n in names] name1 = names[0] if(len(names) > 1): name2 = names[1] else: name2 = '' labels = soup.find_all(class_ ="labelus") labels = [label.contents[0] for label in labels] texts = soup.find_all(class_ = "textus") texts = [text.contents[0] for text in texts] # extract mushroom description as a dictionary description = soup.find(class_ = "longtextus").contents description = [re.sub('[^A-Za-z0-9,.<> ]+', '', str(d)).strip() for d in description] description = [re.sub('<b>', '', d) for d in description if (d != "") & (d != "<br>")] description.insert(0, 'General') description = dict(zip(description[0::2], description[1::2])) texts.append(description) assert len(labels) == len(texts) # find image urls images = soup.find(id="mushroom-list").find_all(class_ = "image") image_urls = ['http://www.mushroom.world' + image.a["href"] for image in images] # contruct the mushroom dictionary mushroom = dict(name1 = name1, name2 = name2, images = image_urls, info = dict(),) # add labels as keys and text as values for i in range(len(labels)): mushroom["info"][labels[i]] = texts[i] return mushroom # Get shrooms # Get shoorm takes as input a list of mushroom urls and scrapes each url using scrape_mushroom(). # # @param urls A list of mushroom.world mushroom page urls # # @return Returns a list of python dictionaries returned by scrape_mushroom(). # See the documentation of scrape_mushroom for details of the dictionaries. # @examples # # urls = ['http://www.mushroom.world/show?n=Amanita-virosa', 'http://www.mushroom.world/show?n=Galerina-marginata'] # shrooms = GetShrooms(urls) # # import json # json.dumps(shrooms) # def GetShrooms(urls): return [scrape_mushroom(url) for url in urls] if __name__ == '__main__': shrooms = GetShrooms(sys.argv[1:]) print(json.dumps(shrooms))
c83f6cef59077419479b4d0b6627697bbc2ae790
Wisetorsk/INF-200-Notes
/Python/dice_strategy.py
1,767
3.65625
4
import random import sys def roll_dice_and_compute_sum(ndice): return sum([random.randint(1, 6) for i in range(ndice)]) def computer_guess(ndice): return random.randint(ndice, 6*ndice) def player_guess(ndice): return 12 def play_one_round(ndice, capital, guess_function): guess = guess_function(ndice) throw = roll_dice_and_compute_sum(ndice) if guess == throw: capital += guess else: capital -= 1 return capital, throw, guess def play(ngames,nrounds, ndice=2): wins = {'Machine': 0, 'You': 0, 'D': 0} for i in xrange(ngames): player_capital = computer_capital = nrounds # start capital for j in range(nrounds): player_capital, throw, guess = \ play_one_round(ndice, player_capital, player_guess) computer_capital, throw, guess = \ play_one_round(ndice, computer_capital, computer_guess) if computer_capital > player_capital: winner = 'Machine' elif computer_capital < player_capital: winner = 'You' else: winner = 'D' wins[winner] += 1 return wins def sample_run(): print '\nWelcome to game of guessing !' print '==============================\n' n_exp = int(raw_input('Number of games per strategy combination: ')) n_rounds = int(raw_input('Number of rounds per game: ')) seed = int(raw_input('random generator seed: ')) random.seed(seed) results = play(n_exp, n_rounds) print '---------------------------' print 'Machine wins You wins Draw' print ' ',results['Machine'],' ',results['You'],' ',results['D'] print if __name__ == '__main__': sample_run()
33ea1c0c21e940c65a184c1da1122533f0fa8aa2
dottormarmitta/QF_ComputationalFinance
/WrittenTests/Ex2.py
1,383
3.578125
4
# © Guglielmo Del Sarto -> guglielmo.delsarto@outlook.com # # # Part 1 (function) # # # My task-performing method: # # @param sentence, word are strings # @return a list of string def getListWithWordsContainingLetters(sentence, word): word = word.lower() i = 0 outputList = [] while (i < len(sentence)): letterDict = getEvenDictionary(word) k = i while i < len(sentence) and isALetter(sentence[i]): letterDict[sentence[i].lower()] = 1 i += 1 if (getSum(letterDict) == len(letterDict)): outputList.append(sentence[k:i]) i += 1 return outputList def isALetter(c): if (ord(c) >= 65 and ord(c) <= 90) or (ord(c) >= 97 and ord(c) <= 122): return True else: return False def getEvenDictionary(string): outputDict = {} for i in range(len(string)): if (i%2 == 0): outputDict[string[i]] = 0 return outputDict def getSum(dictonary): sum = 0 for v in dictonary: sum += dictonary[v] return sum # # # Part 2: some testing # # s = "AbraCadabrae may my dREams coMe true! MaYbe this time for Real. YeS!!" w1 = "aLe" print("I expect to have: 'AbraCadabra', 'dReams', 'MaYbe', 'Real': ") print(getListWithWordsContainingLetters(s, w1)) print() w2 = "MAy" print("I expect to have: 'may', 'my', 'MaYbe': ") print(getListWithWordsContainingLetters(s, w2))
749031e5b7cf767a36791864bb8591339f2a6e85
whitepaper2/data_beauty
/leetcode/085_maximal_rectangle.py
1,781
3.703125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/1/17 下午5:49 # @Author : pengyuan.li # @Site : # @File : 084_largest_rectangle_area.py # @Software: PyCharm from typing import List def maximalRectangle(matrix: List[List[str]]) -> int: """ 求得最大矩形面积,组成直方图 :param matrix: 元素由0、1组成 :return: int """ if matrix is None: return 0 m = len(matrix) if m == 0: return 0 n = len(matrix[0]) heights = [0] * n out = 0 for i in range(m): for j in range(n): heights[j] = 0 if matrix[i][j] == '0' else (heights[j] + 1) out = max(out, largestRectangleArea2(heights)) return out def largestRectangleArea2(heights: List[int]) -> int: """ 输入直方图,输出构成的矩阵面积最大,Time Limited 寻找局部最大值(第i值大于第i+1值),与前面数值形成矩形面积取最大 :param heights: 直方图高度 :return: 最大矩阵面积 """ if heights is None: return 0 width = len(heights) if width == 0: return 0 out = 0 for i in range(width): if i + 1 < width and heights[i] <= heights[i + 1]: continue minH = heights[i] for j in range(i, -1, -1): minH = min(minH, heights[j]) area = minH * (i - j + 1) out = max(out, area) return out if __name__ == "__main__": matrix = [['1', '0', '1', '0', '0'], ['1', '0', '1', '1', '1'], ['1', '1', '1', '1', '1'], ['1', '0', '0', '1', '0']] print(maximalRectangle(matrix)) heights = [2, 1, 5, 6, 2, 3] print(largestRectangleArea2(heights)) heights = [2] print(largestRectangleArea2(heights))
2871fee9b23c94ae374c27235e29d624a237fa97
tohain/aoc2020
/day_04.py
1,387
3.515625
4
import sys def parse_entries( fn ): entries = [] #init first empty dict for first passport pairs = dict() # go through all lines, when reading an empty line, add current # dict to entries array and clear it for the next passport entries with open( sys.argv[1], 'r' ) as ff: for line in ff: line=line.strip() if(line == "" ): #finished, add tmp dict and clear it entries.append( pairs ) pairs = dict() else: for i in line.split(" "): tmp=i.split(":") pairs[tmp[0]] = tmp[1] return entries # check for valid entries here. might want to move the actual validity # check into separate function, especially for part 2 def check_entries( data ): counter_valid = 0 counter_invalid = 0 for i in data: if len(i) == 8: counter_valid+=1 elif len(i) == 7: if( 'cid' not in i ): counter_valid+=1 else: counter_invalid+=1 return counter_valid, counter_invalid if __name__ == '__main__': # parse the entire file and create a dict/map for each passport data = parse_entries( sys.argv[1] ) # count valid entries cv, ci = check_entries( data ) print(f"valid={cv} invalid={ci}")
31f880a01896215e0cbbbfa82619050da881a482
ennima/pauta_bk
/ejercicio.py
356
3.71875
4
import os ejercicios_circuito = 5 max_repeticiones = 4 ejercicio_acumulado = 0 circuito_acumulado = 0 for i in range(0,max_repeticiones): print("Repeticiones: ",i + 1) ejercicio_acumulado += i + 1 print("Acumulado: ",ejercicio_acumulado) circuito_acumulado = ejercicio_acumulado * ejercicios_circuito print("Circuito Acumulado:",circuito_acumulado)
8bda8aa4ebd7ba467f74bce8096552c2ba408fcd
SricardoSdSouza/Curso-da-USP
/Exercicios enviado3/fatorial.py
295
4.0625
4
valor = int(input("Digite o número a ser fatorado ")) fatorial = 1 n = valor ''' while valor >1: fatorial = fatorial * valor valor = valor -1 print("O Fatorial de :",n,"é = ",fatorial) ''' def fatorial(valor): fatorial = fatorial * n print("fatorial de ",valor," é: ",n)
03a12fb2c928816418dd5d50349d54c496571364
ulkutonbuloglu/py-for-neuro
/exercises/solution_01_09.py
244
3.515625
4
DNA = "AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC" nucleotides = { "adenine": DNA.count("A"), "thymine": DNA.count("T"), "guanine": DNA.count("G"), "cytosine": DNA.count("C") } print(nucleotides)
edeff44596291f1d7387df6dccbf1d0036cd1453
yu-ichiro/atcoder-workspace
/abc214/D/main.py
1,348
3.640625
4
#!/usr/bin/env python3 import sys def solve(N: int, U: "List[int]", V: "List[int]", W: "List[int]"): union_find = [-1 for _ in range(N)] def root(x): return x if union_find[x] < 0 else root(union_find[x]) def size(x): return -union_find[root(x)] def union(x, y): x, y = map(root, (x, y)) if size(y) > size(x): x, y = y, x union_find[x] += union_find[y] union_find[y] = x edges = [(w, u-1, v-1) for u, v, w in zip(U, V, W)] edges.sort() cost = 0 for w, u, v in edges: cost += w * size(u) * size(v) union(u, v) print(cost) return # Generated by 2.6.0 https://github.com/kyuridenamida/atcoder-tools (tips: You use the default template now. You can remove this line by using your custom template) def main(): def iterate_tokens(): for line in sys.stdin: for word in line.split(): yield word tokens = iterate_tokens() N = int(next(tokens)) # type: int u = [int()] * (N - 1) # type: "List[int]" v = [int()] * (N - 1) # type: "List[int]" w = [int()] * (N - 1) # type: "List[int]" for i in range(N - 1): u[i] = int(next(tokens)) v[i] = int(next(tokens)) w[i] = int(next(tokens)) solve(N, u, v, w) if __name__ == '__main__': main()
7626569ffdc6fb54fe2693ff086322342a0b7509
platzi/curso-profesional-python
/palidrome.py
202
3.65625
4
def is_palindrome(string: str) -> bool: string = string.replace(' ', '').lower() return string == string[::-1] def run(): print(is_palindrome(1000)) if __name__ == '__main__': run()
b165f9330ec29d2e152a071c96833edadbc3894e
aammokt/newProject
/python101/large/guess_the_number_v5.py
933
4.03125
4
# Added logic to allow player to restart a game after a win # import random sec_no = random.randint(1, 10) chances = int(5) print("I am thinking of a number between 1 and 10.") print("You have 5 guesses left.") while chances > 0: user_guess = int(input("What's the number? ")) if user_guess > 10 or user_guess < 1: print("Please enter a number between 1 and 10.") elif user_guess == sec_no: print("Yes! You win!") playon = input("Do you want to play again (Y or N)? ").upper() if playon == "N": print("Bye!") break else: chances = 5 elif user_guess < sec_no: print(f'{user_guess} is too low.') chances -= 1 elif user_guess > sec_no: print(f'{user_guess} is too high.') chances -= 1 if chances != 0: print(f'You have {chances} guesses left') else: print("You ran out of guesses!")
ef96db17056613dc6f0d755a1259965f959bc2c8
noevazz/learning_python
/050_importing_a_module.py
1,311
4.1875
4
# Importing a module is done by an instruction named import. import math # math is part of the Python standard library # we can import multiple modules using multiple imports or using one: import sys, random # these modules were imported juts to show you how to import do not pay much attention # the other option is: # import module1 # import module2 # import module3 # import moduleX # now we can use the methods an variables of the math module: print(math.pi) # note that we need to use the name of the module + dot + the name of the function/method/variable/etc. # btw if you want to know all the names provided through a particular module use the dir function: print(dir(math)) # if the module's name has been aliased, you must use the alias, not the original name. # if you want to use only a specific featur you can import only that feature: from math import sin, radians # with this kinf of import you are not required to use math.sin, just use sin() print( sin( radians(90) ) ) # you can also use an alias: from math import factorial as facto print(facto(3)) # aliases are also for whole modules: import random as ran print(ran.randint(6, 10)) from math import sin as ss, radians as rr print(rr(180)) # the most agresive import is when you import everything from a module: from math import *
317b9f1b492ccaca7008024a6b55fb336a4f13f5
1KimJiHyeon/BaekJoon-Algorithm
/if문/5543.py
604
3.6875
4
# 나의 답1 bugger = [] for i in range (3): bugger.append(int(input())) coke=int(input()) for coke_price in range(3): bugger[coke_price] = bugger[coke_price] +coke-50 soda=int(input()) for soda_price in range(3,len(bugger)): bugger[soda_price] = bugger[soda_price] +soda-50 print(min(bugger)) # 나의 답2 bugger = [] for i in range (5): bugger.append(int(input())) bugger_set = [] for coke_price in range(3): bugger_set.append(bugger[coke_price] +bugger[3]-50) for soda_price in range(3): bugger_set.append(bugger[soda_price] +bugger[4]-50) print(min(bugger_set))
1c3e2d5b1e2335c04d38c7c4b341b256d8d6ee1e
Sarah-A/training_fullstack_python
/restaurants_list_from_scratch/tst/database_sandbox.py
2,327
3.765625
4
""" insert data into the (previously created) database to test and play with it """ from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine from database_setup import Base, Restaurant, MenuItem engine = create_engine('sqlite:///restaurant_menu.db') Base.metadata.bind = engine # bind the engine DBSession = sessionmaker(bind=engine) session = DBSession() #---------------------------------------------------------------- # Create: #---------------------------------------------------------------- # pizza_palace = Restaurant(name = "Pizza Palace") # session.add(pizza_palace) # session.commit() #---------------------------------------------------------------- # Read: #---------------------------------------------------------------- # print(session.query(Restaurant).first()) # cheese_pizza = MenuItem(name = "Cheese Pizza", # description = "Made with fresh mozzarella", # course = "Entry", # price = "$8.99", # restaurant = pizza_palace) # session.add(cheese_pizza) # session.commit() # restaurants = session.query(Restaurant).all() # for restaurant in restaurants: # print("{}-{}".format(restaurant.id, restaurant.name)) #---------------------------------------------------------------- # Update: #---------------------------------------------------------------- # veggie_burgers = session.query(MenuItem).filter_by(name = 'Veggie Burger') # for veggie_burger in veggie_burgers: # if veggie_burger != "$2.99": # veggie_burger.price = "$2.99" # session.add(veggie_burger) # session.commit() # for veggie_burger in veggie_burgers: # print veggie_burger.id # print veggie_burger.name # print veggie_burger.description # print veggie_burger.price # print veggie_burger.restaurant.name # print "\n" #---------------------------------------------------------------- #Delete: #---------------------------------------------------------------- # spinach_icecream = session.query(MenuItem).filter_by(name = 'Spinach Ice Cream').one() # print spinach_icecream.restaurant.name # session.delete(spinach_icecream) # session.commit() # spinach_icecream = session.query(MenuItem).filter_by(name = 'Spinach Ice Cream').one() restaurants = session.query(Restaurant).all() for restaurant in restaurants: print("{}-{}".format(restaurant.id, restaurant.name))
a423d8106acc0e873633233615e14e13503d0e1c
mfouquier/Python-Crash-Course
/Chapter 4/slices.py
815
4.9375
5
#Create a FOR loop that lists out the different types of pizza in the list. pizzas = ['supreme', 'hawaiian', 'meat lovers', 'pepperoni', 'sausage', 'cheese'] #for pizza in pizzas: # print(f"Give me a {pizza.title()} pizza and I will be happy.") #print("Pizza is the best!") #Use SLICES on a previous project from Chapter 4. Project above. #Print the first three items using SLICE print("The first three items in the list are:") for pizza in pizzas[:3]: print(pizza.title()) print("\n") #Print items from the middle of the list using SLICE print("These are items from the middle of the list:") for pizza in pizzas[1:4]: print(pizza.title()) print("\n") #Print the last three items using SLICE print("These are the last items in the list:") for pizza in pizzas[-3:]: print(pizza.title())
b577ab144dd2297c5663feba2b4aabeebfcb340e
Chenzf2018/pythonDataStructure
/sequencelist.py
1,236
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- 'sequence list' __author__ = 'lxp' #《大话数据结构》48页 class Seqlist(object): def __init__(self, maxsize = 30): self.maxsize = maxsize self.data = [None] * maxsize self.length = 0 def showlist(self): for i in range(self.length): print(self.data[i], ',', end = '') print('') def add(self, data): if self.length == self.maxsize: return self.data[self.length] = data self.length = self.length + 1 def insert(self, data, index): if self.length == self.maxsize - 1 or index > self.length: return for i in range(self.length - index): self.data[self.length - i] = self.data[self.length - i - 1] self.data[index] = data self.length = self.length + 1 def getNode(self, index): if index > self.length - 1 or index < 0: return return self.data[index] def delete(self, index): if index > self.length - 1 or index < 0: return for i in range(self.length - index - 1): self.data[index + i] = self.data[index + i + 1] self.length = self.length - 1 #test def test(): L = Seqlist(10) for i in range(8): L.add(i) L.insert(100, 0) L.delete(100) L.showlist() print(L.getNode(8)) if __name__ == '__main__': test()
382d9689820696ba2987e5e8ca33fc1c3caf06c7
PRABH18/python
/Add_sub_mul_div.py
236
3.921875
4
#Addition,Subtract,Muliplication,Division a=float(input("Enter the Value of a ")) b=float(input("Enter the Value of b ")) c=a+b d=a-b e=a*b f=a/b print("Add of a+b",c) print("Sub of a-b",d) print("Mul of a*b",e) print("Div of a/b",f)
cd8e9c1eee07194fcbcfd81ed1be0462f41c14e3
CarlosViniMSouza/Python-Instagram
/others/python-tip-n3.py
262
3.828125
4
a, b, c, d = 18, 14, 12, 16 condition = [a >= 0, b <= 10, c >= 12, d <= 20] if any(condition): print("Condition okay") else: print("Condition not-okay") if all(condition): print("Condition okay") else: print("Condition not-okay")
022cbc2f64264c7b5d5596605e33a3e4fa0b36ef
xctn/AlienInvasion
/alien_invasion_setting.py
1,218
3.53125
4
#coding:utf-8 #!/usr/bin/python # 游戏设置属性 class Settings(object): """ 存储《外星人入侵》的所有设置的类 """ def __init__(self): # 窗口属性 self.screen_width = 1200 self.screen_height = 800 self.bg_color = (255,255,255) # 飞船属性 self.ship_speed_factor = 4 # 子弹属性 self.bullets_allowed = 10 self.bullet_speed_factor = 5 self.bullet_width = 113 self.bullet_height = 15 self.bullet_color = 60,60,60 # 外星人属性 self.alien_speed_factor = 2 self.fleet_drop_speed = 10 # fleet_direction 1 表示向右移动,为-1表示向左移动 self.fleet_direction = 1 self.ship_limit = 3 self.speedup_scale = 1.1 self.initialize_dynamic_settings() self.alien_points = 50 self.score_scale = 1.5 def initialize_dynamic_settings(self): self.ship_speed_factor = 1.5 self.bullet_speed_factor = 5 self.alien_speed_factor = 2 self.fleet_direction = 1 def increase_speed(self): """ 提高速速设置 """ self.ship_speed_factor *= self.speedup_scale self.bullet_speed_factor *= self.speedup_scale self.alien_speed_factor *= self.speedup_scale self.alien_points = int(self.alien_points * self.score_scale)
091dc9ca3b9b52ddd7af7cc0a65042b86a9c5eec
xiang-daode/Python3_codes
/tkinter10按钮[横向]与绘图器-1.py
2,864
3.6875
4
import tkinter as tk;import math;from tkinter import * #先制作图片:按钮.png root = tk.Tk();root.title("数学函数作图器");x0,y0=400,300 w = tk.Canvas(root, width =900, height = 600);w.pack() #版权标签: lb=tk.Label(text="---by daode1212 2021-10-23---", fg="black", bg="white").pack(side='bottom') #自编函数N个: def myDraw1(): w.create_line(0, 300, 800, 300, fill = "red", dash = (2, 2)) w.create_line(400, 0, 400, 600, fill = "blue", dash = (3, 3)) w.create_text(80,20,text='画二条线段作坐标轴') def myDraw2(): w.create_rectangle(x0-25, y0-25, x0+25, y0+25, fill = "red") def myDraw3(): w.create_oval(155,155,255,255, fill="#44eeff") def myDraw4(): w.create_polygon(212,455,573,47,89,481,23,514,55,466,221,44, fill="gray") def myDraw5(): coord = 10, 50, 240, 210 w.create_arc(coord, start=0, extent=60, fill="blue") def myDraw6(): r=150 for x in range(0,800,5): x1,x2=x-5,x+5 y1,y2=y0-r*math.sin(x/60) ,y0+r*math.sin(x/120) w.create_rectangle(x1, y1, x2, y2, fill = "#F4004F") w.create_text(80,40,text='这是绿色的矩形所组成的') def myDrawA(): r=150 for x in range(0,800,5): x1,x2=x-5,x+5 y1,y2=y0-r*math.sin(x/30) ,y0+r*math.sin(x/70) w.create_rectangle(x1, y1, x2, y2, fill = "#00F4F4") def myDrawB(): r=150 for x in range(0,800,5): x1,x2=x-5,x+5 y1,y2=y0-r*math.sin(x/160) ,y0+r*math.sin(x/80) w.create_rectangle(x1, y1, x2, y2, fill = "#40FF04") def myDrawC(): r=150 for x in range(0,800,5): x1,x2=x-5,x+5 y1,y2=y0-r*math.sin(x/60) ,y0+r*math.sin(x/180) w.create_rectangle(x1, y1, x2, y2, fill = "#F40F04") def myDel(): w.delete('all') #删除全部 #普通按钮: tk.Button(root, text = "添加图形1", command = (lambda: myDraw1())).pack(side='left') tk.Button(root, text = "添加图形2", command = (lambda: myDraw2())).pack(side='left') tk.Button(root, text = "添加图形3", command = (lambda: myDraw3())).pack(side='left') tk.Button(root, text = "添加图形4", command = (lambda: myDraw4())).pack(side='left') tk.Button(root, text = "添加图形5", command = (lambda: myDraw5())).pack(side='left') tk.Button(root, text = "添加图形6", command = (lambda: myDraw6())).pack(side='left') #图片式按钮: photo = tk.PhotoImage(file = '按钮.png') tk.Button(root, text="[按钮A]", command = (lambda: myDrawA()), image = photo, compound = "center").pack(side='left') tk.Button(root, text="[按钮B]", command = (lambda: myDrawB()), image = photo, compound = "center").pack(side='left') tk.Button(root, text="[按钮C]", command = (lambda: myDrawC()), image = photo, compound = "center").pack(side='left') #"删除全部图"按钮: tk.Button(root, text = "删除全部图", command = (lambda : myDel())).pack(side='left') root.mainloop()
5a1ee27dca884bde9783cfc8b2009db3484ba002
robedpixel/CZ2001ProjectPart2
/src/GraphFileReader.py
1,216
3.78125
4
from tkinter import Tk # from tkinter import Tk for Python 3.x from tkinter.filedialog import askopenfilename import snap class GraphFileReader: """ A Class to read a file containing a snap.py graph and load it into a PUNGraph object which can then be accessed """ def __init__(self): self.filename = "" self.Fin = "" self.pungraph = "" def read_file(self): """ Displays a gui file prompt to read a snap.py file """ Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing self.filename = askopenfilename(title='Select snap.py graph File') # show an "Open" dialog box and return the path to the selected file def read_graph(self) -> snap.PUNGraph: self.pungraph = snap.LoadEdgeList(snap.PUNGraph, self.filename, 0, 1) return self.pungraph def display_status(self): print(type(self.pungraph)) print("number of nodes:" + str(self.pungraph.GetNodes())) # Snap.py graph uses numbers to identify nodes # for NI in self.pungraph.Nodes(): # print("node: %d, out-degree %d, in-degree %d" % (NI.GetId(), NI.GetOutDeg(), NI.GetInDeg()))
d34ced80682feb72b59db9120929230d58dab24d
Miyuki-L/text-monopoly
/game.py
28,272
3.75
4
import random import json from time import sleep layout = 'board_layout.txt' # the text file with the name of each block on the board description = "properties_tax.json" # file containing information aobut land, utilities, tax class AI: """ simulator/ai that makes the decisions that players would make in monopoly. different methods in this class represents different playing styles of a player """ def __init__(self, bc, uc): """ Creates object of class AI. bc: buy chance of the player uc: upgrade chance of the player """ self.bc = bc # 0-1 always buy self.uc = uc def answer(self, prompt): """ gets a random number and based on that random number's relative position to the chance rate of that prompt type make a decision. input: prompt: str, the type of decision to make output: str: the decision made for that specific prompt. """ if prompt == 'buy': r = random.uniform(0,1)#random num 0-1 if r < self.bc: return 'y' return 'n' elif prompt == 'upgrade': r = random.uniform(0,1)#random num 0-1 if r < self.uc: return 'y' return 'n' class Land: """ Data Type representing Land in monopoly (those where the player could build houses). Contains the information of price, upgradeCost, colorset, rent and other relavant information """ def __init__(self, name, description): """ Construct object of type Class with the given name and description uses the description to get the information about price, rent, ... Attributes: """ self.name = name self.location = description['location'] self.price = description['price'] self.upgradeCost = description['upgradeCost'] self.rent = description['rent'] self.mortgage_val = description['mortgage'] self.mortgage = False self.colorSet = description['colorSet'] self.houses = 0 self.owner = '' #no one owns this property yet def cal_rent(self): """ Calculates the Rent that a player needs to pay for this property if they land on it. return int, amount of rent to pay """ houses = self.houses rent = self.rent[str(houses)] return rent class Railroad: """ Data Type representing Railroad in monopoly (Electric company/Water works). Contains the information of price, rent and other relavant information """ def __init__(self, name, description): """ Construct object of type Class with the given name and description uses the description to get the information about price, rent, ... Attributes: """ self.name = name self.location = description['location'] self.price = description['price'] self.rent = description['rent'] self.mortgage_val = description['mortgage'] self.mortgage = False self.owner = '' #Class Player def cal_rent(self): """ Calculates the Rent that a player needs to pay for this property if they land on it. return int, amount of rent to pay """ owner = self.owner num_owned = len(owner.railroad) rent = self.rent[str(num_owned)] return rent class Utilities: """ Data Type representing Utilities in monopoly (Electric company/Water works). Contains the information of price, rent and other relavant information """ def __init__(self, name, description): """ Construct object of type Class with the given name and description uses the description to get the information about price, rent, ... Attributes: """ self.name = name self.location = description['location'] self.price = description['price'] self.rent = description['rent'] self.mortgage_val = description['mortgage'] self.mortgage = False self.owner = '' #no one owns this property yet def cal_rent(self): """ Finds the amount to times the dice roll by when a player lands on this property return int, amount to multiply by """ owner = self.owner num_owned = len(owner.utilities) mult = self.rent[str(num_owned)] return mult class Taxes: """ Data Type representing Taxes in monopoly (Income/Luxury Tax). Contains the information of price and other relavant information """ def __init__(self, name, description): """ Construct object of type Class with the given name and description uses the description to get the information about price, ... Attributes: """ self.name = name self.location = description['location'] self.price = description['price'] class Player: """ A data type representing a monopoly player with name, position, money, and other relavant information """ def __init__(self, name): """Construct object of type Player with the given name Attributes: dbl_roll: keeps count of consecutive doubles jail: True/False in Jail jail_roll: Number of rolls rolled in jail properties: The properties they own""" self.name = name self.position = 0 self.money = 1500 self.dbl_roll = 0 self.jail = False self.jail_roll = 0 self.land = [] self.railroad = [] self.utilities = [] self.bankrupt = False self.operator = "" #who is playing the game human or ai self.ai = None self.color = None # terminal printing color def cprint(self, message): """ A print statement that prints the message in the color give to the player Adds color to the terminal version of the monopoly game input: player: object of Class Player message: str, the message to print """ print(f"\033[{self.color}m{message} \033[m") def cinput(self, question): """ Same as the default python input() function but prints the messeage in the color assciated with the player input: question: str, the question to print """ print(f"\033[{self.color}m{question} \033[m", end='') decision = input() return decision def dice_roll(self): """ Rolls dice and returns the value of the two dices Return: d1, d2 """ d1 = random.choice(range(1,7)) d2 = random.choice(range(1,7)) print(f"{self.name} rolled: {d1} {d2}") return d1,d2 def go_to_jail(self): """ Updates players information when they are sent to jail """ print(f"{self.name} going to jail.\n") self.dbl_roll = 0 self.jail = True self.position = 10 def move(self, d1, d2): """ updates player position and checks if player's position needs to be reset because they have reached the end of the board index 39. d1, d2: dice roll outputs """ self.position += d1 + d2 if self.position >= 40: self.position -= 40 self.money += 200 print(f"{self.name} passed Go and collected $200.") def print_position(self,board): """ Prints the block that landed on or is currently at Input: board: the game board """ block = board[self.position] if self.jail: # Player is in jail right now print(f"{self.name} is currently in Jail.\n") elif type(block) != str: # landed on properties print(f"{self.name} landed on {block.name}.\n") else: print(f"{self.name} landed on {board[self.position]}.\n") def post_jail(self): """ Moves the player when they leave the jail This is a separate function because rules are slightly different (Players do not get to roll again when they rolled a double) """ self.jail = False # Update information self.jail_roll = 0 print(f"{self.name} leaving jail. \n") d1, d2 = self.dice_roll() # roll again (this time for moving) self.move(d1, d2) def print_properties(self): """ Prints all of the properties the Player owns and the Mortgage/House values of those properties Return prop_dict, dictionary of prop.name to property """ prop_dict = {} # Printing Property Names print(f"{self.name}'s properties:") for prop_list in [self.land, self.railroad, self.utilities]: for prop in prop_list: if not prop.mortgage: # Not already mortgaged. if type(prop) == Land and prop.houses != 0: print(f"{prop.name : <25} Mortgage Value: ${prop.mortgage_val: 4} Houses: {prop.houses : <5} House value: ${((prop.upgradeCost)//2) : >4}") else: print(f"{prop.name : <25} Mortgage Value: ${prop.mortgage_val : 4}") name = prop.name.lower() # have more flexibility with user input prop_dict[name] = prop # Name: prop dict for easy access later print() return prop_dict def make_decision(self, question, prompt_type): """ determines based on how is the operator of the player, whether to prompt human for an answer or to have the ai make the decision Input: question: the question that is being asked, f string prompt_type: the type/purpose of the question, str e.g. buy """ if self.operator == 'human': decision = self.cinput(question) if prompt_type in ['buy', 'upgrade']: # buy and upgrade have the same type of decision while decision.lower() not in ['y', 'n', 'yes', 'no']: # valid input? self.cprint(f"\n{self.name}: You have ${self.money}.") decision = self.cinput(question) else: ai = self.ai decision = ai.answer(prompt_type) self.cprint(f"{question} {decision}") return decision def mortgage_prop(self, owe): """ Prompts the user to mortgage their property and adds the money they get from the mortgage to their money. Keeps prompting the user to sell houses/mortgage properties until thier money is more than the amout they owe Input: owe, int, the amount that they have to pay """ while self.money < owe: prop_dict = self.print_properties() if len(prop_dict) == 0: # no more properties to mortgage self.cprint(f"{self.name}: You are bankrupt. Game ends for {self.name}.\n") self.bankrupt = True return self.cprint(f"{self.name}: You have ${self.money}. You owe ${owe}") prop_name = self.cinput(f"{self.name}: Which property to you want to sell a house on or mortgage? ") prop_name = prop_name.lower() while prop_name not in prop_dict or prop_dict[prop_name].mortgage: # Make sure that they give a valid property prop_name = self.cinput(f"{self.name}: Which property to you want to sell a house on or mortgage? ") prop_name = prop_name.lower() prop = prop_dict[prop_name] if type(prop) == Land: # see if they have houses to sell houses = prop.houses house_val = prop.upgradeCost/2 if houses != 0: # They have houses they must sell first if houses == 'hotel': self.cprint(f"\n{self.name}: You have a hotel (5 houses) on {prop.name}. Value: {house_val}") houses = 5 # change to 5 so that it's easier to work with later else: self.cprint(f"\n{self.name}: You have {houses} houses on {prop.name}. Value: {house_val}") n = 6 # place holder while n > houses: try: # Check for valid input n = int(self.cinput(f"{self.name}: How many houses on {prop.name} do you want to sell? ")) except ValueError: print("Sorry, please try again") print() self.money += house_val * n # Update information prop.houses = houses - n continue # Go back to the beginig of the while loop print() mortgage_val = prop.mortgage_val # mortgaging property prop.mortgage = True self.money += mortgage_val # prop_dict.pop(prop_name, None) # None is the type to specifiy as if they can't find the key def buy(self, block): """ Prompts the user and askes if they want to buy the block they landed on. If yes, conduct the transcation Input: block, Land (class) """ self.cprint(f"{self.name}: You have ${self.money}.") # decision = input(f"{self.name}: Do you want to buy {block.name} (Price:{block.price})? [y/n] ") # while decision.lower() not in ['y', 'n', 'yes', 'no']: # valid input? # print(f"\n{self.name}: You have ${self.money}.") # decision = input(question) decision = self.make_decision(f"{self.name}: Do you want to buy {block.name} (Price:{block.price})? [y/n] ", 'buy') if decision.lower() in ['y','yes']: # buy if block.price <= self.money: # Have enough money self.money -= block.price # update information block.owner = self if type(block) == Land: self.land += [block] elif type(block) == Utilities: self.utilities += [block] elif type(block) == Railroad: self.railroad += [block] self.cprint(f"{self.name} bought {block.name}.") self.cprint(f"{self.name}: You have ${self.money}.\n") else: # not enough money self.cprint(f"{self.name}: You do not have enough money.\n") return else: print() def upgrade(self, block): """ Checks if an upgrade is avaliable if so Asks the owner of the block if they want to upgrade their property Input: block, class Land """ if block.houses == 'hotel': self.cprint(f"{self.name}: No upgrades avaliable for {block.name}\n") return if block.mortgage: self.cprint(f"{self.name}: {block.name} is under mortgage. No upgrades avaliable.\n") return print(f"{block.name} has {block.houses} houses and the current rent is ${block.cal_rent()}.") if block.houses == 4: print(f"If you upgrade to hotel the rent would be ${block.rent['hotel']}.") else: print(f"If you upgrade to {block.houses+1} houses the rent would be {block.rent[str(block.houses+1)]}.") self.cprint(f"{self.name}: You have ${self.money}.") # decision = input(f"{self.name}: Do you want to upgrade {block.name} (Cost:{block.upgradeCost})? [y/n] ") # while decision.lower() not in ['y', 'n', 'yes', 'no']: # valid input? # print(f"\n{self.name}: You have ${self.money}.") # decision = input(f"{self.name}: Do you want to upgrade {block.name} (Cost:{block.upgradeCost})? [y/n] ") decision = self.make_decision(f"{self.name}: Do you want to upgrade {block.name} (Cost:{block.upgradeCost})? [y/n] ", 'upgrade') if decision.lower() in ['y','yes']: # buy if block.upgradeCost <= self.money: # Have enough money block.houses += 1 if block.houses == 5: block.houses = 'hotel' self.cprint(f"\n{self.name} upgraded {block.name} to a hotel.") else: self.cprint(f"\n{self.name} upgraded {block.name} to {block.houses} houses.") self.money -= block.upgradeCost self.cprint(f"{self.name}: You have ${self.money}.\n") else: self.cprint(f"{self.name}: You do not have enough money. \n") else: print() def rent(self, block): """ checks the block that the player is on and see if they need to pay rent no rent if 1) their own block, 2) owner in jail or 3) property under mortgage """ owner = block.owner if not owner.jail: if not block.mortgage: # property not under mortgage if type(block) in [Land, Railroad]: # Land & Railroad have same method of rent calculation rent = block.cal_rent() elif type(block) == Utilities: d1, d2 = self.dice_roll() mult = block.cal_rent() rent = mult * (d1 + d2) if self.money < rent: # Call Mortgaging functions self.mortgage_prop(rent) if self.bankrupt: return self.money -= rent # Collect Rent owner.money += rent self.cprint(f"{self.name} payed {owner.name} ${rent} for landing on {block.name}.") self.cprint(f"{self.name}: You have ${self.money}.\n") else: # property played under mortgage print(f"{block.name} is under mortgage. No rent is payed. \n") else: # owner in jail print(f"{owner.name} is in jail. No rent is payed.\n") def check_block(self, block): """ Checks the Block that the player is currently on See if they could 1) buy the block, 2) upgrade the block, 3) pay Input: block: the block on the board the player is currently on """ if type(block) == Land: if block.owner != '': # Someone owns the land owner = block.owner if owner.name != self.name: # pay rent? self.rent(block) else: # upgrade? self.upgrade(block) else: # buy? self.buy(block) elif type(block) == Utilities: if block.owner != '': owner = block.owner if owner.name != self.name: # pay? self.rent(block) else: self.buy(block) # buy elif type(block) == Railroad: if block.owner != '': owner = block.owner if owner.name != self.name: # pay? self.rent(block) else: self.buy(block) # buy elif type(block) == Taxes: tax = block.price if self.money < tax: # Call Mortgaging functions self.mortgage_prop(tax) if self.bankrupt: # end call if bankrupt return self.money -= tax self.cprint(f"{self.name} payed ${tax} of {block.name}.") self.cprint(f"{self.name}: You have ${self.money}.\n") def player_turn(self, board): """ Moves the player for their turn. Input: board: the game board """ d1, d2 = self.dice_roll() if self.jail: # In jail self.jail_roll += 1 if self.jail_roll == 3: # in jail for 3 rounds print(f'{self.name} end of third turn in jail.') self.post_jail() self.print_position(board) elif d1 == d2: # rolled a double print(f'{self.name} rolled a double while in jail.') self.post_jail() self.print_position(board) else: self.print_position(board) else: while d1 == d2: # rolled double self.move(d1, d2) # update information self.dbl_roll += 1 self.print_position(board) if self.dbl_roll == 3: # Go to jail for 3 consecutive dbls print(f'{self.name} rolled 3 consecutive doubles.\n') self.go_to_jail() return # end turn elif self.position == 30: # Landed on go to jail self.go_to_jail() return # end turn else: # check block & roll again self.check_block(board[self.position]) # Looks at the checks if they could buy or have to pay if self.bankrupt: return else: d1, d2 = self.dice_roll() self.move(d1, d2) # update information self.dbl_roll = 0 self.print_position(board) if self.position == 30: # landed on go to jail self.go_to_jail() return # end turn self.check_block(board[self.position]) if self.bankrupt: return def read_json(filename): """ Takes in filename of json file that has the properties description for the monopoly and reads in the json return: property_dict, dict """ with open(filename) as f: property_dict = json.load(f) return property_dict def create_board(f_layout, f_json): """ Takes in a filename that leads to a file that contains what each block does on a new line for every block. Input: filename: txt file containing what each block does Output: list, the gameboard """ json_dict = read_json(f_json) f = open(f_layout, 'r') # read layout file lines = f.readlines() board = [] for line in lines: name = line[:-1] # get rid of \n at end of the line try: info = json_dict[name] except KeyError: # Not Land, utility or tax board += [name] else: # Land, utility or tax if info['type'] == "land": # land board += [Land(name, info)] elif info['type'] == 'utilities': # Utilities board += [Utilities(name,info)] elif info['type'] == 'railroad': # Railroad board += [Railroad(name,info)] else: # Tax board += [Taxes(name,info)] return board def create_players(): """ Prompts user for input of number of players to create and creates players Return: players: list, contain n players """ while True: try: n = int(input("PLease enter the number of players: ")) print() except ValueError: #checks if an int was inputted print("Sorry, please try again") continue else: if n <= 8: # limit to 8 players break players = [] cCodes = [91,92,93,94,95,96,97,90] for i in range(n): name = input("What is the player name? ") p= Player(name) p.color = cCodes[i] op = input("Who is operating the player? [human/ai] ") # Asks who is operating the game op = op.lower() while op not in ['human', 'ai']: op = input("Who is operating the player? [human/ai] ") op = op.lower() if op == 'ai': while True: try: bc = float(input("What is the player's buying channce? [0-1] ")) uc = float(input("What is the player's upgrading channce? [0-1] ")) print() except ValueError: #checks if an int was inputted print("Sorry, please try again\n") continue else: break p.ai = AI(bc, uc) p.operator = op else: p.operator = op print() players += [p] return players def game(f_layout=layout, f_json=description): """ Runs the Monopoly game Input: filename: .txt file, the file the contains the layout of the board default set to file included (board_layout.txt) """ board = create_board(f_layout, f_json) # setup players = create_players() p_index = 0 while True: current_p = players[p_index] if not current_p.bankrupt: current_p.player_turn(board) sleep(2) p_index += 1 # next player if p_index == len(players): # reset p_index p_index = 0 if len(players) == 1: # treat 1 player game differently player = players[0] if player.bankrupt: print(f'Game Over!!!\n') return player else: bankrupts = [player.bankrupt for player in players] if sum(bankrupts) == (len(players) - 1): # all but 1 player is bankrupt win_index = bankrupts.index(0) # Find index corresponding to winner winner = players[win_index] print(f'Game Over!!!\n {winner.name} wins the game. \n Congradulations {winner.name}') return winner if False: b = create_board(layout, description) p1 = Player('Hi') p2 = Player('Bye') p1.land = [b[39]] # b[39].houses = 4 # b[39].owner = p2 # b[39].mortgage = True # p1.money = 10 p1.utilities = [b[12]] # p1.railroad = [b[5]] # p1.check_block(b[39]) # p2.upgrade(b[39]) p1.buy(b[1]) if False: #testing simulator players = create_players() b = create_board(layout, description) block = b[39] for player in players: player.make_decision(f"{player.name}: Do you want to upgrade {block.name} (Cost:{block.upgradeCost})? [y/n] ", 'upgrade') p2.upgrade(b[39]) if True: win = game()
a54af8c564ae2edf192fe00d0fc84bd9bc00fbb5
hyun-minLee/20200209
/st01.Python기초/py05형변환/py05_03_형변환오류.py
673
3.875
4
# 숫자가 아닌 것을 정수로 변환하려고 할 때 # 숫자가 아닌 것을 실수로 변환 할 때 # 소수점이 있는 숫자 형식의 문자열을 int() 함수로 변환 할 때 try: i =int("안녕하세요") print(i) except ValueError: pass #print("숫자가 아닙니다. 다시입력하시오.") try: e=str("안녕하세요") print(e) except ValueError: print("숫자가 아닙니다. 다시입력하시오.") try: f=input("값을 입력하세요.") if f ==type(int) print(f) else: print("잘못된값입니다.") except ValueError: print("숫자가 아닙니다. 다시입력하시오.")
1f8e8074a6049cddad32684c5d32f90b3616292e
albertopha/ds-algo
/LC/297/297-py3.py
1,834
3.625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import deque class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ if not root: return '' queue = deque([root]) serialized = [] while queue: node = queue.popleft() if not node: serialized.append('null') else: serialized.append(str(node.val)) queue.append(node.left) queue.append(node.right) return ",".join(serialized) """ [1,2,3,null,null,4,5,null,null,null,null] """ def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ if not data: return serialized = deque(data.split(",")) root = TreeNode(serialized[0]) serialized.popleft() queue = deque([root]) while queue: node = queue.popleft() left = serialized.popleft() right = serialized.popleft() node.left = TreeNode(int(left)) if left != 'null' else None node.right = TreeNode(int(right)) if right != 'null' else None if node.left: queue.append(node.left) if node.right: queue.append(node.right) return root # Your Codec object will be instantiated and called as such: # ser = Codec() # deser = Codec() # ans = deser.deserialize(ser.serialize(root))
c91e7b31ecfde661b314375a0ff9561e59437117
alexartwww/geekbrains-python
/lesson_06/02.py
1,238
3.734375
4
task = ''' Реализовать класс Road (дорога), в котором определить атрибуты: length (длина), width (ширина). Значения данных атрибутов должны передаваться при создании экземпляра класса. Атрибуты сделать защищенными. Определить метод расчета массы асфальта, необходимого для покрытия всего дорожного полотна. Использовать формулу: длина * ширина * масса асфальта для покрытия одного кв метра дороги асфальтом, толщиной в 1 см * число см толщины полотна. Проверить работу метода. Например: 20м * 5000м * 25кг * 5см = 12500 т ''' class Road: def __init__(self, length, width): self._length = length self._width = width def calculate_mass(self, thickness): return self._length * self._width * thickness * 25 if __name__ == '__main__': print(task) road = Road(5000, 20) print('Mass = ', road.calculate_mass(5))
0f0a46bbe935c78ac43cc019a439416250b392b2
ztothez/Programming-for-networks-and-information-security-
/Build A Python Application/1_3_4_3_Option_3_Create_an_App_for_the_ISS_Input.py
1,631
3.65625
4
#Toni Tuunainen 1.3.4.3: Option 3 - Create an App for the ISS With Input import json, urllib.request, time, pgeocode #people in space url = "http://api.open-notify.org/astros.json" response = urllib.request.urlopen(url) result = json.loads(response.read()) people = result["people"] print("People in Space: " ,result["number"],"\n") for p in people: print(p["name"],p["craft"]) #where is iss url = "http://api.open-notify.org/iss-now.json" response = urllib.request.urlopen(url) result = json.loads(response.read()) location = result["iss_position"] isslat = float(location["latitude"]) isslon = float(location["longitude"]) print("Iss is at: ",isslat," ",isslon) #Ask user latitude country = input("Add country code: ") postalcode = input("Add postalcode: ") nomi = pgeocode.Nominatim(country) lists = nomi.query_postal_code(postalcode).tolist() #overheard on location url = "http://api.open-notify.org/iss-pass.json" url = url = url+"?lat="+str(lists[9])+"&lon="+str(lists[10]) response = urllib.request.urlopen(url) result = json.loads(response.read()) over = result["response"][1]["risetime"] readable = time.ctime(over) print("\nSeen next time on Turku: "+readable) #Passed today url = "http://api.open-notify.org/iss-pass.json" url = url+"?lat="+str(lists[9])+"&lon="+str(lists[10]) response = urllib.request.urlopen(url) result = json.loads(response.read()) times = result["request"]["passes"] duration = result["response"] print("\nPasses for today: ",times,"\n") for d in duration: print("The duration is: ",d["duration"],"\nThe risetime is: ",time.ctime(d["risetime"])) print("\nDuration means pass lenght in seconds")
518f5f73a543320a047f0e40ab03fbed0e6aa641
mritunjay2404/PythonProject
/for_loop.py
693
4
4
#for i in range(10): # print(f"mritunjay mukherjee : {i}") # example 1 : addition 20 numbers #total = 0 #for i in range (1,21): # total += i # print(total) # example 2 : add natural numbers input by user # total = 0 # num =input(" enter your number : ") # for i in range(1,num+1): # total += i #print(total) #example 3 : count character in a name # name = input("Enter ur name: ") #temp = "" #for i in range(0,len(name)): # if name[i] not in temp: # print(f"{name[i]} : {name.count(name[i])}") # temp += name[i] # example : 4 : sum of integer input by the user total = 0 n= input("Enter ur number : ") for i in range(0,len(n)): total += int(n[i]) print(total)
cad77bc21e1967e2d49ce7d32c5b91bd6ee568ec
chetandg123/cQubeTesting-1.8
/Data/demo2.py
1,444
4.03125
4
import os import time import unittest # class time_counter(unittest.TestSuite): # hour = int(input('Enter any amount of hours you want -+==> ')) # minute = int(input('Enter any amount of minutes you want -+==> ')) # second = int(input('Enter any amount of seconds you want -+==> ')) # time = hour*10800 + minute*3600 + second*60 # print('{}:{}:{}'.format(hour,minute,second)) # while time > 0: # time = time - 1 # seconds = (time // 60) % 60 # minutes = (time // 3600) # hours = (time // 10800) # print('Time Left -+==> ',hours,':',minutes,':',seconds,) # os.system("CLS") # if time == 0: # print('Time Is Over!') # import time as t # ##this will enable to utilize specified functions within time library such as sleep() # ##Asking user the duration for which the user wants to delay the process # seconds = int(input("How many seconds to wait")) # ##Let's use a ranged loop to create the counter # for i in range(seconds): # print(str(seconds - i) + " seconds remaining \n") # ##we also need the loop to wait for 1 second between each iteration # t.sleep(1) # print("Time is up") import datetime x = datetime.datetime.now() print("Started time is ", x) time.sleep(60*30) y = datetime.datetime.now() print("Ending time",y)
50d22d638e94489f4fb7db10cc3b683fce9e0513
HackerJonh/vscode_git
/Python/Grafico/Menu.pyw
2,604
3.546875
4
import tkinter as tk from tkinter import Menu, filedialog from tkinter import messagebox root = tk.Tk() #Creacion de una ventana Emergente def infoAdicional(): messagebox.showinfo("Programa Juan", "Practica Python Version 2021") def info_Licencia(): messagebox.showwarning("Licencia", "Producto bajo Licencia GNU") def salirAplicacion(): valor = messagebox.askquestion("Salir", "¿Desea salir de la Aplicacion?") #Si quremos cambiar el si o no por aceptar o cancelar debemos cambiar el metodo askquestion por askokcancel if valor == "yes": root.destroy() def cerrarDocumento(): valor = messagebox.askretrycancel("Reintentar", "No es posible cerrar.Documento Bloqueado") if valor == False: root.destroy() def Abrir_Fichero(): fichero = filedialog.askopenfilename(title="Abrir",filetypes=(("Ficheros de Excel","*.xls"),("Ficheros de Texto","*.txt"))) def new_windows(): nueva_ventana = tk.Toplevel(bg="blue") nueva_ventana.title("Nueva Ventana") Etiqueta = tk.Label(nueva_ventana, text="Nueva Ventana") Etiqueta.pack() barMenu = tk.Menu(root) root.config(menu=barMenu, width=300, height=300) Archivo = tk.Menu(barMenu, tearoff=0) Edicion = tk.Menu(barMenu, tearoff=0) Herramientas = tk.Menu(barMenu, tearoff=0) Ayuda = tk.Menu(barMenu, tearoff=0) barMenu.add_cascade(label="Archivo", menu=Archivo) # ---------Agregando submenu---------------- Archivo.add_command(label="Abrir", command=Abrir_Fichero) Archivo.add_command(label="Nuevo",command=new_windows) Archivo.add_command(label="Guardar") Archivo.add_command(label="Guardar Como") Archivo.add_separator() Archivo.add_command(label="Cerrar",command=cerrarDocumento) Archivo.add_command(label="Salir",command=salirAplicacion) barMenu.add_cascade(label="Edicion", menu=Edicion) # ---------Agregando submenu------------------ Edicion.add_command(label="Deshacer") Edicion.add_command(label="Rehacer") Edicion.add_command(label="Copiar") Edicion.add_command(label="Pegar") barMenu.add_cascade(label="Herramientas", menu=Herramientas) # -----------Agregando submenu----------------- Herramientas.add_command(label="Sleccionar Linea") Herramientas.add_command(label="Busqueda Avanzada") Herramientas.add_command(label="Filtrar ip") barMenu.add_cascade(label="Ayuda", menu=Ayuda) # -----------Agregando submenu------------------ Ayuda.add_command(label="Documentos") Ayuda.add_command(label="Informacion de Version",command=infoAdicional) Ayuda.add_command(label="Licencia",command=info_Licencia) Ayuda.add_command(label="configuracion Adicional") root.mainloop()
471a10e061cf88e8571b93b978e47348404a3279
yunghsin615/little_sun
/HW2/merge_sort_06170236.py
1,397
3.765625
4
#!/usr/bin/env python # coding: utf-8 # In[1]: class Solution(object): def merge_sort(self,nums): if len(nums) > 1 : middle = int (len(nums)/2) #有可能是奇數,所以用int left=self.merge_sort(nums[:middle]) #:擺在middle前面 right=self.merge_sort(nums[middle:]) #:擺在middle後面 return self.Merge(left,right) else: return nums def Merge(self,A,B): i = 0 j = 0 C=[] while (i<len(A) and j<len(B)): if(A[i]<=B[j]): C.append(A[i]) i=i+1 elif(A[i]>B[j]): C.append(B[j]) j=j+1 #某邊的值空了,另一邊剩下來的值要加到C裡面 while (i==len(A) or j==len(B)): if(i == len(A)): #i==len(A)表示A空了 C.append(B[j]) #再把B[j]這個數字加進C j=j+1 #可能剩下的不只一個數字,所以還要+1,再繼續跑迴圈 elif(j == len(B)): C.append(A[i]) i=i+1 while(i==len(A) and j==len(B)): #!!!這邊很重要!!!最後i==(A)而j也==len(B)時,迴圈就會一直跑,不會終止,所以設這個停止條件式 return C # In[2]: output = Solution().merge_sort([3,2,-4,6,4,2,19]) output
78c300775c4b4bee96b510c4d89f79702a138d3b
18bytes/whoopee
/problems/codejam/python/StoreCredit.py
580
3.578125
4
def store_credit1(credit, data): result = [] for i in range(1,len(data)): print i for j in range(i+1, len(data)): print "j: " + str(j) if data[i] + data[j] == credit: print data[i] + data[j] return [i, j] def store_credit2(C, L): for i in xrange(len(L) - 1): try: i2 = L.index(C - L[i], i + 1) return [i+1, i2+1] except ValueError: pass return None if __name__ == "__main__": credit = 100 data = [5, 2, 21, 34, 79, 43] print store_credit1(credit, data) print store_credit2(credit, data)
67c0b5521ef8b1082f8d51a7f98c892a545496dc
Oyanna/Decode_Python59
/dictionary/5.py
517
3.53125
4
user_list =[ ["+8783472834", "Anna"], ["476746", "Bob"], ["+877766", "Alice"]] user_dict = dict(user_list) print(user_dict) print(user_dict["+8783472834"]) print(user_dict["476746"]) user_dict["+3943837"] = "Aigul" print(user_dict) #user = user_dict["+211111"] key = "+211111" if key in user_dict: user = user_dict["+211111"] print(user) else: print("Не найден") key1 = "476746" if key1 in user_dict: user = user_dict["476746"] print(user) else: print("Не найден")
211905bbade5e1006c5eb171e9aad64bae5df25d
mr-karan/Udacity-FullStack-ND004
/Project1/assignments/turtle/turtleproject.py
266
3.578125
4
import turtle def draw_shape(): window = turtle.Screen() window.bgcolor("blue") jeff = turtle.Turtle() jeff.color("brown") jeff.shape("classic") jeff.speed(1) for i in range(36): jeff.rt(3) jeff.rt(120) jeff.fd(120) window.exitonclick() draw_shape()
a3c59a059f236361c53db7dded3c338e33baa542
sjdeak/interview-practice
/ds/trie/Add_and_Search_Word.py
1,329
3.921875
4
import os # 在Trie的基础搜索上增加单字符通配符支持 class WordDictionary: def __init__(self): self.isWordEnd = False self.children = {} def addWord(self, word: str) -> None: if not word: self.isWordEnd = True return firstCh = word[0] if firstCh not in self.children: self.children[firstCh] = WordDictionary() self.children[firstCh].addWord(word[1:]) def search(self, word: str) -> bool: if not word: return self.isWordEnd if word[0] == '.': return any([child.search(word[1:]) for child in self.children.values()]) if word[0] not in self.children: return False return self.children[word[0]].search(word[1:]) def startsWith(self, prefix: str) -> bool: if not prefix: return True if prefix[0] in self.children: return self.children[prefix[0]].startsWith(prefix[1:]) else: return False if __name__ == '__main__' and ('SJDEAK' in os.environ): wd = WordDictionary() print('wd.addWord("bad"):', wd.addWord("bad")) print('wd.addWord("dad"):', wd.addWord("dad")) print('wd.addWord("mad"):', wd.addWord("mad")) print('wd.search("pad"):', wd.search("pad")) print('wd.search("bad"):', wd.search("bad")) print('wd.search(".ad"):', wd.search(".ad")) print('wd.search("b.."):', wd.search("b.."))
ff7ae2d174e9cd2f295d378594cc67e3ca98ca68
balintnem3th/balintnem3th
/week-02/day-2/doubling.py
85
3.53125
4
ak = 123 def doubling(number): number *=2 return number print(doubling(ak))
b8f861e9ef711a0ca774f6e909c76f0a83472653
ArionDeno/inteligencia-artificial
/inteligencia_artificial2B/trabalho03/hill_climbing01.py
2,392
3.71875
4
#Steepest Ascent Hill Climbing # matriz matriz = [] #abre o arquivo para leitura with open('arquivo.txt') as fp: linhas = fp.readlines() # percorre as linhas for linha in linhas: colunas = linha.split(' ') matriz.append([int(x) for x in colunas if x != '']) # conveter em numero for i, linhas in enumerate(matriz): for j, colunas in enumerate(linhas): print(matriz[i][j]) #---------------------------- # pega os proximos # def pega_vizinho(solucao,aprendizado): vizinho =[] aprendizado = aprendizado / 10 if aprendizado >= 10 else 1 constante = 0.005 / aprendizado # viznho inf e sup vizinho_superior = solucao + constante if solucao + constante < else solucao vizinho_inferior = solucao - constante if solucao - constante > else solucao vizinho.append(vizinho_superior) vizinho.append(vizinho_inferior) return vizinho #------------------------ # calcula custo def fun_custo(x): custo = 2** -2 * (x - 0.1 /0.9) ** 2 * (math.sin(5* math.pi *x)) **6 return custo #------------------------ #------------------------ def subida_enconsta(estado,passo): solucao_custo = passo custos =[] quant =1 parar_subida = 0 while cout <= 400: vizinho = pega_vizinho(solucao_custo,quant) #------------------------------------ recente = fun_custo(solucao) melhor = recente custos.append(recente) #------------------------------------ for i in range(len(vizinho)): custo = fun_custo(vizinho[i]) if custo >= melhor: parar_no_morro =parar_no_morro + 1 if custo == melhor else 0 melhor = custo solucao = vizinho[i] quant += 1 if melhor == recente and solucao_atual == solucao or parar_no_morro ==20: if parar_no_morro == 20: print("Morro") break return solucao , custos #------------------------------------ # chamando a função custos =[] solucao =[] espaco_solucao =[] for i in range(10): for j in range(10): espaco_solucao.append(matriz[i][j]) solucao_sobe_morro = subida_enconsta[i] custos.append(subida_enconsta[i]) if len(custos) > 1: if max(custos[i] > max custos[i-1]): custos.pop(0) else: custos.pop(1) print("Val X", solucao_subida_encosta[0]) print("Custos", solucao_subida_encosta[1])
ec7fdac83894eb7836683d63d201973577d48901
ellynhan/challenge100-codingtest-study
/hall_of_fame/kimdonghun/[BOJ]10814_SortingByAge.py
490
3.546875
4
import sys from functools import cmp_to_key def compare(a,b): if a[0] > b[0]: return 1 elif a[0] == b[0]: return 0 else: return -1 N = int(sys.stdin.readline()) p_list = [] for i in range(N): cur_l = list(sys.stdin.readline().split()) #print(cur_l) p_list.append((int(cur_l[0]), cur_l[1])) #print(p_list) p_list = sorted(p_list, key=cmp_to_key(compare)) #print(p_list) for i in p_list: print(i[0], i[1])
e08699d68a3f82e0ae73a513a0e786a1a3af5976
evadeesteban/Python
/Python/Ver1.py
774
3.609375
4
#Codigo para inteligencia artificial basica import time from random import choice respuesta1 = input("Soy Diox, en que le puedo ayudar?"'\n') tm_tiempo = time.localtime() def tiempo(): global respuesta1 if respuesta1 == "Que hora es": print(time.asctime(tm_tiempo)) else: chiste() def chiste(): global respuesta1 if respuesta1 == "Cuentame un chiste": print(choice(["¿Qué sale de la cruza entre un mono y un pato? \n ¡Un monopatín!","- ¿Tienes WiFi? \n - Sí \n - ¿Y cuál es la clave? \n- Tener dinero y pagarlo."," Soy Rosa. \n - Ah, perdóname, es que soy daltónico."])) else: respuesta1 = input("Disculpe no le he entendido, ¿puede repetir?") tiempo() tiempo()
fb8b447198a73f93d5a8b218e9af869a76ecc707
ujjavalkag/pythonassignment
/module1/expr_eval3.py
132
3.65625
4
x,y=2,5 z=((x+3)*x**2)/(y-4)*(y+5) print(z) a=(2*x+6.22*(x+y))/(x+y) print(a) x=((12*x**3)+8*x**2)/(4*x)+x**3/(8*x) print(x)
2a28037799fe44ecec09e0bcd10149928625800d
akshayd500/HackerRank-Python
/Python If-Else.py
282
3.90625
4
#Problem Statement #https://www.hackerrank.com/challenges/py-if-else/problem if __name__ == '__main__': n = int(input().strip()) if n%2 == 1 : print("Weird") elif 2<=n and n<=5: print("Not Weird") elif n<=20: print("Weird") else: print("Not Weird")
c960578b16d13dc651c56c4a8020d0567b4c1195
shriki001/Operating-Systems
/Python/Class/ex1.py
1,752
3.734375
4
#%%--------------------------------------------------------------------------%%# #ex1.1 print("""‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ M A I N ‐ M E N U ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ 1. Good 2. Good luck 3. Excellent ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐  """) f = int(input("Enter your choice [1‐3] :")) if f == 1: print("Good...") elif f == 2: print("Good Luck...") elif f == 3: print("Excellent...") else: print("Error") ################################################################################ #ex1.2 a = int(input("Enter your first number:")) b = int(input("Enter your second number:")) print("""‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐  C A L C U L A T I O N S ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐  1. Addition 2. Subtraction 3. Multiplication 4.  Division   5. Floor Division 6. Modulus 7. Exponent ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐  """) f = int(input("Enter your choice [1‐7] :")) def calc(num, x1, x2): if num == 1: return x1 + x2 elif num == 2: return x1 - x2 elif num == 3: return x1 * x2 elif num == 4: return x1 / x2 elif num == 5: return x1 // x2 elif num == 6: return x1 % x2 elif num == 7: return x1 ** x2 else: print("Error") exit(1) print("The result is:", calc(f, a, b)) #%%--------------------------------------------------------------------------%%#
cb3b0dad17e0e7cb79c6331e1cd95b35219b13e9
github81/algoexpert.io
/selection-sort/program.py
425
3.96875
4
def minimumIndex(beginIndex, array): minIndex = beginIndex for i in range(beginIndex,len(array)): if array[i] < array[minIndex]: minIndex = i return minIndex def selectionSort(array): # Write your code here. for idx in range(0,len(array)): minIndex = minimumIndex(idx,array) print(minIndex) if minIndex != idx: minNum=array[minIndex] array.pop(minIndex) array.insert(idx,minNum) return array
994a2cf81e70032ed2ac278da6fddc38f663f94e
jmcs811/interview_prep
/inverview_espresso/strings_arrays/1_first_unique_char.py
505
3.546875
4
# TIME: O(n) # SPACE: O(1) def first_char(arr): char_dict = {} for char in arr: if char in char_dict: char_dict[char] += 1 else: char_dict[char] = 1 for i, char in enumerate(arr): if char_dict[char] == 1: return i return -1 # TIME: O(n^2) # SPACE: O(1) def first_char_alt(arr): for i, char in enumerate(arr): if arr.index(char) == arr.rindex(char): return i return -1 print(first_char('aabb'))
975c1c78960c887a40385632d0cafb0528d6dbf0
fh42/hackerrank
/warmup/alternating-characters.py
435
3.859375
4
# topic: hackerrank.com # problem: alternating characters # author: frank havemann # date: 2014-12-26 import sys def consecutive_chars( characters ): deletions = 0 for i in range(0,len(characters)-1): if characters[i] == characters[i+1]: deletions += 1 return deletions cntTestCases = int(raw_input()) for i in range(0,int(cntTestCases)): record = raw_input() print consecutive_chars( record )
ba6e9200b1df4f84229a375a323dac974726663e
pichetbuu/IntroducingPython-py38
/Chapter 6/Chapter-6.py
6,669
3.78125
4
class Person(): pass someone = Person() class Person(): def __init__(self): pass class Person(): def __init__(self, name): self.name = name hunter = Person('Elmer Fudd') print('The mighty hunter: ', hunter.name) class Car(): pass class Yugo(Car): pass give_me_a_car = Car() give_me_a_yugo = Yugo() class Car(): def exclaim(self): print("I'm a Car!") class Yugo(Car): pass give_me_a_car = Car() give_me_a_yugo = Yugo() give_me_a_car.exclaim() give_me_a_yugo.exclaim() class Car(): def exclaim(self): print("I'm a Car!") class Yugo(Car): def exclaim(self): print("I'm a Yugo! Much like a Car, but more Yugo-ish.") give_me_a_car = Car() give_me_a_yugo = Yugo() give_me_a_car.exclaim() give_me_a_yugo.exclaim() class Person(): def __init__(self, name): self.name = name class MDPerson(Person): def __init__(self, name): self.name = "Doctor " + name class JDPerson(Person): def __init__(self, name): self.name = name + ", Esquire" person = Person('Fudd') doctor = MDPerson('Fudd') lawyer = JDPerson('Fudd') print(person.name) print(doctor.name) print(lawyer.name) class Car(): def exclaim(self): print("I'm a Car!") class Yugo(Car): def exclaim(self): print("I'm a Yugo! Much like a Car, but more Yugo-ish.") def need_a_push(self): print("A little help here?") give_me_a_car = Car() give_me_a_yugo = Yugo() give_me_a_yugo.need_a_push() give_me_a_car.need_a_push() class Person(): def __init__(self, name): self.name = name class EmailPerson(Person): def __init__(self, name, email): super().__init__(name) self.email = email bob = EmailPerson('Bob Frapples', 'bob@frapples.com') bob.name bob.email class EmailPerson(Person): def __init__(self, name, email): self.name = name self.email = email car = Car() car.exclaim() Car.exclaim(car) class Duck(): def __init__(self, input_name): self.hidden_name = input_name def get_name(self): print('inside the getter') return self.hidden_name def set_name(self, input_name): print('inside the setter') self.hidden_name = input_name name = property(get_name, set_name) fowl = Duck('Howard') fowl.name fowl.get_name() fowl.name = 'Daffy' fowl.name fowl.set_name('Daffy') fowl.name class Duck(): def __init__(self, input_name): self.hidden_name = input_name @property def name(self): print('inside the getter') return self.hidden_name @name.setter def name(self, input_name): print('inside the setter') self.hidden_name = input_name fowl = Duck('Howard') fowl.name fowl.name = 'Donald' fowl.name class Circle(): def __init__(self, radius): self.radius = radius @property def diameter(self): return 2 * self.radius c = Circle(5) c.radius c.diameter c.radius = 7 c.diameter c.diameter = 20 class Duck(): def __init__(self, input_name): self.__name = input_name @property def name(self): print('inside the getter') return self.__name @name.setter def name(self, input_name): print('inside the setter') self.__name = input_name fowl = Duck('Howard') fowl.name fowl.name = 'Donald' fowl.name fowl.__name fowl._Duck__name class A(): count = 0 def __init__(self): A.count += 1 def exclaim(self): print("I'm an A!") @classmethod def kids(cls): print("A has", cls.count, "little objects.") easy_a = A() breezy_a = A() wheezy_a = A() A.kids() class CoyoteWeapon(): @staticmethod def commercial(): print('This CoyoteWeapon has been brought to you by Acme') CoyoteWeapon.commercial() class Quote(): def __init__(self, person, words): self.person = person self.words = words def who(self): return self.person def says(self): return self.words + '.' class QuestionQuote(Quote): def says(self): return self.words + '?' class ExclamationQuote(Quote): def says(self): return self.words + '!' hunter = Quote('Elmer Fudd', "I'm hunting wabbits") print(hunter.who(), 'says:', hunter.says()) hunted1 = QuestionQuote('Bugs Bunny', "What's up, doc") print(hunted1.who(), 'says:', hunted1.says()) hunted2 = ExclamationQuote('Daffy Duck', "It's rabbit season") print(hunted2.who(), 'says:', hunted2.says()) class BabblingBrook(): def who(self): return 'Brook' def says(self): return 'Babble' brook = BabblingBrook() def who_says(obj): print(obj.who(), 'says', obj.says()) who_says(hunter) who_says(hunted1) who_says(hunted2) who_says(brook) class Word(): def __init__(self, text): self.text = text def equals(self, word2): return self.text.lower() == word2.text.lower() first = Word('ha') second = Word('HA') third = Word('eh') first.equals(second) first.equals(third) class Word(): def __init__(self, text): self.text = text def __eq__(self, word2): return self.text.lower() == word2.text.lower() first = Word('ha') second = Word('HA') third = Word('eh') first == second first == third first = Word('ha') first print(first) class Word(): def __init__(self, text): self.text = text def __eq__(self, word2): return self.text.lower() == word2.text.lower() def __str__(self): return self.text def __repr__(self): return 'Word("' self.text '")' first = Word('ha') first # uses __repr__ print(first) # uses __str__ class Bill(): def __init__(self, description): self.description = description class Tail(): def __init__(self, length): self.length = length class Duck(): def __init__(self, bill, tail): self.bill = bill self.tail = tail def about(self): print('This duck has a', self.bill.description, 'bill and a', self.tail.length, 'tail') a_tail = Tail('long') a_bill = Bill('wide orange') duck = Duck(a_bill, a_tail) duck.about() from collections import namedtuple Duck = namedtuple('Duck', 'bill tail') duck = Duck('wide orange', 'long') duck duck.bill duck.tail parts = {'bill': 'wide orange', 'tail': 'long'} duck2 = Duck(**parts) duck2 duck2 = Duck(bill = 'wide orange', tail = 'long') duck3 = duck2._replace(tail='magnificent', bill='crushing') duck3 duck_dict = {'bill': 'wide orange', 'tail': 'long'} duck_dict duck_dict['color'] = 'green' duck_dict duck.color = 'green'
1f6ae9095497e5f15a61f45e714e76f14cb4bd45
iCodeIN/data_structures
/greedy/huffman_coding.py
1,302
3.78125
4
from heapq import heappush, heappop, heapify from collections import defaultdict def HuffmanEncode(characterFrequency): """Huffman encode the given dict mapping symbols to weights""" heap = [[freq, [sym, ""]] for sym, freq in characterFrequency.items()] heapify(heap) while len(heap) > 1: lo = heappop(heap) hi = heappop(heap) for pair in lo[1:]: pair[1] = '0' + pair[1] for pair in hi[1:]: pair[1] = '1' + pair[1] heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:]) print(heap) return sorted(heappop(heap)[1:], key=lambda p: (len(p[-1]), p)) if __name__ == '__main__': # time: O(nlogn) # based on frequnecy of the words, build a tree where most frequent at top # need to go left append 0, need to go right append a 1 # most frequent use fewer bytes than ones below inputText = "this is an example for huffman encoding" characterFrequency = defaultdict(int) for character in inputText: characterFrequency[character] += 1 print(characterFrequency) print("\n") huffCodes = HuffmanEncode(characterFrequency) print("\n") print("Symbol\tFrequency\tHuffman Code") for p in huffCodes: print("%s\t%s\t%s" % (p[0], characterFrequency[p[0]], p[1]))