blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
43f484dc485ff29975bea1a2427d8b502d0ff4b6
eeandr/assignments-Andronov
/Assignment_4_AE.py
1,081
3.5
4
#! /usr/bin/env python from __future__ import print_function, division # Task 2 """" :param a: str :param b: str """"" def p_distance(a,b): if len(a) != len(b): raise ValueError('lengths differ') diffs = 0 gaps = 0 for pair in zip(a,b): if pair[0] == pair[1]: diffs += 1 elif '-' in [pair[0], pair[1]]: gaps += 1 return diffs / (len(a) - gaps) # Task 3 """" :param a: list :param b: list """"" def matrix_product(a, b): ia = len(a) ja = len(a[0]) mb = len(b[0]) matr = [[[0] * mb] for _ in xrange(ia)] for m in xrange(0, mb - 1): for i in xrange(0, ia - 1): for j in xrange(0, mb - 1): matr[m][i] += (a[i][j] * b[j][i]) # 'a problem: matr[m][i] is list, not integer' return matr # compu_complexity O(N1 * N2* N3) # Task 1 # nat_row = [1,2,3 .... n] # For any i,j <= n / 2 : nat_row[i-1] + nat_row[-i] = nat_row[j-1] + nat_row[-j] # sum(nat_row) = (nat_row[0] + nat_row[-1]) * n / 2
b60c5b69b64f747b0e8006ac22b56979d6f16198
Sravaniram/pythonprogramming
/mirror list or not.py
108
3.640625
4
s=int(input()) a=input().split() l=input().split() if(sorted(l)==a): print("yes") else: print("no")
38179717b10493e88e3763bd31da34707767ed05
Alessandro-Francia/Compiti-per-10-12
/es_3.py
486
3.9375
4
vocali = ["a","e","i","o","u", " "] while True: italiano = input ("dimmi una parola o una frase in italiano") rovarspraket = "" for lettera in italiano: if lettera not in vocali: rovarspraket += lettera + "o" + lettera else: rovarspraket += lettera print ("la parola in rovarspraket è", rovarspraket) continuare = input ("scrivi 'si' se vuoi inserirne un'altra ") if continuare != "si": break
fe8bd8d77032563b3fc5f61a43463c583b845983
erick1984linares/t08_linares_rojas
/rojas/iteracion.py
1,184
4.1875
4
#6. ITERACION+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #1.Imprimir la palabra nam="mejor" for letra in nam: print(letra) #2.Imprimir la palabra nem="ser" for letra in nem: print(letra) #3.Imprimir la palabra pen="temido" for letra in pen: print(letra) #4.Imprimir la palabra lin="que" for letra in lin: print(letra) #5.Imprimir la palabra zan="amado" for letra in zan: print(letra) #6.Imprimir la palabra dro="---" for letra in dro: print(letra) #7.Imprimir la palabra its="El" for letra in its: print(letra) #8.Imprimir la palabra il="FIN" for letra in il: print(letra) #9.Imprimir la palabra fit="JUSTIFICA" for letra in fit: print(letra) #10.Imprimir la palabra sub="LOS" for letra in sub: print(letra) #11.Imprimir la palabra med="MEDIOS" for letra in med: print(letra) #12.Imprimir la palabra uni="UNPRG" for letra in uni: print(letra) #13.Imprimir la palabra esc="EPIE" for letra in esc: print(letra) #14.Imprimir la palabra fim="FACFYM" for letra in fim: print(letra) #15.Imprimir la palabra thm="python" for letra in thm: print(letra)
ce770d24d7ebbdb7ce872495559d9cca76b6cedb
yejiiha/BaekJoon_step
/for/2739.py
191
3.8125
4
# Say the multiplication tables. n = int(input()) if 1 <= n <= 9: for i in range(1, 10): print(f"{n} * {i} = {n*i}") else: print("1~9 범위의 정수를 입력하시오. ")
4aabaf3d797a74ae0aead09a958e14408fe8fa83
khand420/Learn-Python
/Exersice/Try_Catch_Exception.py
445
3.859375
4
# a = input("What is your Name") # b = input("How much do you Earn") # if int(b) == 0: # raise ZeroDivisionError("b is 0 so stopping the Program") # if a.isnumeric(): # raise Exception("Number are not allowed") # print(f"Hello{a}") c = input("Enter you name: ") try: print(a) except Exception as e: if c == "Khand": raise ValueError("Khand is blocked he is not allowed") print("Exception Handled (:")
1773a9a7ae20bb934ec85ee643a9f50f8fd3ffcf
genkinanodesu/competitive
/AtCoder/ABC/abc107/abc107d.py
1,782
3.609375
4
''' ☆長さnの数列Aの中央値がxであるとは 1.x以上の要素が (n + 1)// 2 個以上 2.そのようなxの中で最小 ということ。 ''' class BIT: def __init__(self, n): self.bit = [0] * (n+1) def sum(self, i): ''' :param i: :return: bit[i]までの和 ''' s = 0 while i > 0: s += self.bit[i] i -= i & -i return s def add(self, i, x): ''' :param i: :param x: :return: bit[i]にxを加える ''' while i < len(self.bit): self.bit[i] += x i += i & -i ''' def median(L): n = len(L) L.sort() return L[n // 2] ''' N = int(input()) a = list(map(int, input().split())) def ans_bigger(X): ''' 答えがX以上かどうかを判定 つまり、区間[l. r]のうち中央値がX以上であるものが ((N+1) * N /2 + 1 ) //2 個以上かを判定 ''' a_X = [1 if a[i] >= X else -1 for i in range(N)]#中央値かどうかの判定には大小関係しかいらない->1, -1に変換 cum = [N] for i in range(N): cum.append(cum[i] + a_X[i]) #累積和を取るが、BITを使うため全部0以上に(初項N) b = BIT(2 * N + 1) ans = 0 for j in range(N + 1): ans += b.sum(cum[j]) b.add(cum[j], 1) if ans >= ((N+1) * N /2 + 1 ) //2: return True else: return False l = min(a) r = max(a) + 1 #区間[l, r)を2分探索 「答えがX以上であるもの」のうち最大のものを返す while r > l + 1: if ans_bigger((l + r) // 2): l = (l + r) // 2 else: r = (l + r) // 2 print(l)
d80d6ef2509569dc71fbdf40e168b650e8731030
Bagnis-Gabriele/Sistemi_e_Reti_Quarta
/python/00007_carte.py
1,183
3.953125
4
""" Bagnis Gabriele Esercizio 7: Correzione della verifica sulle carte """ import random """ classi: carta """ #creazione della struttura class carta(object): def __init__(self, seme, numero): self.seme = seme self.numero = numero def stampa(self): print(f"la carta ha seme {self.seme} con numero {self.numero}") """ funzioni: push, pop, coppaMazzo """ #funzione push della pila def push(stack, element): stack.append(element) return stack #funzione pop della pila def pop(stack): element = stack.pop() return stack, element def coppaMazzo(stack): pos=random.randint(0,len(stack)-1) stack = stack[pos:len(stack)] + stack[0:pos] return stack def mischiaMazzo(stack): stack1=[] while stack!=[]: stack=coppaMazzo(stack) stack1.append(stack.pop()) return stack1 """ Codice """ Mazzo = [] Semi = ["C","Q","F","P"] for i in range (1,14): for s in Semi: push(Mazzo, carta(s,i)) for i in Mazzo: i.stampa() Mazzo=coppaMazzo(Mazzo) print("\n\nmazzo coppato:\n") for i in Mazzo: i.stampa() Mazzo=mischiaMazzo(Mazzo) print("\n\nmazzo mischiato:\n") for i in Mazzo: i.stampa()
50e673f64544f95a18e7781a1627d5b07207632e
DenisYavetsky/PythonBasic
/lesson6/task5.py
1,449
3.703125
4
# 5. Реализовать класс Stationery (канцелярская принадлежность). Определить в нем атрибут title (название) и метод draw # (отрисовка). Метод выводит сообщение “Запуск отрисовки.” Создать три дочерних класса Pen (ручка), Pencil (карандаш), # Handle (маркер). В каждом из классов реализовать переопределение метода draw. Для каждого из классов методы должен # выводить уникальное сообщение. Создать экземпляры классов и проверить, что выведет описанный метод для каждого # экземпляра. class Stationery: def __init__(self, title): self.title = title def draw(self): return 'Запуск отрисовк.' class Pen(Stationery): def draw(self): return f'{self.title}, Запуск отрисовки.' class Pencil(Stationery): def draw(self): return f'{self.title}, Запуск отрисовки.' class Handle(Stationery): def draw(self): return f'{self.title}, Запуск отрисовки. ' a = Pen('Ручка') b = Pencil('Карандаш') c = Handle('Маркер') print(f'{a.draw()}\n{b.draw()}\n{c.draw()}\n')
22e0d7c2ead704db650cf27a148aeb513695c466
Maykit/fizzbuzz
/fizzbuzz.py
449
4.34375
4
# Fizzbuzz counts up to entered number and prints "fizz" if a number can be divided by 3, "buzz" if a number can be divided by 5 and "fizzbuzz" if a number can be divided by both 3 and 5. enter = int(raw_input("Select a number between 1 and 100: "))+1 for var in range(1,enter): if var % 15 ==0: print "fizzbuzz" elif var % 5 == 0: print "buzz" elif var % 3 == 0: print "fizz" else: print(var)
ab6b7cdf2aa3fe423fb8db14887587dfcec9d393
ricardowiest/Python_CURSO
/Ex042.py
522
4.0625
4
m1=float(input('Digite a 1ª medida: ')) m2=float(input('Digite a 2ª medida: ')) m3=float(input('Digite a 3ª medida: ')) if m1+m2>m3 and m2+m3>m1 and m1+m3>m2: print ('Pode ser formado um triângulo.') if m1==m2==m3: print ('\033[1:31mEsse triângulo é equilátero.\033[m') elif m1!=m2!=m3!=m1: print('\033[1:33mEsse triângulo é Escaleno.\033[m') else: print('\033[1:32mEsse triângulo é Isóceles.\033[m') else: print('Não pode ser formado um triângulo.')
9ab8dbc702336569a990e175e350ea06883662c2
williamHuang5468/leetcode
/Third Week/347 Top K Frequent Elements.py
1,864
3.71875
4
''' 法一 使用 build-in,去排序 dictiionary ''' ''' class Solution(object): def topKFrequent(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ numberDict = {} for i in nums: if i not in numberDict: numberDict[i] = 1 else: numberDict[i] +=1 result = self.orderValue(numberDict) return [result[i][0] for i in range(k)] def orderValue(self, dict): from operator import itemgetter return sorted(dict.items(), key=itemgetter(1), reverse=True) ''' ''' 法二 直接使用相關 lib class Solution(object): def topKFrequent(self, nums, k): from collections import Counter result = Counter(nums).most_common(k) return [result[i][0] for i in range(k)][::-1] ''' ''' 暴力解,超 慢 ~ 待改善 ''' class Solution(object): def topKFrequent(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ numberDict = {} for i in nums: if i not in numberDict: numberDict[i] = 1 else: numberDict[i] +=1 sortDict = sorted(numberDict.values(), reverse= True) result = [] for i in range(k): for key,value in numberDict.items(): if value is sortDict[i] and key not in result: result.append(key) break return result[::-1] s = Solution() assert s.topKFrequent([1,2], 2) == [1,2] assert s.topKFrequent([1,1,2], 1) == [1] assert s.topKFrequent([1,1,2], 2) == [1,2] assert s.topKFrequent([1,1,1,2,2,3], 2) == [1,2] assert s.topKFrequent([4,1,-1,2,-1,2,3], 2) == [-1,2]
53ff9ae81f67500932ccb3ed4dc09619b44bddf7
jinruiiii/MIT-6.0001
/Pset1/Pset1c.py
2,238
4
4
# Part C: Finding the right amount to save away # User input annual salary salary = int(input("Enter starting salary: ")) # Calculate the initial monthly salary monthly_salary = float(salary/12) # Cost of dream house total_cost = 1000000 # Cost of down payment down_payment = 1000000 * 0.25 # Initializing number of steps of binary search to 0 steps = 0 # Initializing semi annual raise semi_annual_raise = 0.07 # Initializing returns r = 0.04 # Initializing lower boundary of binary search low = 0 # Initializing upper boundary of binary search high = 10000 # Initializing number of months as 0 counter = 0 counter_1 = 0 # Initializing the saving rate saving_rate = 0 # Initializing total savings total_savings = float(0) # Checking is saving all the salary will be less than the downpayment for i in range(36): counter = counter + 1 if counter % 6 == 0: monthly_salary = round(monthly_salary * (1 + semi_annual_raise), 2) total_savings = round(total_savings + (monthly_salary * 1) + ((total_savings * r )/ 12),2) if total_savings < down_payment: counter_1 = 1 print("It is not possible to pay for the downpayment in 3 years") # Looping until a suitable saving rate is found while abs(total_savings - down_payment) >= 100: if counter_1 == 1: break # Reseting appropriate varibales total_savings = 0.00 counter = 0 monthly_salary = round(float(salary/12),2) saving_rate = round(float((low + high) / 20000),4) for i in range(36): counter = counter + 1 # Afer every 6th months salary will increase if counter % 6 == 0: monthly_salary = round(monthly_salary * (1 + semi_annual_raise), 2) total_savings = round(total_savings + (monthly_salary * saving_rate) + ((total_savings * r )/ 12),2) # Search upper half if savings less than downpayment if total_savings < down_payment: low = int(saving_rate * 10000) # Search lower half if savings more than downpayment else: high = int(saving_rate * 10000) steps = steps + 1 if counter_1 == 0: print(f"steps: {steps}") print(f"saving rate: {saving_rate}") print(f"total savings: {total_savings}")
9859bfe30175d9c14a11798c1737872495778e10
Mauricio-KND/holbertonschool-higher_level_programming
/0x02-python-import_modules/0-add.py~
173
3.890625
4
#!/usr/bin/python3 from add_0 import add def adding(): a = 1 b = 2 print("{:d} + {:d} = {:d}".format(a, b, add(a, b))) if __name__ == "__adding__": adding()
3e53c0331261f783aed4dbeeb966a16999b99b47
rafaelperazzo/programacao-web
/moodledata/vpl_data/29/usersdata/109/9642/submittedfiles/atividade.py
193
3.71875
4
# -*- coding: utf-8 -*- from __future__ import division import math n=int(input('Digite o valor de n:')) cont=0 while True: s=(n//10) cont=cont+1 n=s if s<1: break print cont
b6b6ff27aef268805658abbfc90af042eafa9058
ursu1964/Algorithms-in-Python-1
/06-Stacks-Queues-Deques/Exercises/Project/P6-34.py
720
4
4
import stackarray as Stack def postfix_evaluate(expr): """Evaluate the given postfix operation""" stack = Stack.ArrayStack() operators = ['*','+','-','/','^'] for char in expr: if char not in operators: stack.push(int(char)) else: num1 = stack.pop() num2 = stack.pop() if char == '+': stack.push(num1+num2) elif char == '-': stack.push(num2-num1) elif char == '*': stack.push(num1 * num2) elif char == '/': stack.push(num2 // num1) return stack.top() # Testing if __name__ == "__main__": print(postfix_evaluate('53+83-*4/'))
f9cf1f688a94969ad4a17440cabd0995c80825d8
Arj09/mca101_manisha
/evil.py
196
3.59375
4
def evilNumber(num): count = 0 binnum = bin(num) length = len(binnum) for i in range(2,length): if binnum[i] == '1': count += 1 if count % 2 == 0: return True else: return False
3e5e9df93970036f8ef7bbda4b6fb74579b396b8
xiu-du-du/akk8
/Python-directory/0905.py
3,432
4.21875
4
# 选择结构 ''' year = 2020 # 单分支 if year > 2021: print("不是2021") # 双分支 if year > 3030: print("未来") else: print("现在") # 多分支 if year < 1998: print("1") elif year == 2000: print("2") elif year >= 2020: print("3") else: print("4") # 多层选择结构的使用 day = 2020 moon = True if day >= 2020: if moon: print('yes') else: print('no') else: print("day not 2020!") # 三目运算符 rs = '1' if day == 2020 else '2' print(rs) ''' # 作业一 ''' 第一种: if 条件语句: 表达式 第二种: if 条件语句: 表达式 else: 表达式 第三种: if 条件语句: 表达式 elif 条件语句: 表达式 elif 条件语句: 表达式 else: 表达式 第四种: if 条件语句: if 条件语句: 表达式 elif 条件语句: 表达式 else: 表达式 else: 表达式 第五种: 表达式 if 条件语句 else 表达式 ''' # 作业二 ''' x = input('输入x坐标:') y = input('输入y坐标:') if int(x) > 0: if int(y) > 0: print('你输入的坐标在第一象限') elif int(y) < 0: print('你输入的坐标在第四象限') elif int(x) < 0: if int(y) > 0: print('你输入的坐标在第二象限') elif int(y) < 0: print('你输入的坐标在第三象限') ''' # 作业三 ''' info = input('请输入分数:') if int(info) >= 90: print('你的分数是:A') elif 80 <= int(info) <= 89: print('你的分数是:B') elif 70 <= int(info) <= 79: print('你的分数是:C') elif 60 <= int(info) <= 69: print('你的分数是:D') else: print('你的分数是:E') ''' ''' a = 50 print(type(a)) b = 50 str(b) print(type(b)) ''' # 循环结构 # while 循环 ''' a = 1 b = 0 while a <= 100: b += a a += 1 print(f'a的值是{a},1~100的和是:{b}。') # for 循环 for a in 'python': print(a) for name in ['x', 't', 'z']: print(name) # range(开始,结尾,步长) 默认从0开始 rs = 0 for i in range(1, 101): rs += i print(f'a的值是{i},1~100的和是:{rs}。') ''' # 嵌套循环 '''' tmp = [ ['1', '2', '3'], ['11', '22', '33'], ['111', '222', '333'], ['1111', '2222', '3333'], ] ''' ''' i = 1 for count in tmp: print(f'周{i}观看指南:') for a in count: print(a) ''' # range() 返回下标 ''' for a in range(len(tmp)): print(f'周{a+1}观看指南:') for name in tmp[a]: print(name) ''' # enumerate() 返回下标和下标对应的值 ''' for a, count in enumerate(tmp): print(f'周{a+1}观看指南:') for name in count: print(name) ''' # 作业一 i = 0 tmp1 = 0 # 累加和 while i < 101: tmp1 += i i += 1 print(tmp1) a = 0 tmp2 = 0 # 偶数和 while a < 101: if a % 2 == 0: tmp2 += a a += 1 print(tmp2) b = 0 tmp3 = 0 # 奇数和 while b < 101: if b % 2 == 1: tmp3 += b b += 1 print(tmp3) # 作业二 i = 0 tmp1 = 0 # 累加和 for i in range(0, 101): tmp1 += i i += i print(tmp1) a = 0 tmp2 = 0 # 偶数和 for a in range(0, 101): if a % 2 == 0: tmp2 += a a += 1 print(tmp2) b = 0 tmp3 = 0 # 奇数和 for b in range(0, 101): if b % 2 == 1: tmp3 += b b += 1 print(tmp3) # 作业三 i = 0 a = 0 for i in range(5): for a in range(4): print(i, end=' ') print(i)
4226389aa2099cee2b9bff59483e77f77c195077
CBJNovels/python_study
/venv/Training/P3_Training_exception.py
1,492
4.15625
4
# #异常 # try: # print(5/0) # except: # print("You can't divide by zero!") # # #处理ZeroDivisionError异常 # print("Give me two numbers,and I'll divide them.") # print("Enter 'q' to quit.") # # while True: # first_number=input("\nFirst number: ") # if first_number == 'q': # break # second_number=input("Second_number: ") # try: # answer=int(first_number)/int(second_number) # except ZeroDivisionError:#ZeroDivisionError异常对象 # print("You can't divide by zero!") # else: # print(answer)#输出结果 # #注释结束 # #处理FileNotFoundError异常 # # filename='alice.txt' # # try: # # with open(filename) as f_obj: # # contents=f_obj.read() # # except: # # msg="Sorry,the file "+filename+" does not exist." # # print(msg) # # #注释结束 # #分析文本方法 # # filename='alice.txt' # filenames=['alice.txt','siddhartha.txt'] # # def count_words(filename): # """计算文本单词数""" # try: # with open(filename) as f_obj: # contents=f_obj.read() # except FileNotFoundError: # # pass#略过 # msg="Sorry,the file "+filename+" does not exist." # print(msg) # else: # words=contents.split()#以空格为分隔符拆分字符串为列表 # num_words=len(words) # print("The file "+filename+" has about "+str(num_words)+" words.") # # for filename in filenames: # count_words(filename) # #注释结束
f59927407db804c0469205b9df7640a40cee03d0
AdamZhouSE/pythonHomework
/Code/CodeRecords/2120/60631/254317.py
153
3.90625
4
n = int(input()) if n==2: print(1) else: three = n//3 el = n%3 if 3**three*el==27: print(36) else: print(3**three*el)
8bf0b2ea708648027644c80bdb0bb09b7bbb5a2c
AkiraXD0712/LeetCode-Exercises
/Container With Most Water.py
1,269
3.859375
4
import json """ Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. Note: You may not slant the container and n is at least 2. """ class Solution: def maxArea(self, height): """ :type height: List[int] :rtype: int """ i = 0 j = len(height) - 1 mx = 0 while (i < j): mx = max(mx, ((j - i) * min(height[i], height[j]))) if height[i] < height[j]: i += 1 else: j -= 1 return mx def stringToIntegerList(input): return json.loads(input) def main(): import sys def readlines(): for line in sys.stdin: yield line.strip('\n') lines = readlines() while True: try: line = next(lines) height = stringToIntegerList(line); ret = Solution().maxArea(height) out = str(ret); print(out) except StopIteration: break if __name__ == '__main__': main()
1dfe30c1be5f61a95a450188504d8323711ecd7e
RonCoves/Distributed_Systems
/week_02/domain/visit.py
1,611
3.53125
4
from datatype.enums import DartMultiplier class Dart: def __init__(self, multiplier, segment): self.multiplier = multiplier # see datatype.enums.DartType; optionally create this as a property and validate self.segment = segment # 1 to 20, 0 for miss / double-bull / single-bull def get_score(self): return self.multiplier * self.segment def to_string(self): segment = None if self.segment == 25: segment = "BULL" if self.segment == 0: return "MISS" return DartMultiplier(self.multiplier).name + "-" + str(self.segment) if segment is None else segment class Visit: def __init__(self): self.darts = [] # Limited to 3 Dart elements for most games def __init__(self, darts): self.darts = [] # Limited to 3 Dart elements for most games self.add_darts(darts) def add_dart(self, dart): self.darts.append(Dart(dart[0], dart[1])) def add_darts(self, darts): for dart in darts: self.add_dart(dart) def remove_trailing_darts(self, index): del self.darts[index:] # For many dart games, the total score from 3 darts will be relevant, though there is an argument for placing this # in each specific type of dart game where it is most relevant def get_total(self): total = 0 for dart in self.darts: total += dart.get_score() return total def to_string(self): output = "" for dart in self.darts: output += dart.to_string() + " " return output
1907cff370cca0dfda185d0ee2b5684525c4817b
darraes/coding_questions
/v2/_leet_code_/0040_combination_sum.py
2,741
3.53125
4
import itertools def sort_list(k): for l in k: l.sort() k.sort() return list(k for k, _ in itertools.groupby(k)) class Solution: def combinationSum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ res = self._combine(candidates, target, 0, {}) return sort_list(res) def _combine(self, candidates, target, level, cache): if target == 0: return [[]] if target < 0 or level == len(candidates): return [] if (target, level) in cache: return cache[(target, level)] level_res = [] sub_ans = self._combine(candidates, target, level + 1, cache) for tmp in sub_ans: level_res.append([] + tmp) if candidates[level] <= target: sub_ans = self._combine( candidates, target - candidates[level], level + 1, cache ) for tmp in sub_ans: level_res.append(tmp + [candidates[level]]) cache[(target, level)] = level_res return level_res ############################################################### import unittest class TestFunctions(unittest.TestCase): def test_1(self): s = Solution() self.assertEqual( sort_list([[1, 2, 4], [2, 2, 3], [2, 5], [3, 4]]), s.combinationSum3([5, 3, 1, 2, 2, 4], 7), ) self.assertEqual( sort_list([[1, 1, 2, 2], [1, 1, 4], [1, 2, 3], [2, 2, 2], [2, 4]]), s.combinationSum2([4, 4, 2, 1, 4, 2, 2, 1, 3], 6), ) self.assertEqual( sort_list([[1, 2, 5], [1, 7], [1, 1, 6], [2, 6]]), s.combinationSum2([10, 1, 2, 7, 6, 1, 5], 8), ) self.assertEqual(sort_list([[7]]), s.combinationSum2([2, 3, 6, 7], 7)) self.assertEqual(sort_list([[2, 8]]), s.combinationSum2([2, 5, 8, 4], 10)) self.assertEqual( sort_list([[3, 5], [2, 6]]), s.combinationSum2([2, 3, 5, 6], 8) ) self.assertEqual(sort_list([[2]]), s.combinationSum2([2, 3, 6, 7], 2)) self.assertEqual( sort_list([[3, 3], [2, 4]]), s.combinationSum2([2, 3, 3, 4, 7], 6) ) self.assertEqual( sort_list([[2, 3], [2, 3]]), s.combinationSum2([2, 3, 3, 4, 7], 5) ) self.assertEqual(sort_list([[2]]), s.combinationSum2([2], 2)) self.assertEqual([], s.combinationSum2([2], 3)) self.assertEqual([], s.combinationSum2([2, 4], 3)) self.assertEqual([], s.combinationSum2([], 3)) self.assertEqual([], s.combinationSum2([1], 2)) if __name__ == "__main__": unittest.main()
1a22f23fabe7fcc68a864e8f1be6e22c7b5cf3b9
gabriaraujo/uri
/src/python/1015.py
244
4
4
# -*- coding: utf-8 -*- import math x1, y1 = input().split() x2, y2 = input().split() x1 = float(x1) x2 = float(x2) y1 = float(y1) y2 = float(y2) distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) print("%.4f" %(distance))
8b78b378e37dd2a0231bee8d2bf60076f19bb626
sakorrap/courses-algos
/Assignments/Lab4_quickSort.py
601
3.765625
4
def PARTITION(A,p,r): x=A[r] i=p-1 for j in range(p,r): if (A[j] <= x): i = i+1 temp = A[j] A[j] = A[i] A[i] = temp temp = A[i+1] A[i+1] = A[r] A[r] = temp return i+1 def QUICKSORT(A,p,r): if (p<r) : q = PARTITION(A, p, r) QUICKSORT(A,p,q-1) QUICKSORT(A,q+1,r) return A def main(): # givenArray = map(int,raw_input("Enter the input elements with delimiter as space :").split()); givenArray=[55,10,2,33,12,44] print ("Given Array ", givenArray) start=0 stop=len(givenArray) -1 A = QUICKSORT(givenArray,start,stop) print ("Output :", A) print ("end ") main()
a93ee8593491a8afb2f5a312a2658a4065e334b1
OctopusHugz/holbertonschool-web_back_end
/0x00-python_variable_annotations/102-type_checking.py
409
3.921875
4
#!/usr/bin/env python3 """This module focuses on using mypy""" from typing import Iterator, List, Tuple def zoom_array(lst: Tuple, factor: int = 2) -> List: """This function returns zoomed tuple""" zoomed_in: Iterator = ( item for item in lst for i in range(factor) ) return list(zoomed_in) array = (12, 72, 91) zoom_2x = zoom_array(array) zoom_3x = zoom_array(array, 3)
cae3ca78923b99003507998de297aae844773b91
zhanglintc/leetcode
/Python/Sudoku Solver.py
2,958
3.984375
4
# Sudoku Solver # for leetcode problems # 2015.03.20 by zhanglin # Problem Link: # https://leetcode.com/problems/sudoku-solver/ # Problem: # Write a program to solve a Sudoku puzzle by filling the empty cells. # Empty cells are indicated by the character '.'. # You may assume that there will be only one unique solution. # Pictrue refer to: https://leetcode.com/problems/sudoku-solver/ # |5|3| | |7| | | | | # |6| | |1|9|5| | | | # | |9|8| | | | |6| | # |8| | | |6| | | |3| # |4| | |8| |3| | |1| # |7| | | |2| | | |6| # | |6| | | | |2|8| | # | | | |4|1|9| | |5| # | | | | |8| | |7|9| # A sudoku puzzle... # |5|3|4|6|7|8|9|1|2| # |6|7|2|1|9|5|3|4|8| # |1|9|8|3|4|2|5|6|7| # |8|5|9|7|6|1|4|2|3| # |4|2|6|8|5|3|7|9|1| # |7|1|3|9|2|4|8|5|6| # |9|6|1|5|3|7|2|8|4| # |2|8|7|4|1|9|6|3|5| # |3|4|5|2|8|6|1|7|9| class Solution: # @param board, a 9x9 2D array # Solve the Sudoku by modifying the input board in-place. # Do not return any value. def solveSudoku(self, board): # solveSudoku cannot return anything, so we call another function self.doSolveSudoku(board) def doSolveSudoku(self, board): for row in range(9): for column in range(9): if board[row][column] == '.': for i in range(1, 9 + 1): # from 1 to 9 board[row][column] = str(i) # if this position is OK && resest of board is OK, return True if self.isValid(board, row, column) and self.doSolveSudoku(board): return True # else restore this position else: board[row][column] = '.' # no number fit this position, return False return False # every position is OK, return True return True def isValid(self, board, this_row, this_column): # store this_num and replace it with '.' this_num = board[this_row][this_column] board[this_row][this_column] = '.' # check row for row in range(9): if board[row][this_column] == this_num: board[this_row][this_column] = this_num return False # check column for column in range(9): if board[this_row][column] == this_num: board[this_row][this_column] = this_num return False # check sub-box base_row = this_row / 3 * 3 base_column = this_column / 3 * 3 for sub_row in range(3): for sub_column in range(3): real_row = base_row + sub_row real_column = base_column + sub_column if board[real_row][real_column] == this_num: return False # all well, restore this_num and return True board[this_row][this_column] = this_num return True
0572e94ace21c3508f5383571fa20526ad0fd90c
RDinary/python_06_20
/guess_game.py
375
4.09375
4
from random import randint low = int(input("enter low number")) high = int(input("enter high number")) random_num = randint(low, high) while True: guess = int(input("enter your guess")) if guess > random_num: print("enter lower number") elif guess < random_num: print("enter higher number") else: print("this is it!") break
14d0fe2a9f095e0e6bfe5a81d2f2f4cc4166744b
crazywiden/Leetcode_daily_submit
/Widen/LC765_Couples_Holding_Hands.py
1,827
3.703125
4
""" 765. Couples Holding Hands N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats. The people and seats are represented by an integer from 0 to 2N-1, the couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2N-2, 2N-1). The couples' initial seating is given by row[i] being the value of the person who is initially sitting in the i-th seat. Example 1: Input: row = [0, 2, 1, 3] Output: 1 Explanation: We only need to swap the second (row[1]) and third (row[2]) person. Example 2: Input: row = [3, 2, 0, 1] Output: 0 Explanation: All couples are already seated side by side. """ # tutorial: https://leetcode.com/articles/couples-holding-hands/ # Runtime: 36 ms, faster than 20.78% of Python3 online submissions for Couples Holding Hands. # Memory Usage: 13 MB, less than 100.00% of Python3 online submissions for Couples Holding Hands. class Solution: def minSwapsCouples(self, row: List[int]) -> int: # this is actually a math problem # key part: to prove why greedy is optimal # greedy method: # find the couple, then put the couple on his / her right # little trick: use x ^ 1 to find couple res = 0 IDX = {ele:idx for idx, ele in enumerate(row)} for i in range(0, len(row), 2): couple = row[i] ^ 1 couple_idx = IDX[couple] if couple_idx - i == 1: continue row[i+1], row[couple_idx] = row[couple_idx], row[i+1] IDX = {ele:idx for idx, ele in enumerate(row)} res += 1 return res
6b466e7914697eb0b8e3e07431eb52146bdbb992
HugoValim/DAF
/daf/core/math_utils.py
1,255
3.59375
4
import numpy as np import math def unit_vector(vector): """Returns the unit vector of the vector.""" return vector / np.linalg.norm(vector) def vector_angle(v1, v2, deg=False): """Returns the angle in radians between vectors 'v1' and 'v2':: >>> angle_between((1, 0, 0), (0, 1, 0)) 1.5707963267948966 >>> angle_between((1, 0, 0), (1, 0, 0)) 0.0 >>> angle_between((1, 0, 0), (-1, 0, 0)) 3.141592653589793 """ v1_u = unit_vector(v1) v2_u = unit_vector(v2) if deg: return np.rad2deg(np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))) return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)) def vec_norm(v): """ Calculate the norm of a vector. Parameters ---------- v : list or array-like input vector(s), either one vector or an array of vectors with shape (n, 3) Returns ------- float or ndarray vector norm, either a single float or shape (n, ) """ if isinstance(v, np.ndarray): if len(v.shape) >= 2: return np.linalg.norm(v, axis=-1) if len(v) != 3: raise ValueError("Vector must be of length 3, but has length %d!" % len(v)) return math.sqrt(v[0] ** 2 + v[1] ** 2 + v[2] ** 2)
bab4132702a9523be7535168068bb2d2d7c765ed
milanix13/COVID-19
/src/analysis.py
8,652
3.734375
4
'''Code for analysis of data''' from data_munging import * from plotting import * import scipy.stats as stats import numpy as np def death_case_frequency(total_death_case, total_cases): '''Inputs: total_death - total # covid deaths proportional to population total_cases - total # covid cases proportional to population Calculate frequency of deaths after covid infection Output: float''' return total_death_case / total_cases def shared_frequency(c1_death, c2_death, c1_cases, c2_cases): '''Inputs: c1_death - country 1's total death c2_death - country 2's total death c1_cases - country 1's total cases c2_cases - country 2's total cases Calculate shared frequency Output: float''' return (c1_death + c2_death) / (c1_cases + c2_cases) def shared_std(shared_freq, c1_cases, c2_cases): '''Inputs: shared_freq - calculated shared frequency c1_cases - country 1's total cases c2_cases - country 2's total cases Calculate shared standard deviation Output: float''' return np.sqrt(((c1_cases+c2_cases)*shared_freq*(1-shared_freq))/(c1_cases*c2_cases)) def diff_frequencies(c1_freq, c2_freq): '''Inputs: c1_freq - first country's frequency of deaths per cases c2_freq - second country's frequency of deaths per cases, comparison one Calculates the difference in frequencies betwen two countries Output: float''' return c1_freq - c2_freq def p_value(diff_dist, diff_freq): '''Inputs: diff_dist - normal distribution of difference in frequencies diff_freq - difference in frequencies Calculates the p_value between two sample frequencies Output: float''' return 1 - diff_dist.cdf(diff_freq) def binom_approx_norm_dist(n, p): '''Inputs: n - country's total number cases (minus last two weeks) p - country's frequency of deaths per cases Creates a normal distribution approximation from a binomial distribution Output: normal distribution''' mean = n * p var = n*p*(1-p) return stats.norm(mean, np.sqrt(var)) if __name__ == '__main__': '''daily case stats for table display in readme''' #create data frame for hypothesis testing that doesn't have last two weeks of cases covid_merge_two_week = covid_merge.iloc[0:265, :] #total covid cases overall + proportionally us_total = covid_merge_two_week['US_Daily_Totals'].sum() us_total_prop = covid_merge_two_week['US_Daily_prop'].sum() can_total = covid_merge_two_week['Canada_Daily_Cases'].sum() can_total_prop = covid_merge_two_week['Canada_Daily_prop'].sum() aus_total = covid_merge_two_week['Aus_Daily_Cases'].sum() aus_total_prop = covid_merge_two_week['Aus_Daily_prop'].sum() nz_total = covid_merge_two_week['NZ_Daily_Cases'].sum() nz_total_prop = covid_merge_two_week['NZ_Daily_prop'].sum() #print(us_total, us_total_prop, can_total, can_total_prop,aus_total, aus_total_prop,nz_total, nz_total_prop) #total covid deaths overall + proportionally us_total_death = deaths_merge['US_Daily_Deaths'].sum() us_total_prop_death = deaths_merge['US_Daily_prop'].sum() can_total_death = deaths_merge['Canada_Daily_Deaths'].sum() can_total_prop_death = deaths_merge['Canada_Daily_prop'].sum() aus_total_death = deaths_merge['Aus_Daily_Deaths'].sum() aus_total_prop_death = deaths_merge['Aus_Daily_prop'].sum() nz_total_death = deaths_merge['NZ_Daily_Deaths'].sum() nz_total_prop_death = deaths_merge['NZ_Daily_prop'].sum() # print(us_total_death, us_total_prop_death, can_total_death,can_total_prop_death,aus_total_death, # aus_total_prop_death,nz_total_death, nz_total_prop_death) '''hypothesis testing: H0 - other countries probability of death match US # Ha - US mean is > other countries' probability of death after diagnosis''' #calculate frequency or probability of death after covid diagnosis for each country us_p = death_case_frequency(us_total_prop_death, us_total_prop) can_p = death_case_frequency(can_total_prop_death, can_total_prop) aus_p = death_case_frequency(aus_total_prop_death, aus_total_prop) nz_p = death_case_frequency(nz_total_prop_death, nz_total_prop) # print(us_p, can_p, aus_p, nz_p) #calculate shared frequency and plot normal distribution with country US - x #since the skeptic would say US <= country x shared_p_can_us = shared_frequency(us_total_prop_death, can_total_prop_death, us_total_prop, can_total_prop) std_can_us = shared_std(shared_p_can_us, us_total_prop, can_total_prop) diff_norm_can_us = stats.norm(0, std_can_us) #normal distribution of the differences in frequencies shared_p_aus_us = shared_frequency(us_total_prop_death, aus_total_prop_death, us_total_prop, aus_total_prop) std_aus_us = shared_std(shared_p_aus_us, us_total_prop, aus_total_prop) diff_norm_aus_us = stats.norm(0, std_aus_us) shared_p_nz_us = shared_frequency(us_total_prop_death,nz_total_prop_death, us_total_prop, nz_total_prop) std_nz_us = shared_std(shared_p_nz_us, us_total_prop, nz_total_prop) diff_norm_nz_us = stats.norm(0, std_nz_us) #calculate p_value for difference in frequencies for hypothesis test diff_freq_can_us = diff_frequencies(us_p, can_p) p_value_can_us = p_value(diff_norm_can_us, diff_freq_can_us) diff_freq_aus_us = diff_frequencies(us_p, aus_p) p_value_aus_us = p_value(diff_norm_aus_us, diff_freq_aus_us) diff_freq_nz_us = diff_frequencies(us_p, nz_p) p_value_nz_us = p_value(diff_norm_nz_us, diff_freq_nz_us) # print(diff_freq_can_us, p_value_can_us) # print(diff_freq_aus_us, p_value_aus_us) # print(diff_freq_nz_us, p_value_nz_us) #approximated normal distributions of frequency of deaths per cases us_norm_dist = binom_approx_norm_dist(us_total_prop, us_p) can_norm_dist = binom_approx_norm_dist(can_total_prop, can_p) aus_norm_dist = binom_approx_norm_dist(aus_total_prop, aus_p) nz_norm_dist = binom_approx_norm_dist(nz_total_prop, nz_p) #comparing daily positives to daily tests us_total_prop = covid_merge['US_Daily_prop'].sum() can_total_prop = covid_merge['Canada_Daily_prop'].sum() aus_total_prop = covid_merge['Aus_Daily_prop'].sum() nz_total_prop = covid_merge['NZ_Daily_prop'].sum() us_total_tests_prop = 138020227 / us_pop can_total_tests_prop = (canada_covid_total['numtested'].sum()) / can_pop aus_total_tests_prop = (aus_covid['tests'].sum())/aus_pop nz_total_tests_prop = 1072492 / nz_pop us_p_case = death_case_frequency(us_total_prop, us_total_tests_prop) can_p_case = death_case_frequency(can_total_prop, can_total_tests_prop) aus_p_case = death_case_frequency(aus_total_prop, aus_total_tests_prop) nz_p_case = death_case_frequency(nz_total_prop, nz_total_tests_prop) # print(us_p_case, can_p_case, aus_p_case, nz_p_case) # print(us_total_tests_prop, can_total_tests_prop, aus_total_tests_prop, nz_total_tests_prop) #calculate shared frequency and plot normal distribution with country US - x #since the skeptic would say US <= country x shared_p1_can_us = shared_frequency(us_total_prop, can_total_prop, us_total_tests_prop, can_total_tests_prop) std1_can_us = shared_std(shared_p1_can_us, us_total_tests_prop, can_total_tests_prop) diff_norm1_can_us = stats.norm(0, std1_can_us) #normal distribution of the differences in frequencies shared_p1_aus_us = shared_frequency(us_total_prop, aus_total_prop, us_total_tests_prop, aus_total_tests_prop) std1_aus_us = shared_std(shared_p1_aus_us, us_total_tests_prop, aus_total_tests_prop) diff_norm1_aus_us = stats.norm(0, std1_aus_us) shared_p1_nz_us = shared_frequency(us_total_prop, nz_total_prop, us_total_tests_prop,nz_total_tests_prop) std1_nz_us = shared_std(shared_p1_nz_us, us_total_tests_prop, nz_total_tests_prop) diff_norm1_nz_us = stats.norm(0, std1_nz_us) #calculate p_value for difference in frequencies for hypothesis test diff_freq1_can_us = diff_frequencies(us_p_case, can_p_case) p_value1_can_us = p_value(diff_norm1_can_us, diff_freq1_can_us) diff_freq1_aus_us = diff_frequencies(us_p_case, aus_p_case) p_value1_aus_us = p_value(diff_norm1_aus_us, diff_freq1_aus_us) diff_freq1_nz_us = diff_frequencies(us_p_case, nz_p_case) p_value1_nz_us = p_value(diff_norm1_nz_us, diff_freq1_nz_us) # print(diff_freq1_can_us, p_value1_can_us) # print(diff_freq1_aus_us, p_value1_aus_us) # print(diff_freq1_nz_us, p_value1_nz_us)
06283fa1eb839b639a3d7f40568095a4b84e96d1
AlexFine/CS109
/pset5/p12.py
2,563
3.671875
4
import csv import random import statistics N = 100000 # Reads a files into a 2d array. There are # other ways of doing this (do check out) # numpy. But this shows def loadCsvData(fileName): arr = [] # open a file with open(fileName) as f: reader = csv.reader(f) # loop over each row in the file for row in reader: # cast each value to a float for value in row: arr.append(int(value)) # store the row into our matrix return arr # Master function def master(): data_arr = loadCsvData('peerGrades.csv') # Part a print(sample_mean(data_arr)) # Part b print(var_w_5(data_arr)) # Part c print(var_w_5_median(data_arr)) # Part d print(expected_of_both(data_arr)) # Expected value of BOTH YO def expected_of_both(arr): loop_len = 5 blip = [] var_arr = [] # Simulate the bitch for i in range(N): temp = [] for i in range(loop_len): temp.append(random.choice(arr)) # calc avg. median = statistics.median(temp) blip.append(median) blop = [] for i in range(N): temp = [] for i in range(loop_len): temp.append(random.choice(arr)) # calc avg. avg = sum(temp)/len(temp) blop.append(avg) return sum(blip)/len(blip), sum(blop)/len(blop) # Bootstrap to create an array of 5 averages def var_w_5_median(arr): loop_len = 5 e_2_arr = [] var_arr = [] # Simulate for i in range(N): temp = [] for i in range(loop_len): temp.append(random.choice(arr)) # calc avg. median = statistics.median(temp) e_2_arr.append(median*median) # Print variance e2_sum = sum(e_2_arr)/len(e_2_arr) samp, _ = expected_of_both(arr) # Variance var = e2_sum - samp*samp # return return var # Bootstrap to create an array of 5 averages def var_w_5(arr): loop_len = 5 e_2_arr = [] var_arr = [] # Simulate for i in range(N): temp = [] for i in range(loop_len): temp.append(random.choice(arr)) # calc avg. avg = sum(temp)/len(temp) e_2_arr.append(avg*avg) # Print variance e2_sum = sum(e_2_arr)/len(e_2_arr) samp = sample_mean(arr) # Variance var = e2_sum - samp*samp # return return var # Calculate the sample mean of the arra def sample_mean(arr): arr_sum = 0 # Calculate sum for i in range(len(arr)): arr_sum += arr[i] # Set return ret = arr_sum/len(arr) return ret master()
3e8a2e039c0c5f9f6f2e00d8e9438f7b16c3c4f6
wolffereast/chinese_solitaire
/gameboard.py
10,861
3.65625
4
''' Created on Feb 10, 2018 @author: stephen ''' import Tkinter from random import randrange from time import sleep class Gameboard(Tkinter.Frame): # Board layouts must be an array of equal length arrays, one per column, # and they must only contain 0, -1, and 1. def verifyGameboard(self, boardLayout): length = -1 self.boardWidth = len(boardLayout) if not self.boardWidth: print 'invalid board layout: empty layout' return False for row in boardLayout: # Catch the type error, this will verify that the row is iterable. try: self.boardHeight = len(row) if not self.boardHeight: print 'invalid board layout: empty column' return False except TypeError: # catch when for loop fails print 'invalid board layout: column is not a list' return False if -1 == length: length = len(row) continue if length != len(row): print 'invalid board layout: column lengths must be consistent' return False for i in row: try: if i < -1 or i > 1: print 'invalid board layout: column may only contain -1, 0, and 1' return False except TypeError: print 'invalid board layout: column may only contain -1, 0, and 1' return False return True def createWidgets(self): self.quitButton = Tkinter.Button(self, fg = 'red', text = 'QUIT', command = self.quit) self.quitButton.pack({"side": "left"}) self.showMovesButton = Tkinter.Button(self, fg = 'black', text = 'Show Moves', command = lambda: self.showAvailableMoves(self.boardLayout)) self.showMovesButton.pack({"side": "left"}) self.removeMovesButton = Tkinter.Button(self, fg = 'black', text = 'Remove Moves', command = lambda: self.removeAvailableMoveLines()) self.removeMovesButton.pack({"side": "left"}) self.randomMove = Tkinter.Button(self, fg = 'black', text = 'Random Move', command = lambda: self.makeMove()) self.randomMove.pack({"side": "left"}) self.solve = Tkinter.Button(self, fg = 'black', text = 'Solve', command = lambda: self.solveBoard()) self.solve.pack({"side": "left"}) # Need to create a marble for each item in the row self.canvas = Tkinter.Canvas(width = len(self.boardLayout[0]) * 20, height = len(self.boardLayout) * 20, bg = 'white') self.canvas.pack() self.canvasItems = []; for i, row in enumerate(self.boardLayout): self.canvasItems.append([]) for j, item in enumerate(row): # skip empty squares. if -1 == item: self.canvasItems[i].append('') continue oval = self.createOval(i, j, 'black' if 1 == item else 'white') self.canvasItems[i].append(oval) def createOval(self, x, y, color): x1 = x * 20 + 5 y1 = y * 20 + 5 return self.canvas.create_oval(x1, y1, x1 + 15, y1 + 15, fill = color) def updateStatus(self, x, y, color): marble = self.canvasItems[x][y] self.canvas.itemconfig(marble, fill = color) # Given the current board layout, return a list of available moves as a # triplet with the first index as the item to move, the second as the item # to be removed, and the third as the target. def getAvailableMoves(self, boardLayout): availableMoves = [] # Go through and find empty spots. Any empty spot with two marbles # in a row adjacent is a potential move. for i, row in enumerate(boardLayout): for j, item in enumerate(row): if item != 0: continue # We need to check all four directions around an empty spot # to see if it has potential moves. # Jump Down. if j > 1 and 1 == boardLayout[i][j - 2] and 1 == boardLayout[i][j - 1]: availableMove = [] availableMove.append([i, j - 2]) availableMove.append([i, j - 1]) availableMove.append([i, j]) availableMove.append(0) availableMoves.append(availableMove); # Jump Left. if i < self.boardWidth - 2 and 1 == boardLayout[i + 1][j] and 1 == boardLayout[i + 2][j]: availableMove = [] availableMove.append([i + 2, j]) availableMove.append([i + 1, j]) availableMove.append([i, j]) availableMove.append(1) availableMoves.append(availableMove); # Jump Up. if j < self.boardHeight - 2 and 1 == boardLayout[i][j + 1] and 1 == boardLayout[i][j + 2]: availableMove = [] availableMove.append([i, j + 2]) availableMove.append([i, j + 1]) availableMove.append([i, j]) availableMove.append(2) availableMoves.append(availableMove); # Jump Right. if i > 1 and 1 == boardLayout[i - 1][j] and 1 == boardLayout[i - 2][j]: availableMove = [] availableMove.append([i - 2, j]) availableMove.append([i - 1, j]) availableMove.append([i, j]) availableMove.append(3) availableMoves.append(availableMove); return availableMoves def showAvailableMoves(self, boardLayout): # Wipe the board. self.removeAvailableMoveLines() availableMoves = self.getAvailableMoves(boardLayout) if not len(availableMoves): return # now print them all! We need to overlay the arrow on the middle item # in the quad. for move in availableMoves: # The arrow points a different direction based on the fourth item. # Up. x1 = move[1][0] * 20 + 5 y1 = move[1][1] * 20 + 5 if 0 == move[3]: line = self.canvas.create_line(x1 + 8, y1, x1 + 8, y1 + 15) self.canvas.itemconfig(line, arrow = 'last', fill = 'green') self.availableMoveLines.append(line) elif 1 == move[3]: line = self.canvas.create_line(x1 + 15, y1 + 8, x1, y1 + 8) self.canvas.itemconfig(line, arrow = 'last', fill = 'green') self.availableMoveLines.append(line) elif 2 == move[3]: line = self.canvas.create_line(x1 + 8, y1 + 15, x1 + 8, y1) self.canvas.itemconfig(line, arrow = 'last', fill = 'green') self.availableMoveLines.append(line) elif 3 == move[3]: line = self.canvas.create_line(x1, y1 + 8, x1 + 15, y1 + 8) self.canvas.itemconfig(line, arrow = 'last', fill = 'green') self.availableMoveLines.append(line) def removeAvailableMoveLines(self): for item in self.availableMoveLines: self.canvas.delete(item) def getStateAfterMove(self, boardLayout, move): boardLayout[move[0][0]][move[0][1]] = 0; boardLayout[move[1][0]][move[1][1]] = 0; boardLayout[move[2][0]][move[2][1]] = 1; return boardLayout def makeMove(self): # Make sure we get rid of the available lines first. self.removeAvailableMoveLines() availableMoves = self.getAvailableMoves(self.boardLayout); if not len(availableMoves): print 'Game Over!' return # make this random for now. move = randrange(0, len(availableMoves)) # Need to remove the item being moved over and the item moving, then # add the item moved to. self.canvas.itemconfig(self.canvasItems[availableMoves[move][0][0]][availableMoves[move][0][1]], fill = 'green') # The update call is required, or it will queue all the updates and # wait until after both sleeps. self.canvas.update() sleep(.25) self.canvas.itemconfig(self.canvasItems[availableMoves[move][0][0]][availableMoves[move][0][1]], fill = 'white') self.canvas.itemconfig(self.canvasItems[availableMoves[move][1][0]][availableMoves[move][1][1]], fill = 'red') self.canvas.itemconfig(self.canvasItems[availableMoves[move][2][0]][availableMoves[move][2][1]], fill = 'green') self.canvas.update() sleep(.25) self.canvas.itemconfig(self.canvasItems[availableMoves[move][1][0]][availableMoves[move][1][1]], fill = 'white') self.canvas.itemconfig(self.canvasItems[availableMoves[move][2][0]][availableMoves[move][2][1]], fill = 'black') # Then update the self.boardLayout to reflect the same changes. self.boardLayout = self.getStateAfterMove(self.boardLayout, availableMoves[move]) def solveBoard(self): availableMoves = self.getAvailableMoves(self.boardLayout); if not len(availableMoves): print 'Game Over!' print 'Score: %i' % self.getScore(self.boardLayout) return self.makeMove() self.solveBoard() def resetBoard(self): self.removeAvailableMoveLines() self.boardLayout = self.originalBoardLayout # Remove and recreate the marbles. # Determines the final score of a board layout based on the number of # marbles remaining. def getScore(self, boardLayout): score = 0 for column in boardLayout: for j in column: if j == 1: score += 1 return score def __init__(self, boardLayout=[], master=None): self.boardLayout = boardLayout self.originalBoardLayout = boardLayout # verify the boardLayout first. if not self.verifyGameboard(self.boardLayout): return Tkinter.Frame.__init__(self, master) self.pack() self.createWidgets() self.availableMoveLines = []
aec70871bb17bcf569b304c2ec4744e6f79bf774
alverad-katsuro/Python
/python-examples-master/pilha-poo.py
2,673
4.0625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from os import system class Cliente(object): # Classe cliente, vazia pois pode ser atribuido pass # propriedades mais tarde class Pilha(object): # Classe Pilha def __init__(self): # metodo construtor self.pilha = [] # declara lista vazia sendo propriedade da classe def incluir(self): "Inclui um cliente na pilha" cliente = Cliente() # instancia objeto cliente cliente.nome = raw_input('Nome: ') # inclui propriedade nome no objeto com valor digitado cliente.telefone = raw_input('Telefone: ') # inclui propriedade nome no objeto com valor digitado cliente.cpf = raw_input('CPF: ') # inclui propriedade cpf no objeto com valor digitado self.pilha.insert(0, cliente) # insere sempre na primeira posicao def consultar(self): "Lista todos os items" for item in self.pilha: # faz uma iteracao em todos os items da lista print '\nNome: ' + item.nome print 'Telefone: ' + item.telefone print 'CPF: ' + item.cpf raw_input() # aguarda tecla enter def excluir(self): "Exclui o primeiro item da lista" if len(self.pilha) > 0: # pega tamanho da pilha e compara self.pilha.pop(0) # exclui item da posicao 0 print 'Excluido' else: print 'Pilha vazia' raw_input() # aguarda tecla enter def main(): def limpa(): "Limpa a tela" system('cls') p = Pilha() # instancia objeto Pilha atribuindo para p while True: # loop infinito, sempre verdadeiro limpa() print("\n1. Incluir: ") print("\n2. Consultar: ") print("\n3. Excluir: ") print("\n4. Sair: \n") try: # tenta fazer op = int(raw_input()) # pega a entrada do teclado e converte para int if op == 1: # caso der erro na conversao cai no except abaixo limpa() p.incluir() # chama metodo incluir do objeto p (pilha) elif op == 2: limpa() p.consultar() # chama metodo consultar do objeto p (pilha) elif op == 3: limpa() p.excluir() # chama metodo excluir do objeto p (pilha) elif op == 4: break # quebra o loop e fecha o programa else: print 'Opcao invalida' except: # caso tenha execao, (por exemplo digitar uma letra) sera exec print 'Opcao invalida, digite um numero' main() # chama o main, primeira funcao a ser executada
9e9c672f09e8e2f91f5c64076e54f461c02262c9
jaishivnani/Python-Practice-Problems
/3. Chapter 3 Strings/Practice problems/45_string.py
439
4.1875
4
'''Exercise Question 4: Arrange string characters such that lowercase letters should come first Sample Input str1 = PyNaTive Sample Output yaivePNT ''' str1 = "PyNaTive" def lowerfirst(str1): lower = [] upper = [] for char in str1: if char.islower(): lower.append(char) else: upper.append(char) sorted_string=''.join(lower+upper) print(sorted_string) lowerfirst(str1)
34c5815d7d70b0c78b7f600e4a83e7802f5b4433
mchorney/Python
/Basics/string_list.py
546
3.875
4
# Replace "day" with "month" in string words = "It's thanksgiving day. It's my birthday,too!" words = words.replace("day", "month") print words # Min and Max from List x = [2, 54, -2, 7, 12, 98] min = min(x) max = max(x) print "Min: ", min print "Max: ", max # First and Last x = [19, 2, 54, -2, 7, 12, 98, 32, 10, -3, 6] first = x[0] last = x[-1] print "First: ", first print "Last: ", last # New List x = [19, 2, 54, -2, 7, 12, 98, 32, 10, -3, 6] x.sort() new = len(x) / 2 new = x[0:new] del x[0:len(x) / 2] x.insert(0, new) print x
b9529cf77edbbb0edacce51390046025007b56ab
haukurarna/2018-T-111-PROG
/solutions_to_programming_exercises/assignment23_while.py
221
4.0625
4
low = int(input("Input the lower bound: ")) high = int(input("Input the higher bound: ")) sum_of_odd = 0 while low <= high : if low % 2 == 1 : sum_of_odd += low low += 1 print("The sum is ", sum_of_odd)
ec4b2ab3728b5a4a28cbf7951387c4abcca4546b
woodongk/python-algorithm-study
/파이썬 알고리즘 인터뷰/[7-08] 42. Trapping Rain Water.py
4,089
3.984375
4
""" Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. Example 1: Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Example 2: Input: height = [4,2,0,3,2,5] Output: 9 Constraints: n == height.length 0 <= n <= 3 * 104 0 <= height[i] <= 105 """ from typing import List # 사이에 0 있으면 rain drop count update def count_rain(height_line): # 값 있으면 True, 없으면 False visited = [True if i != 0 else False for i in height_line] n = len(visited) if True not in visited: return 0 start = 0 end = n - 1 while start < n & end >= 0: start += 1 end -= 1 if (visited[start] == True) & (visited[end] == True): break # start = visited.index(True) # end = len(visited) - visited[::-1].index(True) - 1 print("start{} end{}".format(start, end)) rain = visited[start:end + 1].count(0) return rain def trap(height: List[int]) -> int: if len(height) == 0: return 0 rain_drop = 0 max_height = max(height) for _ in range(max_height): print(height, rain_drop) rain_drop += count_rain(height) # 한칸씩 올라가기 height = [i - 1 if i > 0 else 0 for i in height] return rain_drop def fast_trap(height: List[int]) -> int: if not height: return 0 volume = 0 left, right = 0, len(height) - 1 left_max, right_max = height[left], height[right] while left < right: print() print(left,height[left],right, height[right]) left_max, right_max = max(left_max, height[left]), max(right_max, height[right]) if left_max <= right_max: volume += left_max - height[left] left += 1 else: volume += right_max - height[right] right -= 1 return volume def fast_trap(height: List[int]) -> int: """ #@새찬 """ # height 의 길이가 2 아래라면 바로 0을 반환 if len(height) <= 2: return 0 # left_max 를 만날 때까지 선형 탐색하는 알고리즘 def solution(sub_height): # 최초의 0 이상의 값을 left 에 할당 for i in range(len(sub_height)): if sub_height[i] != 0: left = i break sub_volume = 0 # 현재 값을 기준으로 선형 탐색 for i in range(left + 1, len(sub_height)): print("현재 인덱스 : {}, 값 : {}".format(i, sub_height[i])) # 현재보다 같거나 큰 값을 만나면 volume 갱신 if sub_height[i] >= sub_height[left]: # sub_height 에서 현재 높이를 각각 빼기 sub_volume += sum([sub_height[left] - h for h in sub_height[left:i]]) left = i return sub_volume # 가장 큰 값을 기준으로 배열 분리, reverse idx = height.index(max(height)) volume = 0 volume += solution(height[:idx+1]) volume += solution(height[idx:][::-1]) return volume def stack_trap(height: List[int]) -> int: stack = [] volume = 0 for i in range(len(height)): # 변곡점 만나는 경우 (현재 높이가 이전 높이보다 높을 때) while stack and height[i] > height[stack[-1]]: print("i = {}, height[i] = {}, stack = {}".format(i, height[i], stack)) print() # 스택에서 꺼냄 top = stack.pop() if not len(stack): break # 이전과의 차이 만큼 볼륨 증가 distance = i - stack[-1] -1 waters = min(height[i], height[stack[-1]]) - height[top] volume += distance * waters stack.append(i) return volume if __name__ == '__main__': print(stack_trap([0,1,0,2,1,0,1,3,2,1,2,1]))
0dc15a9f95f73c93b0f0f8920ad77ef9a010e4af
iangregson/euler
/problem-two.py
359
3.890625
4
a, b = 0, 1 def fibonacci(): global a, b while True: a, b = b, a + b yield a def main(): f = fibonacci() last_number = 0 fib_sum = 0 while last_number < 4e6: last_number = next(f) if last_number % 2 == 0: fib_sum += last_number print(fib_sum) if __name__ == "__main__": main()
545132a6c874c80258fc9249db817195417918a0
tze18/AI
/python-training/number-string.py
229
3.78125
4
# !/usr/bin/python # -*-coding:utf-8 -*- #數字運算 #x=2+3 #print(x) #x+=1 #x=x+1 #將變數中的數字+1 #字串運算 #字串會對內部的字元編號(索引),從0開始算起 s="hello" print(s[:4]) # # #
2096631b580b5904bfcbf4f924513550ce969039
syurskyi/Python_Topics
/030_control_flow/example/Python-from-Zero-to-Hero/03-Коллеции, циклы, логика/15-ДЗ-Угадай число_solution.py
615
4.0625
4
import random tries = 0 number = random.randint(1, 50) print('Hmmm... Try to guess what number between 1 and 50 I was thinking about :)') while tries < 6: guess = int(input('Take a guess: ')) tries+=1 if guess < number: print('Your guess is too low') if guess > number: print('Yout guess is too high') if guess == number: print(f'Congratulations! You guessed my number in {tries} guesses.') break if guess != number and tries == 6: print(f"Sorry, but you didn't make it. My number was: {number}") break
1980d95a51d20e6c4bd9c6d9a6cb4986ec7dea4d
ayeshaaamir123/Online-Shopping-System
/A1_CS19020_26_4.py
6,518
3.90625
4
class userInterfaceProduct: def __init__(self): print('\t-------PRODUCT IN ONLINE SHOP--------') print('\t=============================\n') p=Order() #when object of Order class is instantiated all the available products with price and quantity are printed print('\n\t--------PLACE YOUR ORDER--------') print('YOUR CART IS READY!') while True: choice=input('Press \'e\' to exit or ANY KEY to continue: ') if choice=='e' or choice=='E': break else: try: product=input('Enter PRODUCT NAME to be added in the Cart: ') if len(product)==0: raise ValueError p.AddToCart(product) except ValueError: print('Enter valid name!') while True: print('************************************') print('MENU\n1: Add more items to Cart\n2: Remove items from the cart\n3: Show Items in cart\n4: CheckOut\nPress ANY key to Exit') print('************************************') self.choice=input('Enter an option: ') if self.choice=='1': while True: try: product=input('Enter PRODUCT NAME to be added in the Cart:') if len(product)==0: raise ValueError p.AddMoreToCart(product) break except ValueError: print('Enter valid name!') elif self.choice=='2': p. removeFromCart() elif self.choice=='3': print('\t----ITEMS IN CART-----') p.printPurchasedProduct() p.TotalPrice() elif self.choice=='4': p.savePurchasedProduct() #saving the Purchased products in a file print('Order placed successfully') print('\t----ORDERED ITEMS------') p.printPurchasedProduct() p.TotalPrice() break else: break from A1_CS19020_26_5 import ProductManagement,Product class Order: def __init__(self): self.product_cart=[] #Using ManageProduct class in Order class as most of the coding was same self.PM = ProductManagement() self.PM.printProduct(self.PM.product_rec) def AddToCart(self,product): p = Product() while True: add_product = self.PM.search(product, self.PM.product_rec) pre_product = self.PM.search(product, self.product_cart) if add_product == None: #If the product user want to buy is not present in stock print('Invalid product entered!!') product=input('Enter product name again!') elif add_product != None: p.setProductName(self.PM.product_rec[add_product][0]) while True: try: #using try except block to avoid program termination and to put some checks quan = int(input('Enter quantity of product: ')) if quan> self.PM.product_rec[add_product][2]: print('SORRY!!,STOCK NOT AVAILABLE IN REQUIRED QUANTITY---') print('Quantity availabe: ', self.PM.product_rec[add_product][2]) return if quan<=0: print('Try Quantity greater than zero!') raise ValueError if pre_product != None: #If the item is already present in the cart then only its quantity is increased self.product_cart[pre_product][2] += quan return else: self.PM.product_rec[add_product][2] -= quan p.setPrice(self.PM.product_rec[add_product][1]) p.setQuantity(quan) self.product_cart.append(p) return except ValueError: print('Enter Valid Value!') def AddMoreToCart(self,add_product): pre_product = self.PM.search(add_product, self.product_cart) #If user has added a product in the cart that is already available in the cart if pre_product != None: print('PRODUCT AVAILABLE ALREADY! ') while True: try: quan = int(input('Enter quantity of product to be added: ')) if quan<=0: print('Try Quantity greater than zero!') raise ValueError self.product_cart[pre_product][2] += quan self.PM.product_rec[pre_product][2] -= quan print('QUANTITY ADDED SUCCESSFULLY!!') return except ValueError: print('Enter valid value!') else: self.AddToCart(add_product) #If new product is added def removeFromCart(self): self.PM.removeProduct(self.product_cart) if self.PM.choice=='2': rem_product = self.PM.search(self.PM.remove, self.PM.product_rec) self.PM.product_rec[rem_product][2] +=self.PM.amount def TotalPrice(self): totalPrice=0 #Calculating total price for element in self.product_cart: totalPrice+=element[1]*element[2] self.PM.saveProduct('A1_CS19020_26_9.txt',self.PM.product_rec) print('\tTotal price of your products is:', totalPrice,'Rs/=') def printPurchasedProduct(self): self.PM.printProduct(self.product_cart) def savePurchasedProduct(self): self.PM.saveProduct('A1_CS19020_26_10.txt',self.product_cart) ##u1=userInterfaceProduct()
a5255d45a2e5b2bc9571ca3ffffbee86bd84eea8
alanvenneman/Programming
/Alan_Exam2/shooter_rec.py
630
4
4
import random # ROOM = random.randint(1, 500) # Comment in the next line and choose 65 to test. ROOM = 65 room_sizes = [] again = 'Y' while again.upper() == 'Y': # print("Not found yet.") sqft = int(input("Enter square footage of room: \n")) room_sizes.append(sqft) again = input("Enter another room size? Y/N") # maximum = max(room_sizes) def found(list): next_room = list.pop() if next_room == ROOM: print(f"You found him in the {next_room} square foot room.") else: if len(list) > 0: return found(list) else: print("No shooter.") found(room_sizes)
b53037ebc8fef4530e81d2804b38c1eec3a5377c
Sabakalsoom/Learning-Python
/numbers.py
180
3.84375
4
int_num = 10 float_num = 20.0 print(int_num) print(float_num) a = 10 b = 20 add = a+b print(add) sub = b-a print(sub) multi = a*b print(multi) div = b/a print(div)
5d81a96e4683a555172a6cf53ded0d295edf6889
vparjunmohan/Python
/Basics-Part-II/program41.py
486
4.1875
4
'''Write a Python program that accepts six numbers as input and sorts them in descending order. Input: Input consists of six numbers n1, n2, n3, n4, n5, n6 (-100000 = n1, n2, n3, n4, n5, n6 = 100000). The six numbers are separated by a space. Input six integers: 15 30 25 14 35 40 After sorting the said integers: 40 35 30 25 15 14''' print('Input six integers:') nums = list(map(int, input().split())) nums.sort() nums.reverse() print('After sorting the said integers:') print(nums)
d1d1513faed9c23caf460a7cb1f69009795bdec1
jagadeeshwithu/Data-Structures-and-Algos-Python
/MergeSort.py
902
4.0625
4
""" Merge Sort implementation: Recursive way Time complexity: O(nlogn) Space complexity: O(n) """ def mergeSort(inputlist): arraylen = len(inputlist) if arraylen > 1: mid = arraylen//2 left = inputlist[:mid] right = inputlist[mid:] mergeSort(left) mergeSort(right) i, j, k = 0, 0, 0 while i < len(left) and j < len(right): if left[i] < right[j]: inputlist[k] = left[i] i += 1 else: inputlist[k] = right[j] j += 1 k += 1 while i < len(left): inputlist[k] = left[i] i += 1 k += 1 while j < len(right): inputlist[k] = right[j] j += 1 k += 1 return inputlist if __name__ == "__main__": print(mergeSort([1, 3, 8, 5, 6, 4]))
d7d8a6280b2064f0e43819a33698b8a4343041e4
armcburney/practice
/python/ctci/arrays_and_strings/palindrome_permutation.py
788
4.125
4
#!/usr/bin/python3 """ palindrome_permutation.py @author: Andrew Robert McBurney @info: Cracking the Coding Interview question. """ import re def palindrome_permutation(s): """Checks if the string is a valid permutation of a palindrome.""" chars_count = {} # Ignore whitespace s = re.sub("\s+", "", s) for c in s: if c in chars_count: chars_count[c] += 1 else: chars_count[c] = 1 if len(s) % 2 == 0: for v in chars_count.values(): if not v % 2 == 0: return False return True else: odd_values = 0 for v in chars_count.values(): if not v % 2 == 0: odd_values += 1 if odd_values is 1: return True return False
c1329d1da410c7cef73a0585f444890d1d86ce1d
RapunzeI/Python
/Chapter_6/31.py
527
3.8125
4
from random import * def craps(): dice1 = randint(1, 6) dice2 = randint(1, 6) sum = dice1 + dice2 if sum == 7 or sum == 11: return 1 elif sum == 2 or sum == 3 or sum == 12: return 0 else: while True: dice1 = randint(1, 6) dice2 = randint(1, 6) sum2 = dice1 + dice2 if sum2 == sum: return 1 elif sum2 == 7: return 0 print(craps()) print(craps()) print(craps())
e584c18e59a3187bbf8038a1f9a52505b6a0b21a
asiajo/python-training-files
/Really small various scripts/Condensing Sentences.py
234
3.96875
4
import re """It removes multiplied consecutive groups of letters""" def condensing_sentences(s): return re.sub('(\S+)\s+\\1', '\\1', s) text = 'Digital alarm clocks scare area children.' print(condensing_sentences(text))
d12ecefab68f42468f32a3b13a130fdee72c7f7f
alexalvg/cursoPython
/EjsBucles.py/ÑIA3.9.py
785
4.09375
4
#Escribir un programa que almacene la cadena de # caracteres contraseña en una variable, # pregunte al usuario por la contraseña # hasta que introduzca la contraseña correcta. #contraseña = "password" #ask = str(input("¿Cuál es la contraseña?: ")) #key = "contraseña" #password="" #NO ENTIENDO PARA QUE PONE ESTO, NO SOBRA? #while password != key: # password = input("Introduce la contraseña: ") #print("Contraseña correcta") #no entiendo porque hay que definir antes lo de intento # si se supone que el input te almacena la respuesta del usuario en una variable #¿se guarda vacía para poder comparar en el while? password = "Alex" intento = "" while intento != password: intento = input("introduce contraseña: ") print("vamus")
5fef74fb4ebd6be519c353acfedf542c8d28d9e2
sgrade/pytest
/testdome/binary_search_tree.py
2,251
3.859375
4
# """Binary search tree (BST) is a binary tree where the value of each node is larger or equal to the values in all the nodes in that node's left subtree and is smaller than the values in all the nodes in that node's right subtree. Write a function that checks if a given binary search tree contains a given value. For example, for the following tree: n1 (Value: 1, Left: null, Right: null) n2 (Value: 2, Left: n1, Right: n3) n3 (Value: 3, Left: null, Right: null) Call to contains(n2, 3) should return True since a tree with root at n2 contains number 3.""" import collections class BinarySearchTree: Node = collections.namedtuple('Node', ['left', 'right', 'value']) @staticmethod def contains(root, value): # print(root) if root is not None: root_value = root.value root_left = root.left root_right = root.right if root_value == value: # Found return True elif root_value <= value: # print('looking for', value, 'in the right node: ', root.right) return BinarySearchTree.contains(root_right, value) else: # print('looking in the levg node: ', root.left) return BinarySearchTree.contains(root_left, value) else: return False n1 = BinarySearchTree.Node(value=1, left=None, right=None) n3 = BinarySearchTree.Node(value=3, left=None, right=None) n2 = BinarySearchTree.Node(value=2, left=n1, right=n3) print(BinarySearchTree.contains(n2, 3)) # My own test case based on # https://ru.wikipedia.org/wiki/Двоичное_дерево_поиска """ n1 = BinarySearchTree.Node(value=1, left=None, right=None) n4 = BinarySearchTree.Node(value=4, left=None, right=None) n7 = BinarySearchTree.Node(value=7, left=None, right=None) n6 = BinarySearchTree.Node(value=6, left=n4, right=n7) n13 = BinarySearchTree.Node(value=13, left=None, right=None) n14 = BinarySearchTree.Node(value=14, left=n13, right=None) n3 = BinarySearchTree.Node(value=3, left=n1, right=n6) n10 = BinarySearchTree.Node(value=10, left=None, right=n14) n8 = BinarySearchTree.Node(value=8, left=n3, right=n10) print(BinarySearchTree.contains(n8, 2)) """
8c37b00a3c1d1ef62f15d3849165df8dec44a430
abhishekanand10/dataStructurePy3
/mislPy/mergeSort.py
878
3.796875
4
def mergesort(a): if len(a) == 1: return else: # tmp = [] mid = len(a) // 2 ll = a[:mid] rr = a[mid:] mergesort(ll) mergesort(rr) merge(a, ll, rr) return a def merge(a, leftlist, rightlist): ln = len(leftlist) rn = len(rightlist) x = y = z = 0 while x < ln and y < rn: if leftlist[x] <= rightlist[y]: a[z] = leftlist[x] x += 1 else: a[z] = rightlist[y] y += 1 z += 1 if x < len(leftlist): for i in range(x, ln): a[z] = leftlist[x] z += 1 x += 1 elif y < len(rightlist): for i in range(y, rn): a[z] = rightlist[y] z += 1 y += 1 if __name__ == '__main__': lst = [7, 5, 1, 3, 2] print(mergesort(lst))
f653269d1f3cc3d6d6b15c8943aa291d6193e52c
djinnome/MaxMass
/src/codebase/GPR.py
1,946
3.578125
4
from pyparsing import * import types import pdb class Node(object): def __init__(self, data): self.data = data self.children = [] def add_child(self, obj): self.children.append(obj) def other_name(self, level=0): print '\t' * level + repr(self.data) for child in self.children: child.other_name(level+1) # traverse GPR list and create trees def traverse_GPR(GPR_list,root): if "AND" not in GPR_list and "OR" not in GPR_list: if type(GPR_list) is list: root.add_child(Node(GPR_list[0])) else: root.add_child(Node(GPR_list)) return if GPR_list != "AND" and GPR_list != "OR": if "AND" in GPR_list: logic = "AND" if "OR" in GPR_list: logic = "OR" new_node = Node(logic) root.add_child(new_node) root = new_node for child in GPR_list: # only go deeper is a list if child == "AND" or child == "OR": continue traverse_GPR(child,root) def parathesis_to_list(GPR): #pyparse to break GPR into nested list enclosed = Forward() nestedParens = nestedExpr('(', ')', content=enclosed) enclosed << (Word(alphanums+'.') | ',' | nestedParens) GPR_list = enclosed.parseString(GPR).asList() return GPR_list if __name__ == '__main__': # test examples GPR = "((g1 OR g2) AND (g2 OR (g1 AND (g3 OR g4)) OR (g1 AND g4) OR (g3 AND g4)))" # GPR = "(((g1) OR (g2)) AND ((g2) OR ((g1) AND ((g3) OR (g4))) OR ((g1) AND (g4)) OR ((g3) AND (g4))))" # GPR = "((g1) OR (g2))" # GPR = "(g1 OR g2)" # GPR = "((g1 and g2) or (g2 and g3))" GPR = GPR.replace("or","OR").replace("and","AND") GPR_list = parathesis_to_list(GPR) print GPR_list # convert to trees GPR_tree = Node("R1") traverse_GPR(GPR_list[0],GPR_tree) GPR_tree.other_name()
b9b2906004f832bbcff77c649ae59fca51e65f84
rksam24/MCA
/Sem 1/DM/Q6.Planer.py
671
4.25
4
#Program to check if graph is planer or not #this program not work for K3,3 def main(): #taking total number vertex and edges from user vertex=int(input("Enter the Total number of vertex in the graph: ")) edges=int(input('Enter the Total number of edges in the graph: ')) #max edge of vertex max=vertex*(vertex-1)/2 #checking the edge is valid or not if edges>max: print("Edge is not correct") exit() #checking the graph is planer or not if (edges<=3*vertex-6 and vertex>=3) or vertex==2: print("Graph is planer ") else: print("Graph is not planer ") if __name__=="__main__": main()
cb78f864b309c19bc51cf0a8f05f8d70f6b9be3e
radics100/radix_sandbox_python
/first_codes/pelda4.py
267
3.84375
4
x = [1, 'two', 3.0, [4, 'four'], 5] y= [1, 'two', 3.0, [4, 'four'], 5] print('x is {}'.format(x)) print(id(x)) print(id(y)) if isinstance(y, tuple): print("tuple") elif isinstance(y, list): print('list') else: print('nope') print(type(x))
8ee9a2f9a7858471b417acc0dd09f10d05a395d5
lukaskiss222/PTS_DU1
/decorator.py
1,813
3.65625
4
import login def login_decorator(Cls): """decorate class, make it login :Cls: input class :returns: decorated class """ class NewCls(object): """decorated class""" def __init__(self,*args,**kwargs): """ Constructor""" self.login = login.Login() self.oInstance = Cls(*args,**kwargs) def __getattribute__(self, s): """this is called whenever any attribute of a NewCls object is accessed. This function first tries to get the attribute off NewCls. If it fails then it tries to fetch the attribute from self.oInstance (an instance of the decorated class). :arg1: what we want to get :returns: return attribute """ try: # I call parent __getattribute__, # because if I dont do it. It will loop forever. # __getattribute__ return attribute of class x = super(NewCls, self).__getattribute__(s) except: pass # not find in my class, should look in instance else: return x # I find the attribute in my class, just return it # My class (decorator) don t have attribute s, so I ask # if the decorated class has that attribute. x = self.oInstance.__getattribute__(s) return x def execute(self): """ This function decorates execute and before execute function execute of oInstance first call login function and then execute oInstance execute """ if self.login.login(): self.oInstance.execute() else: print("Wrong Password") return NewCls
7f070a5fafe17272bea460844a6a0dba83f61ba8
johnkle/FunProgramming
/Python/pythonBasic/thread1.py
903
3.5625
4
import threading import time class mythread(threading.Thread): def __init__(self,threadID,name,count): #表示定义 加self #threading.Thread.__init__(self) #表示调用 不加self super().__init__() self.threadID = threadID self.name = name self.count = count def run(self): print('开始线程'+self.name) print_name(self.name,self.count,1) print('结束线程'+self.name) def print_name(threadName,count,delay): while count: time.sleep(delay) print ("%s: %s" % (threadName, time.ctime(time.time()))) count -= 1 if __name__ == "__main__": thread1 = mythread(1,'thread-1',6) thread2 = mythread(2,'thread-2',5) #主线程退出 kill thread1 #thread1.setDaemon(True) thread1.start() thread2.start() #thread1.join() thread2.join() print('主线程')
101017e4c713c49124e944a56c341b266f6e7699
shulme801/Python101
/motorcycles.py
850
4.09375
4
# Stephen H. Hulme 8 Nov 2020 # Basic work with lists. Experiments are commented out motorcycles = [] motorcycles.append('honda') motorcycles.append('harley davidson') motorcycles.append('ducati') # motorcycles.append(14) This works b/c you can have a list with heterogenous types. This stmt adds an integer to the # end of the list motorcycles.insert(0,'indian') myMSG = (", ".join(motorcycles)).title() print(myMSG) too_expensive = ('ducati') motorcycles.remove(too_expensive) print(motorcycles) print(f"\nA {too_expensive.title()} is too expensive for me") # print(motorcycles[-1].title()) assuming the last item in the list is a variable of type string, this prints the last item # with Title capitalization # print(motorcycles.title()) should get an error because a list object has no "title" attribute. # motorcycles.append(14) # print(motorcycles[-1])
c633e1f4f8e76d3d3c3fb02544674377c00fd336
ArunCSK/PythonWeek1
/sets.py
1,089
4.25
4
#create set def createset(): iset = {"1","2","3"} print("Sets: ",iset) #iterate set def iterate(): iset = {"1","2","3"} print("Sets: ",iset) for val in iset: print(val) #add set def add(): iset = {"1","2","3"} print("Sets: ",iset) item = input("Enter item to be add:") iset.add(item) print("Sets: ",iset) #remove for set def remove(): iset = {"1","2","3"} print("Sets: ",iset) item = input("Enter item to be removed:") iset.remove(item) print("Sets: ",iset) #remove for set if present def check(): iset = {"1","2","3"} print("Sets: ",iset) item = input("Enter item to be removed:") for val in iset: if val == item: iset.remove(item) break print("Sets: ",iset) #accept user input options io = input("1.create 2.iterate 3.add 4.remove 5.check Enter values:") if io == "create": createset() elif io == "iterate": iterate() elif io == "add": add() elif io == "remove": remove() elif io == "check": check() else: print('Execute Succes!!!')
5941e7e4a95cbfdf1b4379a2e238a2763ecaa41c
Philtesting/Exercice-Python
/7eme cours/Programme/Ex60.py
182
3.5625
4
def hascap(s): mots = s.split() majs = [] for m in mots: if m[0].isupper(): majs.append(m) return majs print(hascap("Il était une fois, Jean François"))
a4aba4d46753772a4a90e2f515e59e57837373d3
TijanaSekaric/SP-Homework00
/ex4.py
170
3.84375
4
def sum_of_squares2(n): n -= 1 sum = 0 while n > 0: if n % 2 != 0: sum += n * n n -= 1 return sum print(sum_of_squares2(8))
9afc2fee6a3d8df799ba4745db8254147449204e
lucianamaroun/probabilistic-ranking
/src/auxiliary.py
468
3.984375
4
""" Contains common and simple procedures used by several modules. """ import os def adequate_dir(dirname): """ Formats a directory name in order to terminate with '/' if absent and creates it if necessary. Args: dirname: the string name of the directory to format. Returns: A string with the formatted directory name. """ if not os.path.isdir(dirname): os.makedirs(dirname) return dirname if dirname[-1] == '/' else dirname + '/'
f229b0c47a9c025bc032a0cba5a3e945e7df4cc4
tanghowl/Leetcode
/topic2.py
1,130
4.03125
4
""" 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 示例: 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807 """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: number1 = self.chain2number(l1) number2 = self.chain2number(l2) result_number = number1 + number2 result_chain = self.number2chain(result_number) return result_chain def chain2number(self, list_node): return int(''.join(map(str, list_node[::-1]))) def number2chain(self, number): return list(str(number))[::-1] # 不了解链表的数据结构,后面再解答此题
4f33d8ebabfb181d0e0758eb4a72545bb496c230
ksaubhri12/ds_algo
/geeksForGeeks/algorithms/search/ternarySearch.py
506
3.9375
4
def ternarySearch(arr, l, r, x, ): if r >= l: mid1 = l + (r - l) / 3 mid2 = mid1 + (r - l) / 3 if arr[mid1] == x: return mid1 if arr[mid2] == x: return mid2 if arr[mid1] > x: return ternarySearch(arr, l, mid1 - 1, x) if arr[mid1] < x < arr[mid2]: return ternarySearch(arr, mid1 + 1, mid2 - 1, x) if arr[mid2] < x: return ternarySearch(arr, mid2 + 1, r, x) else: return -1
042f7e1c0ea571ed55130757e1044f3ecfa8865c
arunekuriakose/MyPython
/diooo.py
8,633
3.71875
4
sel=[] tp=[] def p_menu(): l=[[1,"PA",230,330,430],[2,"PB",240,340,440,],[3,"PC",250,350,450]] print() print("*************************************") print("** S.no Pizza **") print("*************************************") for i in l: print("** **") print("**",i[0]," ",i[1]," **") print("** Small Medium Large **") print("** ",i[2]," ",i[3]," ",i[4]," **") print("** **") print("*************************************") print("** **") print("** 4 GoBack **") print("** **") print("*************************************") e=1 print("Please select the Pizza you want from above menu:") while e: k=int(input()) d=k-1 if d<3: print("You have selected: ",l[d][1]) print("Please select the size(S for Small, M for Medium, L for Large): ") print(" Small Medium Large ") print(" ",l[d][2]," ",l[d][3]," ",l[d][4]," ") c=1 while c: s=input() if s=="s" or s=="S": print("You have selected",l[d][1],"pizza of size Small costing",l[d][2]) elif s=="m" or s=="M": print("You have selected",l[d][1],"pizza of size Medium costing",l[d][3]) elif s=="l" or s=="L": print("You have selected",l[d][1],"pizza of size Large costing",l[d][4]) else: print("Please enter only the mentioned sizes") continue c=0 sel.append([l[d][1],l[d][2]]) tp.append(l[d][2]) break elif d==3: menu() else: print("please select from given menu only") continue e=0 def s_menu(): l=[[1,"SA",130],[2,"SB",230],[3,"SC",330]] print() print("*************************************") print("** S.no Sides **") print("*************************************") for i in l: print("** **") print("**",i[0]," ",i[1]," **") print("** ",i[2]," **") print("** **") print("*************************************") print("** **") print("** 4 GoBack **") print("** **") print("*************************************") e=1 print("Please select the Sides you want from above menu:") while e: k=int(input()) d=k-1 if d<3: print("You have selected Sides",l[d][1],"costing",l[d][2]) sel.append([l[d][1],l[d][2]]) tp.append(l[d][2]) elif d==3: menu() else: print("please select from given menu only") continue e=0 def dr_menu(): l=[[1,"DrA",10],[2,"DrB",20],[3,"DrC",30]] print() print("*************************************") print("** S.no Drinks **") print("*************************************") for i in l: print("** **") print("**",i[0]," ",i[1]," **") print("** ",i[2]," **") print("** **") print("*************************************") print("** **") print("** 4 GoBack **") print("** **") print("*************************************") e=1 print("Please select the Drinks you want from above menu:") while e: k=int(input()) d=k-1 if d<3: print("You have selected Drink",l[d][1],"costing",l[d][2]) sel.append([l[d][1],l[d][2]]) tp.append(l[d][2]) elif d==3: menu() else: print("please select from given menu only") continue e=0 def des_menu(): l=[[1,"DsA",55],[2,"DsB",65],[3,"DsC",75]] print() print("*************************************") print("** S.no Desserts **") print("*************************************") for i in l: print("** **") print("**",i[0]," ",i[1]," **") print("** ",i[2]," **") print("** **") print("*************************************") print("** **") print("** 4 GoBack **") print("** **") print("*************************************") e=1 print("Please select the Desserts you want from above menu:") while e: k=int(input()) d=k-1 if d<3: print("You have selected Dessert",l[d][1],"costing",l[d][2]) sel.append([l[d][1],l[d][2]]) tp.append(l[d][2]) elif d==3: menu() else: print("please select from given menu only") continue e=0 def menu(): print() print("*************************************") print() print("Please choose from the below menu:") l=[[1,"Pizza"],[2,"Sides"],[3,"Drinks"],[4,"Desserts"],[5,"Exit"]] for i in l: print(i[0],i[1]) print() print("(Enter the number)") print() f=1 while f: j=input() if j=="1": p_menu() elif j=='2': s_menu() elif j=='3': dr_menu() elif j=='4': des_menu() elif j=='5': print("Thank you for visiting") else: print("Please choose the right option") continue f=0 b=1 while b: n=input("Enter your name: ") if n=="": print("Invalid Input") print("Do you wish to continue? (Y or N)") y=input() if y=="y" or y=="Y": continue elif y=="n" or y=="N": print("Thank you for visiting us") break else: print("Please enter the valid input") else: print("Dominos".center(100,"*")) print("Welcome Mr/Ms",n) print() menu() c=True while c: print() print() print("Your selected items are:") print("*******************************************") print(" S.No Selected Item Cost") print("*******************************************") q=0 for i in sel: print(" ",q+1," ",i[0]," ",i[1]) print() q+=1 print("*******************************************") print(" Total cost: ",sum(tp)) print("*******************************************") print() print("Do you need anything more? (Y or N)") y=input() if y=="y" or y=="Y": menu() continue elif y=="n" or y=="N": print() else: print("Please enter the valid input") continue print("Do you want to remove anything? (Y or N)") z=input() if z=="y" or z=="Y": print("which one to remove?") t=int(input()) del sel[t-1] del tp[t-1] elif z=="n" or z=="N": print("Please pay the bill of",sum(tp)," and GTFO") print("Thank you for visiting us, Please visit again") c=False b=0 else: print("Please enter valid input") continue b=0
c0be8db2b10db10c3d7c5db073adbe6c35d015a0
xoempire/Python-Challanges
/22-reading-from-a-file.py
524
4.0625
4
# logc: # reading from a file which has multiple names in it # we woudl print the content of the file # the program woudl tell us how many names there are in the list # the program would also tell us the number of times that a name has been repeated counter_dict = {} with open("/Users/xoempire/Desktop/names.txt") as filey: line = filey.readline() while line: line = line.strip('\n') if line in counter_dict: counter_dict[line] += 1 else: counter_dict[line] = 1 line = filey.readline() print(counter_dict)
0bcb5ba32604b44e75f754a85d94677f73358726
EduardoEspinosaLahoz/Primera-Evaluaci-n
/bucle_10.py
840
3.703125
4
def bucle_10(): print"*******************" print"* PARES E IMPARES *" print"*******************" #Suma de numeros pares e impares nfinal=input("Hasta que numero quieres sumar?") #Definimos una variable para contar los pares n_pares=0 #Inicializamos la variable a cero #Definimos una variable para contar los pares n_impares=0 #INicializamos la variable a cero for numero in range(1,nfinal+1): #para cada numero me pregunto si es par o impar if(numero%2==0): print str(numero)," es PAR" n_pares=n_pares+1 else: print str(numero)," es IMPAR" n_impares=n_impares+1 print "He contado ",n_pares," numeros pares." print "He contado ",n_impares," numeros impares." bucle_10()
43dad805e7cf76e29341030e8ea042c5dee770e5
Leal31/cursopython
/Ejercicios_condiciones.py
2,903
4.03125
4
#Dos numeros y los compara para ver cual es par o cual es impar numero1 = int(input("Digita un numero: ")) numero2 = int(input("Digita otro numero: ")) if numero1 % 2 == 0 and numero2 % 2 == 0: print("Ambos son pares") elif numero1 % 2 == 0 and numero2 % 2 != 0: print(f"{numero1} es par") elif numero1 % 2 != 0 and numero2 % 2 == 0: print(f"{numero2} es par") else: print("ninguno es par") numero1 = int(input("Digite un numero: ")) numero2 = int(input("Digite un numero: ")) numero3 = int(input("Digite un numero: ")) if numero1 > numero2 and numero1 > numero3: print(f"{numero1} es el numero mayor ") elif numero2 > numero1 and numero2 > numero3: print(f"{numero2} es el numero mayor") elif numero3 > numero1 and numero3 > numero2: print(f"{numero3} es el numero mayor") elif numero1 == numero2 and numero1 == numero3 and numero2 == numero3: print("Todos los numeros son iguales") caracter = input("Digite un caracter por favor: ").lower() if caracter == 'a' or caracter == 'e' or caracter == 'i' or caracter == 'o' or caracter == 'u': print(f"{caracter} es una vocal") else: print(f"{caracter} no es una vocal") numero1 = float(input("Digite un numero: ")) numero2 = float(input("Digite un numero: ")) opcion = input("Digite que quisiera hacer (Sumar(+), Restar(-), Multiplicar(*), Dividir(/))") if opcion=='+': operacion = numero1 + numero2 print(f"La suma de {numero1} y {numero2} es: {operacion:.2f}") elif opcion == '-': operacion = numero1 - numero2 print(f"La resta de {numero1} y {numero2} es: {operacion:.2f}") elif opcion == '*': operacion = numero1 * numero2 print(f"La multiplicacion de {numero1} y {numero2} es: {operacion:.2f}") elif opcion == '/': operacion = numero1 / numero2 print(f"La division de {numero1} y {numero2} es: {operacion:.2f}") else: print("Eso no es un caracter valido") saldo_inicial = 1000 usuario = input("Que quisiera hacer en su cuenta:\n (I = ingresar dinero)\n (R = Retirar dinero)\n (M = Mostrar dinero en su cuenta)\n (S = Salir)").upper() if usuario == 'I': ingresar = float(input("Cuanto dinero desea ingresar?: ")) saldo_inicial += ingresar print(f"El saldo de su cuenta ahora es: {saldo_inicial}") print("Muchisimas gracias, vuelva pronto") elif usuario == 'R': retirar = float(input("Cuanto dinero desea retirar?: ")) if retirar > saldo_inicial: print("No puede retirar tanto dinero") else: saldo_inicial -= retirar print(f"Su saldo restante es: {saldo_inicial}") print("Muchisimas gracias, vuelva pronto") elif usuario == 'M': print(f"El saldo que hay en su cuenta es: {saldo_inicial}") print("Muchisimas gracias, vuelva pronto") elif usuario == 'S': print("Muchisimas gracias, vuelva pronto") else: print("Esto no es una opcion valida, por favor ingrese de nuevo para ingresar una opcion valida")
c98ce3a929d63eb2eb06a3c85f8a0bbdca88c72c
lzhui/python_space
/函数式编程/hign-order.py
2,007
3.96875
4
#!/usr/bin/python # -*- coding: UTF-8 -*- print abs(-10) print abs a = abs(-10) print a #变量可以指向函数 a = abs print a def add(x, y, f): return f(x) + f(y) print add(-5, 6, abs) def f(x): return x * x print map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) print map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]) def add(x, y): return x + y print reduce(add, [1, 3, 5, 7, 9]) def fn(x, y): return x * 10 + y print reduce(fn, [1, 3, 5, 7, 9]) #Python内建的filter()函数用于过滤序列 def is_odd(n): return n % 2 == 1 print filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]) # 结果: [1, 5, 9, 15] #把一个序列中的空字符串删掉,可以这么写: def not_empty(s): return s and s.strip() print filter(not_empty, ['A', '', 'B', None, 'C', ' ']) # 结果: ['A', 'B', 'C'] #排序算法 #Python内置的sorted()函数就可以对list进行排序 print sorted([36, 5, 12, 9, 21]) #sorted()函数也是一个高阶函数 def reversed_cmp(x, y): if x > y: #正常来说是返回1 return -1 if x < y: return 1 return 0 #传入自定义的比较函数reversed_cmp,就可以实现倒序排序: print sorted([36, 5, 12, 9, 21], reversed_cmp) #字符串排序 print sorted(['bob', 'about', 'Zoo', 'Credit']) #对字符串排序,是按照ASCII的大小比较的,由于'Z' < 'a',结果,大写字母Z会排在小写字母a的前面 #['Credit', 'Zoo', 'about', 'bob'] #现在,我们提出排序应该忽略大小写,按照字母序排序。要实现这个算法,不必对现有代码大加改动,只要我们能定义出忽略大小写的比较算法就可以 def cmp_ignore_case(s1, s2): u1 = s1.upper() u2 = s2.upper() if u1 < u2: return -1 if u1 > u2: return 1 return 0 #忽略大小写来比较两个字符串,实际上就是先把字符串都变成大写(或者都变成小写),再比较 print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case) #['about', 'bob', 'Credit', 'Zoo']
bda83b9c946726011def3734ddf0ec5b0616108e
MayankVerma105/Python_Programs
/percentage1.py
611
3.890625
4
def main(): totalMarks = 0 nSubjects = 0 while True: marks = input('Marks for Subject ' + str(nSubjects + 1) + ' : ') if marks == '': break marks = float(marks) if marks < 0 and marks > 100: print('INVALID MARKS') continue nSubjects = nSubjects + 1 totalMarks += marks percentage = totalMarks / nSubjects print('Total Marks : ',int(totalMarks)) print('Number of subjects',nSubjects) print('Percentage : ',round(percentage)) if __name__ == '__main__': main()
56e28766976a316b765f72c37fb61052173d9463
suhanacharya/python-jetbrains-academy
/Vowels/task.py
156
4.1875
4
vowels = 'aeiou' # create your list here letters = list(input()) vowel_in_word = [letter for letter in letters if letter in vowels] print(vowel_in_word)
3749be2d3a105643592b7338474903194c1a7022
Kawser-nerd/CLCDSA
/Source Codes/AtCoder/arc007/A/4778782.py
91
3.71875
4
X = input() s = input() result = "".join([c for c in s if c not in X]) print(result)
489a2172e583e0e54a3ea91faf82df4097e11077
NSASiddhartha/BitsHyderabad_NSASiddhartha
/IdentyQ5.py
288
3.78125
4
#Question5: import numpy as np list1 = [] array1 = np.random.randint(100, size = 10) tf = np.array([True, False]) array2 = np.random.choice(tf, len(array1)) for x in range(0,len(array1)): if array2[x] is True: list1.append(array1[i]) print(array1) print(array2) print(list1)
6e2203f3479146a72bc4baab919f336e6922ff08
SimonBuettner/MachineLearning
/Decision Tree/decision_tree.py
1,646
3.9375
4
"""This code gives an overview how to create a decision tree """ import pandas as pd import graphviz from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.tree import export_graphviz from helper import plot_classifier # Read CSV-File: DF = pd.read_csv("desease.csv") # Returns the first 5 rows: print(DF.head()) X = DF[["monthlySport", "monthlyHealthyFood"]].values Y = DF["desease"].values # Splitting the Set in Train and Test Data: XTRAIN, XTEST, YTRAIN, YTEST = train_test_split(X, Y, random_state=0, test_size=0.25) # Creates a decesion tree model with a maximum node depth of 5 # and with at least 2 numbers of samples per leaf MODEL = DecisionTreeClassifier(criterion="gini", max_depth=5, min_samples_leaf=2) MODEL = MODEL.fit(XTEST, YTEST) print(MODEL.score(XTEST, YTEST)) # Export tree to PNG-file TREE = export_graphviz(MODEL, None, feature_names=["monthlySport", "monthlyHealthyFood"], class_names=["no desase", "desease"], rounded=True, filled=True) SRC = graphviz.Source(TREE, format="png") SRC.render("./datei", view=True) # prints the diagram plot_classifier(MODEL, XTRAIN, YTRAIN, proba=True, xlabel="monthlySport", ylabel="monthlyHealthyFood") plot_classifier(MODEL, XTEST, YTEST, proba=True, xlabel="monthlySport", ylabel="monthlyHealthyFood")
d03a99d55933462219041a0b05994c1976d92358
higor-gomes93/curso_programacao_python_udemy
/Sessão 13 - Exercícios/ex4.py
799
4.09375
4
''' Faça um programa que receba do usuário um arquivo de texto e mostre na tela quantas letras são vogais e quantas são consoantes. ''' raiz = 'c:/Users/Higor H/Documents/Estudos/Python' pasta = raiz + '/Curso de Programação em Python (Udemy)/Notas de Aula/Sessão_3_Entrada.py' vogais = ['a', 'e', 'i', 'o', 'u'] vogais.extend([i.upper() for i in vogais]) consoantes = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'] consoantes.extend([i.upper() for i in consoantes]) with open(pasta, 'r', encoding='UTF-8') as arquivo: vog = 0 cons = 0 for i in arquivo.read(): if i in vogais: vog += 1 elif i in consoantes: cons += 1 print(f'Existem {vog} vogais e {cons} consoantes no texto.')
e344ead13ab8527e36c10f52370e82bd158b9ab6
hyang012/leetcode-algorithms-questions
/005. Longest Palindromic Substring/Longest_Palindromin_Substring.py
1,020
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Leetcode 5. Longest Palindromin Substring Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. Example 1: Input: "babad" dabab Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: "cbbd" Output: "bb" """ def longestPalindrome(s): """ :type s: str :rtype: str """ if not s: return '' elif len(s) == 1: return s max_len = 1 start = 0 for i in range(1, len(s)): if i - max_len >= 1 and s[(i-max_len-1):(i+1)] == s[(i-max_len-1):(i+1)][::-1]: start = i - max_len - 1 max_len += 2 continue if i - max_len >= 0 and s[(i-max_len):(i+1)] == s[(i-max_len):(i+1)][::-1]: start = i - max_len max_len += 1 continue return s[start:(start+max_len)] print(longestPalindrome('cecbaa')) print(longestPalindrome('cbbd'))
53c1ad3297fd3526ceed8d23689c5b127d340262
mbeven/FINM_2016_SPRING
/FINM 33150/HW2/Michael_Beven_HW2.py
14,563
3.515625
4
# Michael Beven # University of Chicago - Financial Mathematics # FINM 33150 - Quantitative Strategies and Regression # Homework 2 # make plots come up in this window - ipython notebook # %matplotlib inline # import packages import matplotlib.pyplot as plt import pandas as pd import keyring import numpy as np import Quandl # write the code in a function, which spits out a final dataframe of results # makes it easier for analysis def strat(M,g,j,s,X_code,Y_code,X_close,X_volume,Y_close,Y_volume): """ This function creates a dataframe with results to a spread trading strategy (see HW2 of FINM 33150 - Quantitative Strategies and Regression) Inputs: M ~ return difference calculation time frame. M cannot exceed the number of trading days between 2013-12-02 and 2014-01-01 g ~ entering threshold j ~ exiting threshold s ~ stop loss threshold X_code ~ Quandl code for X Y_code ~ Quandl code for Y X_close ~ X column name for close X_volume ~ X column name for volume Y_close ~ Y column name for close Y_volume ~ Y column name for volume Example of calling function: strat(10,0.01,0.008,0.10,'GOOG/NYSE_XSD','YAHOO/SMH','GOOG.NYSE_XSD - Close', 'GOOG.NYSE_XSD - Volume','YAHOO.SMH - Close','YAHOO.SMH - Volume') """ ############################################################################ #2 DATA ############################################################################ # grab data using Quandl raw_data = Quandl.get(list((X_code,Y_code)),authtoken=keyring.get_password('Quandl','mbeven'), trim_start="2013-12-02",trim_end="2015-12-31",returns="pandas") # take a subset of columns of the close data and volume (volume needed for daily # dollar volume) raw_data_close = pd.DataFrame(raw_data.ix[:,(X_close,X_volume,Y_close,Y_volume)]) raw_data_close.columns = ['XP','XV','YP','YV'] # calculate daily dollar volumes XSD_DDV = pd.DataFrame(raw_data_close.XP*raw_data_close.XV) XSD_DDV.columns = ['XDDV'] # create 15 day rolling median of data using Pandas Nt = pd.DataFrame(pd.rolling_median(XSD_DDV.XDDV,15)) Nt.columns = ['Nt'] ############################################################################ #3 EXERCISE ############################################################################ # capital - set K now that we have Nt K = np.max(2*Nt.Nt) # set up difference calculation of returns based on M previous days. # create log return columns and sum over M days. assumes # returns are normally distributed # log returns - use the shift technique to calculate XR = pd.DataFrame(np.log(raw_data_close['XP']) - np.log(raw_data_close['XP'].shift(1))) XR.columns=['XR'] YR = pd.DataFrame(np.log(raw_data_close['YP']) - np.log(raw_data_close['YP'].shift(1))) YR.columns=['YR'] # difference of X and Y Delta = pd.DataFrame(XR.XR-YR.YR) Delta.columns=['Delta'] # previous M day accumulated difference DeltaM = pd.DataFrame(pd.rolling_sum(Delta.Delta,M)) DeltaM.columns = ['DeltaM'] # set dataframe and drop the unnecessary month in 2013. This month # is now unnecessary because we have calculated the M day difference. df = pd.concat([raw_data_close,XSD_DDV,XR,YR,Delta,DeltaM,Nt],axis=1) df = df[df.index >= '2014-01-01'] # drop unnecessary date range # add empty signal column - the signal will be our way of telling whether # we are entering or maintaining a trade (in this case Signal = 1). Signal = pd.DataFrame(np.zeros((len(df),1))).set_index(df.index) Signal.columns = ['Signal'] # beginning January 1 2014, start generating signals based on g/j Signal.Signal[np.abs(df.DeltaM) > g] = 1 # should be entering or maintaining trade Signal.Signal[np.abs(df.DeltaM) < j] = -1 # should be exiting or out of trade # account for exiting trades at the end of each month # create empty data frame EOM = pd.DataFrame(np.zeros((len(df),1)),columns=['EOM']).set_index(df.index) for i in range (1,len(df)): # the first trading day can occur on the 1st, 2nd or 3rd day of a month, # which depends on where the weekend falls. If we are in day 1, 2 or 3, # and the previous row is in a day which is different by more than 1 from # the current day, then the previous row must be the last trading day of # the previous month. if ((df.index.day[i] <= 3) and (df.index.day[i]-df.index.day[i-1] != 1)): Signal.Signal[i-1] = -1 #update Signal EOM.EOM[i-1] = 1 #update end of month (EOM) for i in range(1,len(df)): if Signal.Signal[i] == 0:# this is where we are between g and j; a trade is either #being maintained or we are out of a trade Signal.Signal[i] = Signal.Signal[i-1] # fill in where Signal = 0 (will already be # entered or exited from a trade) Signal.Signal[Signal.Signal == -1] = 0 # represent exiting trades with 0 instead of -1 # GTC (gross traded cash) # for GTC, we need to find where the entry point is and what GTC is at that # point, and then track the trade for the whole time that it is maintained. # the GTC value is the same (|$long|+|$short| at position entry time) while # the trade is on. A 1/0 indicator is used to keep track of where entry # points are, these are then set as the GTC and populated for the trade # period. GTC = pd.DataFrame(np.zeros((len(df),1))) GTC = GTC.set_index(df.index) GTC.columns = ['GTC'] GTC.GTC.ix[0] = 1*(Signal.Signal.ix[0] == 1) # set the correct first indicator # set all other entry time indicators GTC.GTC = GTC.GTC + 1*((Signal.Signal == 1) & (Signal.shift(1).Signal == 0)) # mutiply by GTC GTC.GTC = GTC.GTC*(np.abs(np.round(df.Nt/100,0)*df.XP)+np.abs(np.round(df.Nt/100,0)*df.YP)) # populate GTC for the entire trade period for i in range(1,len(df)): if (GTC.GTC[i-1] != 0) & (Signal.Signal[i] == 1): GTC.ix[i] = GTC.ix[i-1] # stop loss Stop = pd.DataFrame(np.zeros((len(df),1))) Stop = Stop.set_index(df.index) Stop.columns = ['Stop'] # mark if the simulation experiences a day such that the present position value # has lost more than a proportion s. Update Stop column and Signal column Stop.Stop[(DeltaM.DeltaM > j) & (GTC.GTC != 0) & (GTC.GTC*s*-1>np.round(Signal.Signal*df.Nt/100,0).shift(1)*-df.Delta)] = 1 Signal.Signal[(DeltaM.DeltaM > j) & (GTC.GTC != 0) & (GTC.GTC*s*-1>np.round(Signal.Signal*df.Nt/100,0).shift(1)*-df.Delta)] = 0 Stop.Stop[(DeltaM.DeltaM < j) & (GTC.GTC != 0) & (GTC.GTC*s*-1>np.round(Signal.Signal*df.Nt/100,0).shift(1)*df.Delta)] = 1 Signal.Signal[(DeltaM.DeltaM < j) & (GTC.GTC != 0) & (GTC.GTC*s*-1>np.round(Signal.Signal*df.Nt/100,0).shift(1)*df.Delta)] = 0 # roll forward the stop until DeltaM is above g again for i in range(1,len(df)): if ((Stop.Stop[i-1]==1) | (Signal.Signal[i-1]==-1)) & (np.abs(df.DeltaM[i]) < g): Signal.Signal[i] = -1 Stop.Stop[i] = 0 Signal.Signal[Signal.Signal == -1] = 0 # represent exiting trades with 0 instead of -1 # add empty columns for entry and exit points Entry = pd.DataFrame(np.zeros((len(df),1))) Entry = Entry.set_index(df.index) Entry.columns = ['Entry'] Exit = pd.DataFrame(np.zeros((len(df),1))) Exit = Exit.set_index(df.index) Exit.columns = ['Exit'] # create entry and exit points Entry.Entry.ix[0] = (Signal.Signal.ix[0] == 1) # set first day of trading Entry.Entry = Entry.Entry + 1*((Signal.Signal == 1) & (Signal.shift(1).Signal == 0)) Exit.Exit.ix[0] = False # cannot exit on the first day Exit.Exit = Exit.Exit + 1*((Signal.Signal == 0) & Signal.shift(1).Signal == 1) # make the trade Size = pd.DataFrame(np.round(Signal.Signal*df.Nt/100,0)) # size of trade Size.columns = ['Size'] # the dollar profit(loss) is going to be the next day after the trade has been # entered. this profit amount will be the difference in returns of X and Y # times the trade size Profit = pd.DataFrame(np.zeros((len(df),1))) Profit = Profit.set_index(df.index) Profit.columns = ['Profit'] for i in range(1,len(df)): if DeltaM.DeltaM[i] > j: Profit.Profit[i] = Size.Size[i-1]*(-df.Delta[i]) if DeltaM.DeltaM[i] < j: Profit.Profit[i] = Size.Size[i-1]*(df.Delta[i]) Profit.ix[0] = 0 # can't calculate profit for the first day Cum_Profit = pd.DataFrame(np.cumsum(Profit.Profit)) #cumulative profit Cum_Profit.columns = ['Cum_Profit'] # capital - the capital available grows(shrinks) on a daily basis, based on # the amount we have profited(lost) K = pd.DataFrame(np.round(K + Cum_Profit.Cum_Profit,0)) K.columns = ['K'] Cum_Return = pd.DataFrame(K.K/K.K[0]-1) Cum_Return.columns = ['Cum_Return'] # set dataframe - make it easier to read and in one table for outputting df = pd.concat([df.XP,df.XV,np.round(df.XDDV,0),np.round(df.YP,2),df.YV,np.round(df.Nt,0),np.round(df.XR,3), np.round(df.YR,3),np.round(df.Delta,3),np.round(df.DeltaM,3),Signal,Entry,Exit, EOM,Size,np.round(GTC,0),Stop,np.round(Profit,0),np.round(Cum_Profit,0),K, Cum_Return], axis=1) return df # output M = 20 G = 0.0014 J = 0.0002 s = 0.00009 X_code = 'EOD/XSD' Y_code = 'EOD/SMH' X_close = 'EOD.XSD - Adj_Close' X_volume = 'EOD.XSD - Adj_Volume' Y_close = 'EOD.SMH - Adj_Close' Y_volume = 'EOD.SMH - Adj_Volume' df = strat(M,G*M,J*M,s,X_code,Y_code,X_close,X_volume,Y_close,Y_volume) # let's see what comes out pd.set_option('display.max_columns', 500) print(df[(df.index.year == 2014) & (df.index.month == 1)]) print(df[(df.index.year == 2015) & (df.index.month == 12)]) # plot DeltaM with entry and exit points plt.figure(1,figsize=(16,8)) plt.title('Difference in Returns Over M Days') plt.ylabel('Return Difference') df.DeltaM.plot(color='black') plt.axhline(y=G*M,color='green') plt.axhline(y=J*M,color='red') plt.axhline(y=-G*M,color='green') plt.axhline(y=-J*M,color='red') Entry_Pts = pd.DataFrame(df.Entry*df.DeltaM) Entry_Pts = Entry_Pts[Entry_Pts != 0] Exit_Pts = pd.DataFrame(df.Exit*df.DeltaM) Exit_Pts = Exit_Pts[Exit_Pts != 0] Stop_Pts = pd.DataFrame(df.Stop*df.DeltaM) Stop_Pts = Stop_Pts[Stop_Pts != 0] p1, = plt.plot(Entry_Pts,'g.') p2, = plt.plot(Exit_Pts,'r.') p3, = plt.plot(Stop_Pts,'r*',ms=10) for i in range(0,len(df)): if df.EOM[i] == 1: plt.axvline(x=df.index[i],color='grey') plt.legend([p1,p2,p3],['Entry Point','Exit Point','Stop-Loss Point'], numpoints=1,loc='lower right') # plot cumulative profit plt.figure(2,figsize=(16,8)) plt.title('Cumulative Profit') plt.ylabel('Dollar Profit') df.Cum_Profit.plot(color='black') Entry_Pts = pd.DataFrame(df.Entry*df.Cum_Profit) Entry_Pts = Entry_Pts[Entry_Pts != 0] Exit_Pts = pd.DataFrame(df.Exit*df.Cum_Profit) Exit_Pts = Exit_Pts[Exit_Pts != 0] Stop_Pts = pd.DataFrame(df.Stop*df.Cum_Profit) Stop_Pts = Stop_Pts[Stop_Pts != 0] p1, = plt.plot(Entry_Pts,'g.') p2, = plt.plot(Exit_Pts,'r.') p3, = plt.plot(Stop_Pts,'r*',ms=10) for i in range(0,len(df)): if df.EOM[i] == 1: plt.axvline(x=df.index[i],color='grey') plt.legend([p1,p2,p3],['Entry Point','Exit Point','Stop-Loss Point'], numpoints=1,loc='lower right') ############################################################################ #4 ANALYSIS ############################################################################ # check overall profit when varying M. need to make j g and s functions of M Perform_M = pd.DataFrame(columns = ['M','Cum_Profit']) G = 0.0014 J = 0.0002 s = 0.00009 X_code = 'EOD/XSD' Y_code = 'EOD/SMH' X_close = 'EOD.XSD - Adj_Close' X_volume = 'EOD.XSD - Adj_Volume' Y_close = 'EOD.SMH - Adj_Close' Y_volume = 'EOD.SMH - Adj_Volume' for M in range(1,25): df = strat(M,G*M,J*M,s,X_code,Y_code,X_close,X_volume,Y_close,Y_volume) Perform_M = Perform_M.append(pd.DataFrame([[M,df.Cum_Profit[-1]]],columns=['M','Cum_Profit']), ignore_index=True) plt.figure(3) plt.plot(Perform_M.M,Perform_M.Cum_Profit,color='black') # M=12 looks optimal plt.title('Profit When Varying M') plt.ylabel('Total Profit (dollars)') plt.xlabel('M (days)') plt.grid() # check overall profit when widening the spread of g and j Perform_W = pd.DataFrame(columns = ['W','Cum_Profit']) M = 20 s = 0.00009 X_code = 'EOD/XSD' Y_code = 'EOD/SMH' X_close = 'EOD.XSD - Adj_Close' X_volume = 'EOD.XSD - Adj_Volume' Y_close = 'EOD.SMH - Adj_Close' Y_volume = 'EOD.SMH - Adj_Volume' for i in range(0,14): i = i/10000 #G = 0.0012+i G = 0.0014 J = 0.0014-i df = strat(M,G*M,J*M,s,X_code,Y_code,X_close,X_volume,Y_close,Y_volume) Perform_W = Perform_W.append(pd.DataFrame([[G,J,G-J,df.Cum_Profit[-1]]],columns=['G','J','W','Cum_Profit']), ignore_index=True) plt.figure(4) plt.plot(Perform_W.W,Perform_W.Cum_Profit,color='black') # window of 0.0011 looks good plt.title('Profit When Widening the Spread of G and J') plt.ylabel('Total Profit (dollars)') plt.xlabel('G-J') plt.grid() # check overall profit when shifting the spread of g and j Perform_S = pd.DataFrame(columns = ['G','J','Cum_Profit']) M = 20 s = 0.00009 X_code = 'EOD/XSD' Y_code = 'EOD/SMH' X_close = 'EOD.XSD - Adj_Close' X_volume = 'EOD.XSD - Adj_Volume' Y_close = 'EOD.SMH - Adj_Close' Y_volume = 'EOD.SMH - Adj_Volume' for i in range(0,20): i = i/10000 G = 0.0012+i J = 0.0000+i df = strat(M,G*M,J*M,s,X_code,Y_code,X_close,X_volume,Y_close,Y_volume) Perform_S = Perform_S.append(pd.DataFrame([[G,J,df.Cum_Profit[-1]]], columns=['G','J','Cum_Profit']),ignore_index=True) plt.figure(5) plt.plot((Perform_S.G+Perform_S.J)/2,Perform_S.Cum_Profit,color='black') # window of 0.005 looks good plt.title('Profit When Shifting the Spread of G and J') plt.ylabel('Total Profit (dollars)') plt.xlabel('Midpoint of G and J') plt.grid() # check overall profit when varying the stop loss level Perform_SL = pd.DataFrame(columns = ['s','Cum_Profit']) M = 20 G = 0.0014 J = 0.0002 X_code = 'EOD/XSD' Y_code = 'EOD/SMH' X_close = 'EOD.XSD - Adj_Close' X_volume = 'EOD.XSD - Adj_Volume' Y_close = 'EOD.SMH - Adj_Close' Y_volume = 'EOD.SMH - Adj_Volume' for s in range(0,40): s = s/100000 df = strat(M,G*M,J*M,s,X_code,Y_code,X_close,X_volume,Y_close,Y_volume) Perform_SL = Perform_SL.append(pd.DataFrame([[s,df.Cum_Profit[-1]]], columns=['s','Cum_Profit']),ignore_index=True) plt.figure(6) plt.plot(Perform_SL.s,Perform_SL.Cum_Profit,color='black') # window of 0.0004 looks good plt.title('Profit When Shifting the Stop Loss Level') plt.ylabel('Total Profit (dollars)') plt.xlabel('s') plt.grid()
6624c0f47f5aafcfc38304cced29e9e224438269
jmseb3/bakjoon
/34.문자열 알고리즘 1/4354.py
350
3.5
4
while True: s = input() if s == ".": break elif s =="": print(0) else: for length in range(len(s),0,-1): cnt,ck =divmod(len(s),length) if ck != 0: continue temp = s[:cnt] if (temp)*length == s: print(length) break
8971ca0d33d22c03314421d84ce6e18194c6ac46
lidongze6/leetcode-
/实现 strStr() 函数.py
450
3.734375
4
def strStr(haystack, needle): l = len(needle) h = len(haystack) if l == 0: return 0 if l == h: if needle == haystack: return 0 else: return -1 else: for i in range(h - l+1): if haystack[i:i + l] == needle: return i return -1 if __name__ == "__main__": haystack = "mississippi" needle = "pi" print(strStr(haystack, needle))
e49bef1824062f10c6aa86c3e2410c6ab6f9c1c6
michealodwyer26/MPT-Senior
/Homework/Week 3/rightAngledTriangle.py
1,039
4.28125
4
''' This program finds if the real numbers a, b, c form a right angled triangle Inputs: a, b, c - float Output: ans - boolean How to do it? Input a, b, c as float Test if the variables are positive Test if the variables form a triangle Test if the variables satisfy Pythagoras Theorem ''' # import modules import math # function to find if a, b, c form a Pythagorean triangle def isPythagoreanTriangle(): ''' isPythagoreanTriangle will return a boolean value true if the values a, b, c satisfy Pythagoras Theorem ''' # input a, b, c a, b, c = map(float, input("Please enter a, b, c : ").split()) ans = True # test if the variables are positive if a <= 0 or b <= 0 or c <= 0: ans = False # end if # test if the variables form a triangle if a >= b+c or b >= a+c or c >= a+b: ans = False # end if # Test if the variables satisfy Pythagoras Theorem if a**2 + b**2 != c**2: ans = False else: ans = True # end if # print the result ans print("Forms a right angled triangle = ", ans) # end def
71530c2e7223b411fa99971c2883ef9835543c1e
arlexmolina/dojopython
/app/test/test_romano.py
2,028
3.8125
4
import unittest numeros = [1000,900,500,400,100,90,50,40,10,9,5,4,1] valor_romano=['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I'] class NumeroRomano(object): def test(self, numero): numero = int(numero) pendiente = numero resultado = '' for i in range(len(numeros)): pendiente_aux = pendiente resultado_aux = resultado while pendiente_aux >= numeros[i]: resultado_aux = resultado_aux + valor_romano[i] pendiente_aux = pendiente_aux - numeros[i] pendiente = pendiente_aux resultado = resultado_aux return resultado # Creamos una clase heredando de TestCase class TestMyCalculator(unittest.TestCase): # Creamos una prueba para probar un valor inicial def test_uno(self): claseRomana = NumeroRomano() numero = claseRomana.test(1) self.assertEqual('I', numero) def test_cuatro(self): claseRomana = NumeroRomano() numero = claseRomana.test(4) self.assertEqual('IV', numero) def test_cinco(self): claseRomana = NumeroRomano() numero = claseRomana.test(5) self.assertEqual('V', numero) def test_cien(self): claseRomana = NumeroRomano() numero = claseRomana.test(100) self.assertEqual('C', numero) def test_quinientos(self): claseRomana = NumeroRomano() numero = claseRomana.test(500) self.assertEqual('D', numero) def test_NOVECIENTOS(self): claseRomana = NumeroRomano() numero = claseRomana.test(900) self.assertEqual('CM', numero) def test_novecientoscincuenta(self): claseRomana = NumeroRomano() numero = claseRomana.test(950) self.assertEqual('CML', numero) def test_novecxinetonoventayocho(self): claseRomana = NumeroRomano() numero = claseRomana.test(998) self.assertEqual('CMXCVIII', numero) if __name__ == '__main__': unittest.main()
bb93485529a293daf7b55014f7e31359eaab1c2f
kevinhan29/python_fundamentals
/08_file_io/08_01_words_analysis.py
1,826
4.125
4
''' Write a script that reads in the words from the words.txt file and finds and prints: 1. The shortest word (if there is a tie, print all) 2. The longest word (if there is a tie, print all) 3. The total number of words in the file. ''' with open("/Users/kevinhan/Documents/CodingNomads/labs/08_file_io/words.txt", "r") as fin: longest = [] shortest = [] total = 0 for line in fin.readlines(): temp = line.strip() if len(longest) == 0: # for the first item in the list, store it in both longest and shortest words list longest.append(temp) shortest.append(temp) continue if len(temp) == len(longest[0]): # if long words are same length, add current word to long word list longest.append(temp) if len(temp) > len(longest[0]): # if current is longer, clear previous longest word list and add current word longest = [] longest.append(temp) if len(temp) == len(shortest[0]): # if short words are same length, add current word to short word list shortest.append(temp) if len(temp) < len(shortest[0]): # if current is shorter, clear previous shortest word list and add current word shortest = [] shortest.append(temp) total += 1 # print the shortest words newline = 0 # helps create a new line every 15th word to help with readability print("\nThe shortest words in the list are:") for words in shortest: print(f"{words:<4s} ", end="") newline += 1 if newline == 15: print("") newline = 0 # print the longest words print("\n\nThe longest words in the list are: ") for words in longest: print(f"{words} ") # print the total number of words print(f"\nThere are {total} words in the file")
10d2360912103ff1531468663cac1d47ec806a32
slawektestowy/bootcamp_d3
/dzien3/przypomnienie.py
351
3.984375
4
# aaa = (3,4,"a",55,44,21) # # print(aaa) # print(aaa[2]) # print(aaa[1:4]) lista = [1,2,6,7,8,34,88] # print(lista) # a = max(lista) # print(a) # b = min(lista) # print(b) # # c = lista.index(a) # print(c) # d = lista.index(b) # print(d) lista_indexow = list((range(len(lista)))) print(lista_indexow) for i in lista_indexow: print(lista[i])
8447fd685bf203b3c582463e6208c02639522942
esddse/leetcode
/medium/380_insert_delete_getrandom_o1.py
1,444
4.09375
4
import random class RandomizedSet: def __init__(self): """ Initialize your data structure here. """ self.items = [] self.val2idx = {} def insert(self, val: int) -> bool: """ Inserts a value to the set. Returns true if the set did not already contain the specified element. """ if self.val2idx.get(val) is None: self.val2idx[val] = len(self.items) self.items.append(val) return True else: return False def remove(self, val: int) -> bool: """ Removes a value from the set. Returns true if the set contained the specified element. """ if self.val2idx.get(val) is None: return False else: idx, last = self.val2idx[val], self.items[-1] self.items[idx] = last self.items.pop() self.val2idx[last] = idx self.val2idx[val] = None return True def getRandom(self) -> int: """ Get a random element from the set. """ idx = random.randint(0, len(self.items)-1) return self.items[idx] # Your RandomizedSet object will be instantiated and called as such: # obj = RandomizedSet() # param_1 = obj.insert(val) # param_2 = obj.remove(val) # param_3 = obj.getRandom()
d48564ed42502e693d2b3680e1873f32f36a4fbc
thinhld80/python3
/python3-13/python3-13.py
502
4
4
#For loop and range #For loop on lists, tuples, sets l = [1,2,3,4] #List t = (1,2,3,4) #Tuple s = {1,2,3,4} #Set for i in s: print(f'i = {i}') #For loop on dictionaries x = dict(Bryan=46,Tammy=48, Heather=28,Chris=30) print(x) for k in x.keys(): print(f'Keys: {k} = {x[k]}') for k,v in x.items(): print(f'Items: {k} = {v}') #Range x = range(5) print(x) for i in x: print(f'Range: {i}') #Range start, stop and step x = range(5,20,3) print(x) for i in x: print(f'Stepped: {i}')
5ef93d4f94dd027b1f45504ed81a3da6ebfa718e
slevinsps/python_prog
/python_labs/интересные задачки/points in area2.py
1,684
3.578125
4
# Спасенов Иван ИУ7-13 # Выписать точки, области которых находятся остальные точки from tkinter import * from math import sqrt # Функция, которая считает угол между векторами def ugol(a1, a2, a3): k1 = [a3[0] - a2[0], a3[1] - a2[1]] k2 = [a1[0] - a2[0], a1[1] - a2[1]] u = (k1[0] * k2[0] + k1[1] * k2[1]) / (sqrt(k1[0] ** 2 + k1[1] ** 2) * (sqrt(k2[0] ** 2 + k2[1] ** 2))) return u # Массив точек a = [[0, 0], [10, -10], [20, -10], [10, -20], [10, -30], [-10, -10], [-10, 10], [10,20], [30,-10], [0,-20], [-5,-25]] def opred_vip(a) min_ld = a[0] # Самая нижняя левая точка for i in range(len(a)): if a[i][1] < min_ld[1]: min_ld = a[i] elif a[i][1] == min_ld[1]: if a[i][0] < min_ld[0]: min_ld = a[i] # Три точки по которым считаем угол между векторами x3 = [] x2 = min_ld x1 = [min_ld[0] - 10, min_ld[1]] q = [] q.append(min_ld) # Массив углов между векторами ug = [0] * (len(a)) # Находим нужные точки while True: for i in range(len(a)): if a[i] != x2 and a[i] != x1: ug[i] = ugol(a[i], x2, x1) elif a[i] == x2 or a[i] == x1: ug[i] = 2 x3 = a[ug.index(min(ug))] if x3 == min_ld: break x1 = x2 x2 = x3 q.append(x3) ug = [0] * (len(a)) print('Точки:') for i in q: for j in i: print(j,end = ' ') print()
1c5ac6edb8312d08872937fd453317eaab9462fa
Tuchev/Python-Fundamentals---january---2021
/02.Data_Types_and_Variables/02.Exercise/04. Sum of Chars.py
174
3.875
4
n = int(input()) count = 0 total_sum = 0 while count != n: symbol = input() total_sum += ord(symbol) count += 1 print(f"The sum equals: {total_sum}")
225741f619a693a2f41a1eccaf328fa232854e6a
rosannaz/hello-world
/projectEuler3.py
824
4
4
#Problem 3 #The prime factors of 13195 are 5, 7, 13 and 29. #What is the largest prime factor of the number 600851475143 ? def isPrime(x): global largest for i in range(2, int(x**(0.5) + 1)): if x % i == 0: return False return True def findLargestPrimeFactor(number): factor = 2 if isPrime(number) == True: largest = number else: while number > 1: if number % factor == 0 and isPrime(number / factor) == True: largest = number / factor break factor += 1 return largest def main(): number = int(raw_input('Please Enter an Integer: ')) print 'The largest prime factor of ' + str(number) + ' is ' + str(findLargestPrimeFactor(number)) + '.' if __name__ == '__main__': main()
181a3630188e37b842736c61ebd0109c5f47be07
jfriend15/visualize-convo
/v1.0/helper.py
372
3.8125
4
''' Helper functions. ''' import math def generate_rgb(xyz): ''' Create an rgb value from a list of three floats TODO create a function that maps more intentionally ''' def map_btwn_01(x): freq = 1 # TODO custom freq return 0.5 * math.sin(freq * x) + 0.5 return [map_btwn_01(xyz[0]), map_btwn_01(xyz[1]), map_btwn_01(xyz[2])] #print(generate_rgb([16,41,8]))
b2cb2dab52101f7647a50e7e3d33a8965fb87fd0
JuanMelendres/The-Modern-Python-3-Bootcamp
/Boolean&Conditional_Logic/calling_in_sick.py
1,499
4.0625
4
''' Calling in sick in this exercise you will be given a few variables that will be set randomly to boolean values (True or False) * actually_sick - when you legit have the flu! * kinda_sick - you´re feeling under the weather and it´s enough to treat yoself with a day off if you can spare it. * hate_your_job - work sucks, I know.. You´re also given a random number of sick_days between 0 and 10. finally, there is a variable called calling_in_sick that you must set true or false based on the bollowing scenarios: set true if: * you´re actually_sick and you have sick_days remaining * you´re kinda_sick and hate_your_job and you vae sick_days remaining Otherwise, set to false: The test check that the value of calling_in_sick is correct based on the conditions specified above. ''' # NO TOUCHING ====================================== from random import choice, randint # randomly assigns values to these four variables actually_sick = choice([True, False]) kinda_sick = choice([True, False]) hate_your_job = choice([True, False]) sick_days = randint(0, 10) # NO TOUCHING ====================================== calling_in_sick = None # set this to True or False with Boolean Logic and Conditionals! # YOUR CODE GOES HERE vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv if actually_sick and sick_days > 0: calling_in_sick = True elif kinda_sick and hate_your_job and sick_days > 0: calling_in_sick = True else: calling_in_sick = False # YOUR CODE GOES HERE ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6bee560f3cd058eed70a286a52adfc9acc5a0775
jliving207/CodeCademy
/Loops_Cheatsheet.py
1,327
4.6875
5
# for <temporary variable> in <list variable>: # <action statement> # <action statement> #each num in nums will be printed below nums = [1,2,3,4,5] for num in nums: print(num) numbers = [0, 254, 2, -1, 3] for num in numbers: if (num < 0): print("Negative number detected!") break print(num) print("-----continue keyword----------") big_number_list = [1, 2, -1, 4, -5, 5, 2, -9] # Print only positive numbers: for i in big_number_list: if i < 0: continue print(i) print("---------range()----------/n The range() function can be used to create a list that can be used to specify the number of iterations in a for loop.") # Print the numbers 0, 1, 2: for i in range(3): print(i) # Print "WARNING" 3 times: for i in range(3): print("WARNING") print("----------------Nested Loops---------------") print("In Python, loops can be nested inside other loops. Nested loops can be used to access items of lists which are inside other lists. The item selected from the outer loop can be used as the list for the inner loop to iterate over.") groups = [["Jobs", "Gates"], ["Newton", "Euclid"], ["Einstein", "Feynman"]] # This outer loop will iterate over each list in the groups list for group in groups: # This inner loop will go through each name in each list for name in group: print(name)
a05ee462dee18c0d8d08637ddf1f6eb6a7050f0c
MartinR2295/University-Exercises-Artificial-Intelligence
/cellular_systems/src/rule.py
1,269
3.59375
4
from .cell import Cell ''' Rule class To handle the rules in the cellular system. Here you can set start_state, end_state and min+max alive neighbours. ''' class Rule(object): def __init__(self, start_state, end_state, min_alive_neighbours, max_alive_neighbours=None): self.start_state = start_state self.end_state = end_state self.min_alive_neighbours = min_alive_neighbours self.max_alive_neighbours = max_alive_neighbours # execute this rule on a specific cell with their neighbours # this method will set the mark flag in the cell if needed def execute_rule_on(self, cell: Cell, neighbours: [Cell]): # check if we have the needed start_state if cell.alive != self.start_state: return # calculate alive neighbours alive_neighbours = 0 for neighbour in neighbours: if neighbour.alive: alive_neighbours += 1 # check the rules if alive_neighbours < self.min_alive_neighbours: return if self.max_alive_neighbours and alive_neighbours > self.max_alive_neighbours: return # mark the cell if it needed a changement if cell.alive != self.end_state: cell.mark()
830fc1f3f3a19d7bc6c18d2eeb2879b613cc6de0
Madhava-mng/li5tgen
/bin/lib/edit.py
2,444
3.578125
4
#!/bin/env python3 from itertools import product from lib.core import Element def Replace(str_, list_): return str_.replace(list_[0],list_[1]) def Crop(str_, list_): front = int(list_[0] or 0) back = int(list_[1] or 0) return str_[front:len(str_)-back] def Join(str_, list_): front = list_[0] or "" back = list_[1] or "" return front+str_+back def main_edit(file_, argvs): try: buff = open(file_, "r") flist_ = buff.readlines() NEW_FILE = "editedlist.txt" with open(NEW_FILE,"w") as buff2: for f in flist_: f = Replace(f, ["\n",""]) for i in range(len(argvs)): if argvs[i] in ("-r","--replace"): try: if not argvs[i+1].startswith("-"): f = Replace(f, argvs[i+1].split(",")) except: print(Element["ERROR"]["REPLACE"]) return 1 elif argvs[i] in ("-c", "--crop"): try: if not argvs[i+1].startswith("-"): f = Crop(f, argvs[i+1].split(",")) except: print(Element["ERROR"]["CROP"]) return 1 elif argvs[i] in ("-j", "--join"): try: if not argvs[i+1].startswith("-"): f = Join(f, argvs[i+1].split(",")) except: print(Element["ERROR"]["JOIN"]) return 1 buff2.write(f+"\n") buff2.close() for i in range(len(argvs)): if argvs[i] in ("-C", "--caps"): buff2_list=[] with open(NEW_FILE, "r") as buff2: for i in buff2.readlines(): buff2_list.append(Replace(i,["\n",""])) buff2.close() with open(NEW_FILE, "w") as buff2: for f in buff2_list: for l in sorted(map(''.join, product(*((c.upper(), c.lower()) for c in str(f))))): buff2.write(l+"\n") buff2.close() except: print(Element["ERROR"]["FILE"],Element["EDITHELP"]);exit() return 0
e77f8089b4c089c3710990adbe6662f243940d2b
vothin/code
/代码/day2-1/A.IfDemo1.py
679
4.03125
4
""" if单分支选择语句 if(条件表达式): 选择体 一条或者多条语句 条件表达式:结果为boolean类型的表达式。 表达式可以为常量、变量、比较运算、逻辑运算 当条件表达式结果为true时,选择体中的语句就会执行。 当条件表达式结果为false时,选择体中的语句不会执行。 Python中没有switch条件分支语句 """ number = int(input('请输入你的年纪:')) if number > 18: # 广东省 print("你已经成年了.....") # 深圳市 print("你可以工作了") print("你可以赚钱了") print("程序结束......") # 湖南省
b8c6a858e3d066422639939621483912fd057846
aira26/homework4
/1dna.py
394
3.921875
4
with open('rosalind_dna.txt') as input_data: dna = input_data.read() #i opened the file in order to read it ans then i created an empty list, # in order to append it with the result of the counting count = [] for nucleotide in ['A', 'C', 'G', 'T']: count.append(str(dna.count(nucleotide))) print (' '.join(count))
ac45ac853223a56fc459d84357a5a79c91dcc41c
faisalraza33/leetcode
/Python/1567. Maximum Length of Subarray With Positive Product.py
2,427
4.03125
4
# Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive. # A subarray of an array is a consecutive sequence of zero or more values taken out of that array. # Return the maximum length of a subarray with positive product. # # Example 1: # # Input: nums = [1,-2,-3,4] # Output: 4 # Explanation: The array nums already has a positive product of 24. # # Example 2: # # Input: nums = [0,1,-2,-3,-4] # Output: 3 # Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6. # Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive. # # Example 3: # # Input: nums = [-1,-2,-3,0,1] # Output: 2 # Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3]. # # Constraints: # # 1 <= nums.length <= 10^5 # -10^9 <= nums[i] <= 10^9 # 1) Dynamic Programming # https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/819329/Python3GoJava-Dynamic-Programming-O(N)-time-O(1)-space # # Time O(n) # Space O(n) # # pos[i], neg[i] represent longest consecutive numbers ending with nums[i] forming a positive/negative product class Solution: def getMaxLen(self, nums: List[int]) -> int: n = len(nums) pos, neg = [0] * n, [0] * n if nums[0] > 0: pos[0] = 1 if nums[0] < 0: neg[0] = 1 res = pos[0] for i in range(1, n): if nums[i] > 0: pos[i] = 1 + pos[i - 1] neg[i] = 1 + neg[i - 1] if neg[i - 1] > 0 else 0 elif nums[i] < 0: pos[i] = 1 + neg[i - 1] if neg[i - 1] > 0 else 0 neg[i] = 1 + pos[i - 1] res = max(res, pos[i]) return res # 2) Dynamic Programming, similar to 1) # Time O(n) # Space O(1) class Solution: def getMaxLen(self, nums: List[int]) -> int: n = len(nums) pos, neg = 0, 0 if nums[0] > 0: pos = 1 if nums[0] < 0: neg = 1 res = pos for i in range(1, n): if nums[i] > 0: pos = 1 + pos neg = 1 + neg if neg > 0 else 0 elif nums[i] < 0: pos = 1 + neg if neg > 0 else 0 neg = 1 + pos else: pos, neg = 0, 0 res = max(res, pos) return res
a77765a1c7890b5ad2d7699006fa131e51f895c9
millerg09/python_lesson
/ex3.py
1,282
4.5
4
print "I will now count my chickens:" # prints a line of text print "Hens", 25.0 + 30.0 / 6.0 # prints a line of text, and then performs addition and division print "Rooster", 100.0 - 25.0 * 3.0 % 4.0 # prints a line of text, and then performs subtraction, multiplication, and fmod (3 to the power of 4) print "Now I will count the eggs:" # prints a line of text print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0 # performs math: addition, subtraction, more addition, exponent (4 to the 2) subtraction, division, and addition print "Is it true that 3 + 2 < 5 - 7?" # prints a line of text as a question print 3.0 + 2.0 < 5.0 - 7.0 # evaluates an inequality, and resolves to a boolean print "What is 3 + 2?", 3.0 + 2.0 # prints a line of text, and then performs addition print "What is 5 - 7?", 5.0 - 7.0 # prints a line of text, and then performs subtraction print "Oh, that's why it's False." # prints a line of text print "How about some more." # prints a line of text print "Is it greater?", 5.0 > -2.0 # prints a line of text, and then evaluates an inequality print "Is it greater or equal?", 5.0 >= -2.0 # prints a line of text, and then evaluates an inequality print "Is it less or equal", 5.0 <= -2.0 # prints a line of text, and then evaluates an inequality
fb989b24c718f4b468e156647dc688e5d59d4bec
YannThorimbert/Thorpy
/examples/guessthenumber.py
1,725
3.609375
4
#ThorPy minigame tutorial. Guess the number : start menu import thorpy import _mygame as mygame def launch_game(): #launch the game using parameters from varset global varset, e_background game = mygame.MyGame(player_name=varset.get_value("player name"), min_val=varset.get_value("minval"), max_val=varset.get_value("maxval"), trials=varset.get_value("trials")) game.launch_game() game.e_background.unblit() #unblit the game when finished game.e_background.update() e_background.unblit_and_reblit() #reblit the start menu application = thorpy.Application(size=(600, 400), caption="Guess the number") thorpy.set_theme("human") e_title = thorpy.make_text("My Minigame", font_size=20, font_color=(0,0,150)) e_title.center() #center the title on the screen e_title.set_topleft((None, 10)) #set the y-coord at 10 e_play = thorpy.make_button("Play!", func=launch_game) #launch the game varset = thorpy.VarSet() #here we will declare options that user can set varset.add("trials", value=5, text="Trials:", limits=(1, 20)) varset.add("minval", value=0, text="Min value:", limits=(0, 100)) varset.add("maxval", value=100, text="Max value:", limits=(0, 100)) varset.add("player name", value="Jack", text="Player name:") e_options = thorpy.ParamSetterLauncher.make([varset], "Options", "Options") e_quit = thorpy.make_button("Quit", func=thorpy.functions.quit_menu_func) e_background = thorpy.Background(color=(200, 200, 255), elements=[e_title, e_play, e_options, e_quit]) thorpy.store(e_background, [e_play, e_options, e_quit]) menu = thorpy.Menu(e_background) menu.play() application.quit()
ff77b522589127dd2a137675011129461910635a
chriswolfdesign/MIT600
/psets/pset4/Problem2/ps4b.py
1,107
3.78125
4
# Problem Set 4 # Chris Wolf # 2:00 # # Problem 2 # def nestEggVariable(salary, save, growthRates): savings = [] years = len(growthRates) for year in range(0, years): if year == 0: savings.append(salary * save * 0.01) else: savings.append(savings[year - 1] * (1 + 0.01 * growthRates[year]) \ + salary * save * 0.01) return savings """ - salary: the amount of money you make each year. - save: the percent of your salary to save in the investment account each year (an integer between 0 and 100). - growthRate: a list of the annual percent increases in your investment account (integers between 0 and 100). - return: a list of your retirement account value at the end of each year. """ def testNestEggVariable(): salary = 10000 save = 10 growthRates = [3, 4, 5, 0, 3] savingsRecord = nestEggVariable(salary, save, growthRates) print(savingsRecord) # Output should have values close to: # [1000.0, 2040.0, 3142.0, 4142.0, 5266.2600000000002] testNestEggVariable()
2e7de9540157e06fe9f90a14b034b615ae4b0673
vvvm23/ADS_Algorithms
/binary_search.py
403
3.828125
4
def search(L, x, left=-1, right=-1): if left == -1 or right == -1: left = 0 right = len(L) - 1 if right == left and L[left] != x: print(x, "does is not in the inputted list!") return -1 p = (left + right) // 2 if L[p] == x: return p if x > L[p]: return search(L, x, p + 1, right) else: return search(L, x, left, p - 1)