blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
cfd3292829a5f7458c5c44229d9046c6addea805
vineeta786/hackerank_solutions_python
/Strings/Capitalize!.py
395
3.671875
4
import math import os import random import re import sys # Complete the solve function below. def solve(s): l = s.split(" ") width = len(l) for i in range(width): if(l[i].isalpha()): cap = list(l[i]) cap[0] = cap[0].upper() l[i] = "".join(cap) cap.clear() res = " ".join(l) return res if __name__ == '__main__':
780e81524394afbf859287e768a87d8ab385d44b
aquibjamal/hackerrank_solutions
/validating_phone_nums.py
315
3.625
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Sep 12 02:39:52 2019 @author: aquib """ # Enter your code here. Read input from STDIN. Print output to STDOUT import re n=int(input()) for _ in range(n): if re.match(r'[789]\d{9}$', input()): print('YES') else: print('NO')
38ac8c311b2c1334c50a7768cd79eee1921af74a
vishalbelsare/rPSMF
/pypsmf/psmf/learning_rate.py
615
3.765625
4
# -*- coding: utf-8 -*- import abc class BaseLearningRate(metaclass=abc.ABCMeta): @abc.abstractmethod def get(self, t): """ Get the learning rate for time t """ class ConstantLearningRate(BaseLearningRate): def __init__(self, lr): self.lr = lr def get(self, t): return self.lr class ExponentialLearningRate(BaseLearningRate): def __init__(self, lr_start, lr_end, steps): self.lr_start = lr_start self.lr_end = lr_end self.steps = steps def get(self, t): return self.lr_start * pow(self.lr_end / self.lr_start, t / self.steps)
6b13ab4fcc119127d28e22cc544897ee8c60e358
shiratsu/face_trim
/numpytest.py
396
3.625
4
# -*- coding: utf-8 -*- import numpy as np def main(): # 2次元配列の宣言・初期化 A = np.array([[1, 2], [3, 4], [5, 6]]) A = np.array([1,2]) # 行列の大きさ print("行列Aの大きさ:", A.shape) print("行列Aの行数:", A.shape[0]) print("行列Aの列数:", A.shape[1]) if __name__ == '__main__': main()
05d577a93177d8212ee42ec99d5412e23e96fe2d
anganesh/PythonLearning
/tutorial_loop_examples.py
799
4.21875
4
# To check whether a given number is even or odd for i in range(2,10): if i%2 == 0: print (i,'even number') else: print (i, 'odd number') # To print fibonaci series n0=1 print n0 n1=1 print n1 val = n0+n1 for i in range(2,10): print val n0=n1 n1=val val = n0+n1 print " another way to print fibonacci using function" def fibn(n): x=0 y=1 while x < n: print x x,y=y,x+y # if we do this step in two lines, we will not get fib series #y= x+y fibn(100) print; print "range function range(3,33,3)" for i in range(3,33,3): print i print "using array, range and len function" a = ['complete' ,'surrender','prerequisite','for','spiritual','journey'] for i in range(len(a)): print(i,a[i])
9c14d2ce7a64346f5c87b086519698b88aca6d28
xdfc1745/baekjoon
/17478.py
901
3.578125
4
def recursion(n, cnt): intent = '____' * cnt print(intent+"\"재귀함수가 뭔가요?\"") if n == 1 : print(intent+"\"재귀함수는 자기 자신을 호출하는 함수라네\"") print(intent+"라고 답변하였지.") return print(intent+"\"잘 들어보게. 옛날옛날 한 산 꼭대기에 이세상 모든 지식을 통달한 선인이 있었어.") print(intent+"마을 사람들은 모두 그 선인에게 수많은 질문을 했고, 모두 지혜롭게 대답해 주었지.") print(intent+"그의 답은 대부분 옳았다고 하네. 그런데 어느 날, 그 선인에게 한 선비가 찾아와서 물었어.\"") cnt += 1 recursion(n-1, cnt) print(intent+"라고 답변하였지.") return num = int(input()) print("어느 한 컴퓨터공학과 학생이 유명한 교수님을 찾아가 물었다.") recursion(num+1, 0)
0f78e5b9ea3a3d06cd68d6448ca0e394a461774c
giordafrancis/adventofcode2019
/day02_alarm.py
2,522
3.984375
4
""" https://adventofcode.com/2019/day/2 """ from typing import List, NamedTuple, Iterator import itertools class Command(NamedTuple): pointer: int opcode: int pos_1: int = None pos_2: int = None pos_final: int = None def instructions(inputs: List[int]) -> Iterator[Command]: """ Splits instructions into Commands based on opcodes 1, 2 & 99 """ length = len(inputs) for i in range(0, length, 4): opcode = inputs[i] if opcode == 99: yield Command(pointer=i, opcode=opcode) else: yield Command(pointer=i, opcode=opcode, pos_1=inputs[i + 1] , pos_2=inputs[i + 2], pos_final=inputs[i + 3]) TEST_INPUT = [1,9,10,3,2,3,11,0,99,30,40,50] def intcode(inputs: List[int], noun:int=0, verb:int=0) -> int: """ Return value at position 0 once opcode 99 is found. """ inputs = inputs.copy() # required for part 2 inputs[1] = noun # as defined in the problem noun & verb inputs inputs[2] = verb commands = instructions(inputs) for command in commands: if command.opcode == 99: return inputs[0] elif command.opcode == 1: inputs[command.pos_final] = inputs[command.pos_1] + inputs[command.pos_2] elif command.opcode == 2: inputs[command.pos_final] = inputs[command.pos_1] * inputs[command.pos_2] else: raise RuntimeError(f"invalid opcode {command.opcode}") assert intcode(TEST_INPUT, noun=TEST_INPUT[1], verb=TEST_INPUT[2]) == 3500 def problem_prep(problem_input: str) -> List[int]: inputs = [int(num) for num in problem_input.split(",")] return inputs # PART 2 def inputs_brute_force(inputs: List[int]) -> int: """ finds the input pairs between 0 - 99 inclusive that produce an output of 19690720 """ input_pairs = itertools.permutations(range(0,100), 2) # pairs between 0 and 99 inclusive while True: noun, verb = next(input_pairs) if intcode(inputs, noun=noun, verb=verb) == 19690720: return 100 * noun + verb break if __name__ == "__main__": with open("day02_inputs.txt") as file: problem_input = file.read() inputs = problem_prep(problem_input) part_1 = intcode(inputs, noun=12, verb=2) part_2 = inputs_brute_force(inputs) print("PART 1 halt code pos 0->", part_1) print("PART 2 value based on input pairs is->", part_2)
b7757a06f89cacb51cb96eba0c685b4cf31a9b4a
jdobner/grok-code
/find_smallest_sub2.py
1,537
4.21875
4
def find_substring(str, pattern): """ Given a string and a pattern, find the smallest substring in the given string which has all the characters of the given pattern. :param str: :param pattern: :return: str >>> find_substring("aabdec", 'abc') 'abdec' >>> find_substring("abdbca", 'abc') 'bca' >>> find_substring('adcad','abc') '' """ freq_map = dict.fromkeys(pattern, 0) found_indexes = None window_start = 0 chars_found = 0 for window_end in range(len(str)): nextChar = str[window_end] if nextChar in freq_map: if nextChar in freq_map: freq = freq_map[nextChar] + 1 freq_map[nextChar] = freq if freq == 1: chars_found += 1 while chars_found == len(freq_map): charToRemove = str[window_start] if charToRemove in freq_map: newFreq = freq_map[charToRemove] - 1 freq_map[charToRemove] = newFreq if newFreq == 0: chars_found -= 1 newLen = window_end - window_start + 1 if not found_indexes or found_indexes[0] > newLen: found_indexes = (newLen, window_start, window_end + 1) window_start += 1 if found_indexes: return str[found_indexes[1]:found_indexes[2]] else: return "" if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
6fd13c22a04c044832d1c6622237bded799931cd
mupotsal/Programming_Practice_IGIT
/Lab2.py
2,282
3.59375
4
import random from datetime import datetime def mergesort(A): n = len(A) if n > 1: mid = n // 2 B = A[0:n // 2] C = A[n // 2:n] mergesort(B) mergesort(C) merge(B, C, A) def merge(B, C, A): bIndex = cIndex = 0 m1 = len(B) m2 = len(C) n = len(A) i = 0 while (bIndex < m1) and (cIndex < m2): small = B[bIndex] if C[cIndex] < small: small = C[cIndex] cIndex += 1 else: bIndex += 1 A[i] = small i += 1 while bIndex < m1: A[i] = B[bIndex] bIndex += 1 i += 1 while cIndex < m2: A[i] = C[cIndex] cIndex += 1 i += 1 def quicksort(A): n = len(A) A.append(1E30) quicksortAux(A, 0, n - 1) del A[n] def quicksortAux(A, l, r): if l < r: s = partition(A, l, r) quicksortAux(A, l, s - 1) quicksortAux(A, s + 1, r) def partition(A, l, r): p = A[l] i = l j = r + 1 stillLooping = True while stillLooping: sL = True while sL: i = i + 1 if A[i] >= p: sL = False sL = True while sL: j = j - 1 if A[j] <= p: sL = False A[i], A[j] = A[j], A[i] if i >= j: stillLooping = False A[i], A[j] = A[j], A[i] A[l], A[j] = A[j], A[l] return j def rand_func(): store_arr=[] ran = random.Random() n = ran.randint(1000,5000) for i in range(n): value = ran.randint(0,400) store_arr.append(value) return store_arr def main(): outfile = open("data.txt","w") for i in range(100): A=rand_func() n=len(A) Aoriginal = A[0:n] before=datetime.now() mergesort(A) after=datetime.now() elapsed=after-before ms_microseconds=elapsed.total_seconds()*(10**6) A=Aoriginal[0:n] before = datetime.now() quicksort(A) after=datetime.now() elapsed=after-before qs_microseconds = elapsed.total_seconds() * (10 ** 6) outfile.write(str(n)+"\t"+str(ms_microseconds)+"\t"+str(qs_microseconds)+"\n") print(str(n)+"\t"+str(ms_microseconds)+"\t"+str(qs_microseconds)) main()
9af12851de2d3e0ef8ea0181fa1a627fef74bee7
MrinaliniTh/Algorithms
/Interview_question/find_second_largest.py
596
3.96875
4
import heapq def find_second_largest(nums): largest = 0 second_largest = 0 for num in nums: if num > largest: second_largest = largest largest = num elif num > second_largest: second_largest = num return second_largest, largest def find_using_heapq(nums, k): val = nums[0:k] heapq.heapify(val) for i in range(k, len(nums)): if nums[i] > val[0]: heapq.heapreplace(val, nums[i]) return val[0] # print(find_second_largest([3,5,18,25,20,7,1])) print(find_using_heapq([3,5,18,25,20,7,1], 2))
7c3bdfed299500306f053fab3d9b0d7f68eba598
k3vzz/Coursera_Python
/week5_1.py
400
3.984375
4
count = 0 total = 0 avg = None while True: try: inp = raw_input('Enter a number: ') if inp == 'done': break if len(inp) < 1 : break num = float(inp) count = count + 1 total = total + num avg = total / count except: print 'Invalid input' continue print 'Count = ',count print 'Total = ',total print 'Average = ',avg
05d40ca989c3349ade58bb07af4e849ea275f27b
845318843/20190323learnPython
/withKid/代码清单5-end.py
1,058
4.03125
4
# test items # anser = input("key a num,please!") # print(type(anser)) # key in 12, will be stored as string form # num = float(input()) # using float() can solve it # print(num) # try items # item1 # firstname = "ke" # lastname = "zj" # print(firstname+lastname) # item2 # firstname = input("hi,key your firstname") # lastname = input("then, key your lastname") # print("well i get it: ", firstname+lastname) # item3 # border1 = float(input("how is the length?")) # border2 = float(input("then, how is the width?")) # totals = border1 * border2 # # print("well i get it: ", totals, "pieces are enough!") # item4 # border1 = float(input("how is the length?")) # border2 = float(input("then, how is the width?")) # price = float(input("well, how much is a piece?")) # totals = border1 * border2 * price # # print("well it will cost: ", totals, "!") # item5 # num_5 = int(input("how many 5fen do you have?")) # num_2 = int(input("how many 2fen do you have?")) # num_1 = int(input("how many 1fen do you have?")) # print(num_5 * 5 + num_2 * 2 + num_1, "fen")
6af6cb9c5b143d49f1ff1497eeb69a2a7fbeeba9
JJJOHNSON22/Python-fundamentals
/functions_intermediate1.py
560
3.671875
4
import random def randInt(max_num=0, min_num=0): if (min_num==0 and max_num==0): num = int(random.random() * 100) return num elif (min_num!=0 and max_num!=0): num = int(random.random() * (max_num - min_num) + min_num) return num elif (max_num!=0): num = int(random.random() * max_num) return num else: num = int(random.random() * (100 - min_num) + min_num) return num print(randInt()) print(randInt(max_num=50)) print(randInt(min_num=50)) print(randInt(min_num=50, max_num=500))
53bf2ba5463159243732ead589db72ffe603afb4
sashadev-sky/Python-for-Networking
/chapter2/threads/threads_init.py
952
3.96875
4
from threading import Thread from time import sleep num_threads = 4 def thread_message(message): global num_threads num_threads -= 1 print('Message from thread %s\n' % message) while num_threads > 0: print("I am the %s thread" % num_threads) Thread(target=thread_message("I am the %s thread" % num_threads)).start() sleep(0.1) """ chapter2/threads$ p3 threads_init.py I am the 4 thread Message from thread I am the 4 thread I am the 3 thread Message from thread I am the 3 thread I am the 2 thread Message from thread I am the 2 thread I am the 1 thread Message from thread I am the 1 thread """
1312fed483a6a70d4f53b53b761b498b55a82bcc
FabianoJanisch/CursoEmVideo-Python
/Exercício 039.py
428
3.953125
4
from datetime import date ano = int(input("Ano de nascimento: ")) anoatual = date.today().year idade = anoatual - ano jafoi = ano + 18 jafoi2 = anoatual - jafoi aindavai = 18 - idade if idade == 18: print ("Esse ano é o seu alistamento!") if idade > 18: print (f"Já se passou {jafoi2} anos de seu alistamento e foi em {jafoi}") if idade < 18: print (f"Seu alistamento será em {jafoi} e faltam {aindavai} anos")
42f2ef71989736761630fa4080b6b49474e524eb
codelurker/ASCIIShooter
/shapes.py
422
3.765625
4
def draw_circle(at,size): Circle = 0 width=size height=size CenterX=(width/2) CenterY=(height/2) circle = [] for i in range(height): for j in range(width+1): Circle = (((i-CenterY)*(i-CenterY))/((float(height)/2)*(float(height)/2)))+((((j-CenterX)*(j-CenterX))/((float(width)/2)*(float(width)/2)))); if Circle>0 and Circle<1.1: circle.append((at[0]+(j-(width/2)),at[1]+(i-(height/2)))) return circle
82d86b34440c384268f49f27b03477179bfbff4e
marcusvtms/moto_questions
/q5.py
2,057
3.796875
4
#!/usr/bin/env python class node: def __init__(self): self.val = None self.next = None class lk_list: def __init__(self): self.curr_node = None def add_node(self, value): n_node = node() n_node.val = value n_node.next = self.curr_node self.curr_node = n_node def get_head(self): return self.curr_node def get_head_value(self): return self.curr_node.val def get_next_node(self): return self.curr_node.next def is_empty(self): return self.curr_node == None def print_list(self, list_node): if list_node is not None: print(str(list_node.val)+' -'), self.print_list(list_node.next) def remove_duplicate(self, size, duplicates_verif): if size > 1: duplicates_verif.add(self.get_head_value()) self.remove_duplicate_aux(self.get_head(), self.get_next_node(), duplicates_verif) def remove_duplicate_aux(self, previous_node, curr_node, duplicates_veri): if curr_node is not None: if curr_node.val in duplicates_veri: previous_node.next = curr_node.next self.remove_duplicate_aux(previous_node, previous_node.next, duplicates_veri) else: duplicates_veri.add(curr_node.val) self.remove_duplicate_aux(curr_node, curr_node.next, duplicates_veri) def main(): list_numbers = [0, 1, 0, 6, 0, 0, 6, 0, 0, 0, 2, 0, 0, 0, 0] test_list = lk_list() for elmnt in list_numbers: test_list.add_node(elmnt) print('list with possible duplicates') test_list.print_list(test_list.get_head()) print('\nhead value is ') print(test_list.get_head_value()) duplicates = set() test_list.remove_duplicate(len(list_numbers), duplicates) print('list with duplicates removed') test_list.print_list(test_list.get_head()) if __name__ == '__main__': main()
a0ebf828880a2d4b056d808c99794902ac0228af
wisdom2018/pythonLearn
/class.py
422
3.640625
4
#! /usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2020/7/29 9:42 AM # @Author: zhangzhihui.wisdom # @File:class.py class Student(object): def __init__(self, name, score): self.name = name self.score = score def print_score(self): print('%s: %s' % (self.name, self.score)) if __name__ == '__main__': print('class character') tom = Student('Tom', 89) tom.print_score()
84f42f83ca2e2691009a5f47d1e5b81d66521112
liquid-sky/scripts
/collatz.py
928
3.921875
4
#!/usr/bin/python THRESHOLD = 10L ** 6 length_memo = {1: 1} def collatz_length(n): '''Recursively builds a dict of lenghts of Collatz sequences. ''' if n not in length_memo: if n % 2 == 0: length_memo[n] = 1 + collatz_length(n / 2) else: length_memo[n] = 1 + collatz_length(3 * n + 1) return length_memo[n] def longest_sequence(memo): '''Finds longest memoized Collatz length and returns the sequence starting number. ''' max_v = max(memo.values()) keys = [x for x,y in memo.items() if y == max_v] return keys # Generates all Collatz sequence lengths < 10 ** 6 for i in range(1, THRESHOLD): collatz_length(i) starting_nums = longest_sequence(length_memo) for the_number in starting_nums: print "The number under %d that produces the longest chain is %s.\ Chain length is %d." % (THRESHOLD, the_number, length_memo[the_number])
a90ed40f60edcfa686e000cabe790d22bcdeab18
syurskyi/Python_Topics
/020_sequences/examples/ITVDN Python Essential 2016/20-comparing_sequences.py
664
3.90625
4
""" Последовательности одинаковых типов можно сравнивать. Сравнения происходят в лексикографическом порядке: последовательность меньшей длины меньше, чем последовательность большей длины, если же их длины равны, то результат сравнения равен результату сравнения первых отличающихся элементов. """ print('abc' < 'ab') print('abc' < 'abcd') words = ['lorem', 'ipsum', 'dolor', 'sit', 'amet'] print(sorted(words))
0b767a90585b8aa99191ff03ad9f0516808240b6
nckturner/practice
/cookies/sorted.py
155
3.875
4
d= [{ "a": 1, "b": 3, "c": "FIRST"}, { "a": 2, "b": 2, "c": "SECOND"}, { "a": 3, "b": 1, "c": "THIRD"}] print(d) print(sorted(d, key=lambda x: x["b"]))
7738a512670afe1612e0d49ce51ea5d0901809d8
akinovak/music_visualisation
/musical-genres.py
6,615
3.640625
4
""" Cilj rada je da se sto pribliznije moguce vizualizuju slicnosti (odnosno razlike) muzickih zanrova, koriscenjem genetskog algoritma. Podaci korisceni u radu preuzeti su sa: https://www.researchgate.net/figure/Relations-between-liking-for-musical-genres-in-the-N332-participants-screened-for-the_fig1_330110820 """ import random import numpy import math import pandas as pd import matplotlib.transforms as mtransforms import matplotlib.pyplot as plot import warnings warnings.filterwarnings("ignore") class Chromosome: def __init__(self, gene, fitness): self.gene = gene self.fitness = fitness def __str__(self): return "{} -> {}".format(self.gene, self.fitness) class GeneticAlgorithm: def __init__(self, matrix): self.matrix = matrix self.generation_size = 5000 self.chromosome_size = len(matrix) self.reproduction_size = 2000 self.max_iterations = 100 self.mutation_rate = 0.2 self.tournament_size = 50 self.selection_type = 'tournament' def calculate_fitness(self, gene): sum_fitness = 0 for i in range(0, len(self.matrix)-1): for j in range(i+1, len(self.matrix)): degree = gene[i] - gene[j] sum_fitness = sum_fitness + (self.matrix[i][j] - math.cos(degree*math.pi/180))**2 return sum_fitness def initial_population(self): init_population = [] for i in range(self.generation_size): gene = [] for j in range(self.chromosome_size): selected_value = random.randint(0,360) gene.append(selected_value) fitness = self.calculate_fitness(gene) new_chromosome = Chromosome(gene, fitness) init_population.append(new_chromosome) return init_population def selection(self, chromosomes): selected = [] for i in range(self.reproduction_size): if self.selection_type == 'roulette': selected.append(self.roulette_selection(chromosomes)) elif self.selection_type == 'tournament': selected.append(self.tournament_selection(chromosomes)) return selected def roulette_selection(self, chromosomes): total_fitness = sum([chromosome.fitness for chromosome in chromosomes]) selected_value = random.randrange(0, int(total_fitness)) current_sum = 0 for i in range(self.generation_size): current_sum += chromosomes[i].fitness if current_sum > selected_value: return chromosomes[i] def tournament_selection(self, chromosomes): selected = random.sample(chromosomes, self.tournament_size) winner = min(selected, key = lambda x: x.fitness) return winner def mutate(self, gene): random_value = random.random() if random_value < self.mutation_rate: random_index = random.randrange(self.chromosome_size) while True: new_value = random.randint(0, 360) if gene[random_index] != new_value: break gene[random_index] = new_value return gene def create_generation(self, chromosomes): generation = [] generation_size = 0 while generation_size < self.generation_size: [parent1, parent2] = random.sample(chromosomes, 2) child1_code, child2_code = self.crossover(parent1, parent2) child1_code = self.mutate(child1_code) child2_code = self.mutate(child2_code) child1 = Chromosome(child1_code, self.calculate_fitness(child1_code)) child2 = Chromosome(child2_code, self.calculate_fitness(child2_code)) generation.append(child1) generation.append(child2) generation_size += 2 return generation def crossover(self, parent1, parent2): break_point = random.randrange(1, self.chromosome_size) child1 = parent1.gene[:break_point] + parent2.gene[break_point:] child2 = parent2.gene[:break_point] + parent1.gene[break_point:] return (child1, child2) def optimize(self): best_result = 10000 population = self.initial_population() br = 0 for i in range(0, self.max_iterations): selected = self.selection(population) population = self.create_generation(selected) global_best_chromosome = min(population, key=lambda x: x.fitness) if global_best_chromosome.fitness < best_result: best_result = global_best_chromosome.fitness br = 0 print("{} -> {}".format(i, best_result)) else: br += 1 print(i) if br == 10: break if global_best_chromosome.fitness < 10: break return global_best_chromosome def main(): matrix = pd.read_csv("musical-genres.csv", sep = ",", header=None) matrix = numpy.array(matrix) genetic_algorithm = GeneticAlgorithm(matrix) result = genetic_algorithm.optimize() print('Result: {}'.format(result)) radian = numpy.zeros(len(result.gene)) radius = 1 labels = ["Metal", "Blues", "Classical", "Contemporary", "Electro", "Folk", "Jazz", "Pop", "Rap", "Religious", "Rock", "Soul", "Variety", "World"] for i in range(0, len(labels)): labels[i] = labels[i] + ' ' + str(result.gene[i]) fig = plot.figure() fig.set_size_inches(18.5, 10.5, forward=True) fig.canvas.set_window_title('Visual representation of correlation between music genres') plot.clf() plot.title('Music genres') ax = fig.add_subplot(111, projection='polar') ax.set_yticklabels([]) ax.set_theta_zero_location('W') ax.set_theta_direction(-1) ax.grid(False) for r in range(0, len(result.gene)): radian[r] = result.gene[r]*math.pi/180 for i in range(0, len(radian)): plot.polar((0,radian[i]), (0,radius), label = labels[i], zorder = 3) ax.legend(loc = 'upper center', bbox_to_anchor = (1.45, 0.8), shadow = True, ncol = 1) plot.show() if __name__ == "__main__": main()
65d2d463767cb856379bed83e3987b6896446551
mrparkonline/ics4u_solutions
/09-28-2020/tuple.py
1,637
4.5
4
# Question related to Tuple Slide Deck # Q1) Create a list of tuples containing (a,b,c). Where b = a^2 and c = a^3. Let a be integers of 2 to user_input upper limit upper_limit = 30 result = [(a, a**2, a**3) for a in range(1,upper_limit)] print(result) # Q2) Create a deck of cards using tuples. Creating a function to shuffle it as well. suits = ('Spade', 'Heart', 'Club', 'Diamond') numeric_values = tuple(range(2,11)) letter_values = ('Jack', 'Queen', 'King', 'Ace') value = numeric_values + letter_values deck = [(suit, num) for suit in suits for num in value] print(deck) print(len(deck)) def shuffler(seq): ''' from random import shuffle shuffle(seq) ''' from random import choice seq_copy = seq.copy() result = [] while seq_copy: # while our list is not empty current = choice(seq_copy) result.append(current) seq_copy.remove(current) return result print(shuffler(deck)) # Q3) Create a function that converts a string into a list of tuples. A single tuple holds two values: the character and the number of occurance. Sort the list. def charCount(word): ''' charCount returns the occurance of each character from word argument -- word : string return -- list ''' result = [] tracker_string = '' for c in word: # let c be character if c not in tracker_string: tracker_string += c result.append((word.count(c), c)) result.sort() return result # end of charCount print(charCount('hello goodbye'))
81ea55e1c158529c9af4e2bc7df81648320f81ba
qorjiwon/LevelUp-Algorithm
/LeetCode/Leet_0024.py
1,111
3.671875
4
""" @ LeetCode 0024. Swap Nodes in Pairs @ Prob. https://leetcode.com/problems/swap-nodes-in-pairs/ Ref. @ Algo: LinkedList @ Start day: 20. 10. 05. @ End day: 20. 10. 05. """ class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def swapPairs(self, head: ListNode) -> ListNode: if head == None: return head currentNode = head while currentNode and currentNode.next: currentNode.val, currentNode.next.val = currentNode.next.val, currentNode.val nextNode = currentNode.next if nextNode.next == None: break currentNode = nextNode.next return head if __name__ == "__main__": node4 = ListNode(4, None) node3 = ListNode(3, node4) node2 = ListNode(2, node3) node1 = ListNode(1, node2) solution = Solution() swapHead = solution.swapPairs(node1) while swapHead != None: print(swapHead.val, end=" ") swapHead = swapHead.next
fde2b33c370e40e49c1bb33e82f7797c772aded6
stufit/pycharm_test
/numpy예제/소스코드_예제/ch06/ex06-4.py
459
3.734375
4
#!/usr/bin/env python # coding: utf-8 # # 6.4 데이터형 객체의 개념 # In[1]: #p117 def func(x): x = 5 print('x(함수):', x) x = 3 func(x) print('x(메인):', x) # In[2]: #p118 def swap(aa, bb): print('2: id(aa)', id(aa), 'id(bb)', id(bb)) return bb, aa a=3 b=5 print('a=', a, 'b=', b) print('1: id(a)', id(a), 'idb(b)', id(b)) a, b = swap(a, b) print('3: id(ab)', id(a), 'id(b)', id(b)) print('a=', a, 'b=', b) # In[ ]:
6874077a6cedea9a6b2d5a1f49a43431ba349f81
theksenia/hm7
/2.py
164
3.78125
4
a= int(input("Enter: ")) def fido(x): if x == 0: return 0 elif x == 1: return 1 else: return fido(x-1)+ fido(x-2) print(fido(a))
d0aed2b088e4d174f150970a19ec683c3633a1bb
duanwandao/PythonBaseExercise
/Day11(面向对象3)/Test07.py
1,417
4.375
4
""" 方法重写: 1.什么叫方法重写?如何重写? 前提: 继承关系,父类中存在某个方法,子类中将该方法重写实现一遍 overrides 2.重写有什么好处? 可以为父类中方法补充新的东西 3.什么情况下需要重写? 父类中的方法,不能满足需求的时候,可以使用重写 4.重写的时候注意事项: 1.方法名 方法名必须一致 2.参数 参数可以不同 3.返回值 与返回值无关 """ class Animal(object): def __init__(self,color): self.color = color def eat(self): print("吃") def shout(self): print("动物都会叫") class Dog(Animal): def __init__(self,name,age,color): # 如果使用super的话,子类中只能使用父类继承的color super().__init__(color) #父类中有一个color,子类中重写写了一个color # self.color = color self.name = name self.age = age def eat(self): print("吃除了吃肉还吃骨头") def shout(self,a,c): #调用父类的方法 super().shout() # super(Dog, self).shout()s print("汪汪汪~") return 123 dog = Dog('Big Yellow',3,'Yellow') dog.eat() dog.shout(1,2) print(dog.color) an = Animal('Black') print(an.color) print(dog.color)
1ced777666dbd99c44aa407f7b30524fe14320c0
liuhanyu200/pygame
/7/7-5.py
362
3.625
4
# coding:utf-8 promote = "\nHow old are you?" promote += "\n Enter quit to quit." active = True while active: age = input(promote) if age == 'quit': active = False continue if age != 'quit': age = int(age) if age < 3: print("free") if 3 < age < 12: print("$10") if age >= 12: print("$15")
01dc5136feb0d573fdfdddf26730ae7782ea8b79
dima-panchenko/Python
/week-2/5.Ход короля.py
512
3.90625
4
x1 = int(input()) y1 = int(input()) x2 = int(input()) y2 = int(input()) if x2 == x1 and (y2 - y1 == 1 or y1 - y2 == 1): print("YES") elif y2 == y1 and (x2 - x1 == 1 or x1 - x2 == 1): print("YES") elif (x2 - x1 == 1 and y2 - y1 == 1) or (x1 - x2 == 1 and y1 - y2 == 1): print("YES") elif (x2 - x1 == 1 and y1 - y2 == 1) or (x2 - x1 == 1 and y2 - y1 == 1): print("YES") elif (x1 - x2 == 1 and y1 - y2 == 1) or (x1 - x2 == 1 and y2 - y1 == 1): print("YES") else: print("NO")
2eb17b1e47e94d09b4da2557c13d4a170466f3f2
Jeff2076/YOUTUBE
/youtube.py
1,131
3.828125
4
import time print("Do you want to start? (y,n)") start = input(">>>") if start == "y" or start == "Y": while True: time.sleep(1) print("[1] World Youtuber") print("[2] Asian Youtuber") print("[3] Europian Youtuber") print("[4] African Youtuber") print("[5] Others") 대륙 = input(">>>") if 대륙 == "1" or 대륙 == "[1]" or 대륙 == "World Youtuber": print("[1] Pewdiepie") print("[2] T-Series") world = input(">>>") if world == 1: print("Felix Arvid Ulf Kjellberg (/ˈʃɛlbɜːrɡ/ SHEL-burg,Swedish: [ˈfěːlɪks ˈǎrːvɪd ɵlf ˈɕɛ̂lːbærj] (About this soundlisten);[c] born 24 October 1989), better known as PewDiePie (/ˈpjuːdiːpaɪ/ PEW-dee-py), is a Swedish YouTuber, comedian, and philanthropist, known primarily for his Let's Play videos and comedic formatted shows.") print("Go to subscribe! https://www.youtube.com/user/PewDiePie") print("Want go back? (y,n)") h = input(">>>") if world == 2: print("Go to subscribe! https://www.youtube.com/user/tseries") print("Want go back? (y,n)") h = input(">>>")
19049a97aa13aaa967d6ef8d5b09411c47620151
sharathoddiraju/firstcode
/Helloworld.py
437
4
4
def helloworld(myString): print(myString) myName = input("what is your name?") myVar = input("Enter a number: ") myVar2 = input("Enter another number :") if((myName == "santosh" and myVar == "0") or myVar2 == "5"): print("santosh is great") elif(myName == "raghu"): print("you are cool") else: print("No one is good") helloworld("This is first set of calling code") helloworld("This is second set of calling code")
22afefa9f19c238ea51b9f154ce412decf573157
NitinJRepo/Python
/Dictionary/1-dictionary.py
717
4.4375
4
# Creating an empty Dictionary Dict = {} print("Empty Dictionary: ") print(Dict) # Creating a Dictionary # with Integer Keys Dict = {1: 'Nitin', 2: 'Nilesh', 3: 'Nitesh'} print("\nDictionary with the use of Integer Keys: ") print(Dict) # Creating a Dictionary # with Mixed keys Dict = {'Name': 'Nitin', 1: [1, 2, 3, 4]} print("\nDictionary with the use of Mixed Keys: ") print(Dict) # Creating a Dictionary # with dict() method Dict = dict({1: 'book1', 2: 'book2', 3:'book3'}) print("\nDictionary with the use of dict(): ") print(Dict) # Creating a Dictionary # with each item as a Pair Dict = dict([(1, 'C++'), (2, 'Python')]) print("\nDictionary with each item as a pair: ") print(Dict)
e189db84272034517f80f883b8402af3e03cb6a4
bochenekk/codebrainers
/Pycharm-Projects/oop/day1/example2.py
154
3.84375
4
list = tuple a = [1,2,3,4,5] print(tuple(a)) print(list(a)) # dlaczego?? a = (1,2,3) b = [1,2,3] print(list(a)) print(b) print(list(b)) print(tuple(b))
3083442c2f53ee9288e12658e430c57b3c07c5b9
soumyajitray/Learning-Python
/Leet - Pascal's Triangle II.py
606
3.640625
4
import math class solution(object): # def combination(self,n, r): # return int((math.factorial(n)) / ((math.factorial(r)) * math.factorial(n - r))) def pascals_trianglecombined(self, rows): # result = [] # for count in range(rows): # row = [] row = [] for element in range(rows + 1): combination = int( (math.factorial(rows)) / ((math.factorial(element)) * math.factorial(rows - element))) row.append(combination) print(row) return row obj = solution() obj.pascals_trianglecombined(5)
552bf152dc2e7a7d1ea31ae793c22e3ba4f0a5b4
acejang1994/SoftwareDesign
/hw2/compare.py
218
3.765625
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 30 13:03:38 2014 @author: james """ def compare(x ,y): if x > y: return 1 if x == y: return 0 if x < y: return -1 print compare(4,6)
96cfbf1b793c5cd256dec3ddec70df5168c5e04e
Kuranio/Ejercicios-sencillos-en-Python
/Suma.py
124
3.796875
4
numero1 = int(input("Primer numero: ")) numero2 = int(input("Segundo numero: ")) numero3 = numero1 + numero2 print(numero3)
ae954512e5f67cdaaa7ae362128b1c6b15faba3f
qeedquan/challenges
/codeforces/749A-bachgold-problem.py
1,013
4.0625
4
#!/usr/bin/env python """ Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1. Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k. Input The only line of the input contains a single integer n (2 ≤ n ≤ 100 000). Output The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them. Examples input 5 output 2 2 3 input 6 output 3 2 2 2 """ def decompose(n): o = n % 2 n = n//2 - o p = [2] * n if o != 0: p.append(3) return p def main(): assert(decompose(5) == [2, 3]) assert(decompose(6) == [2, 2, 2]) main()
ced8513b0af26a36817ee35d4bc80e6b184dca16
JUNGEEYOU/python-algorithm
/6/1.py
397
3.8125
4
""" 선택 정렬 """ def selection_sort(a): """ 선택 정렬 함수 :param a: 리스트 :return: """ for i in range(len(a)): min_index = i for j in range(i+1, len(a)): if a[min_index] > a[j]: min_index = j a[min_index], a[i] = a[i], a[min_index] print(a) array = [7, 5, 9, 0, 1, 6, 2, 4, 8] selection_sort(array)
4aa9041c3a305efc16b73a687f01a59849f47718
stacygo/2021-01_UCD-SCinDAE-EXS
/06_Writing-Functions-in-Python/06_ex_4-12.py
851
3.5625
4
# Exercise 4-12: Check the return type def returns_dict(func): # Complete the returns_dict() decorator def wrapper(*args, **kwargs): result = func(*args, **kwargs) assert (type(result) == dict) return result return wrapper @returns_dict def foo(value): return value try: print(foo([1, 2, 3])) except AssertionError: print('foo() did not return a dict!') def returns(return_type): # Complete the returns() decorator def decorator(func): def wrapper(*args, **kwargs): result = func(*args, **kwargs) assert (type(result) == return_type) return result return wrapper return decorator @returns(dict) def foo(value): return value try: print(foo([1, 2, 3])) except AssertionError: print('foo() did not return a dict!')
cf694893b29f721e0b381c4fc7b896e8e225ab19
zantiago29/bicycle_industry
/bicycles.py
2,180
4.1875
4
class Bicycle(object): def __init__(self, model_name, weight, cost): self.model_name = model_name self.weight = weight self.cost = cost class BikeShop(object): def __init__ (self, shop_name, bicycle_inventory = {}, bicycle_markup = 0.0): self.shop_name = shop_name self.bicycle_inventory = bicycle_inventory self.bicycle_markup = bicycle_markup self.profit_balance = 0 #calculate sale price for bicycle" def bicycle_sales_price(self, bicycle): return int(bicycle.cost + round(bicycle.cost * self.bicycle_markup,0)) #Print inventory of bicycles with an optional price limit #I would like to go over this function and understand the flow of parameters def print_inventory(self, sale_price_limit = 9999): print ("Name Count Sales Price") for bicycle in self.bicycle_inventory: bicycle_sale_price = self.bicycle_sales_price(bicycle) if bicycle_sale_price < sale_price_limit: print("{} {} ${}".format(bicycle.model_name, self.bicycle_inventory[bicycle], bicycle_sale_price)) #Sell bicycle def sell_bicycle(self, bicycle): if self.bicycle_inventory[bicycle] > 0: bicycle_profit = self.bicycle_sales_price(bicycle) - bicycle.cost self.profit_balance += bicycle_profit self.bicycle_inventory[bicycle] -= 1 print ("{} has successfully sold a {} for ${}.".format(self.shop_name, bicycle.model_name,bicycle_profit)) class Customer(object): def __init__ (self, customer_name, bicycle_fund, bicycle = None): self.customer_name = customer_name self.bicycle_fund = bicycle_fund self.bicycle = bicycle #Customer purchases bicycle and reduces bicycle fund def purchase_bicycle(self, bicycle, bicycle_cost): self.bicycle = bicycle self.bicycle_fund -= bicycle_cost print ("Congratulations {}, you have purchased a {} for ${}. You have ${} remaining of your bicycle fund".format(self.customer_name, bicycle.model_name, bicycle.cost, self.bicycle_fund))
df03b8d58b4cb0991c4bd75b41c1effb64a02bf6
dresenhista/python_thehardway
/check_list.py
1,581
4.09375
4
#Version3.0 #Changes: # -> perfect square works now # -> prime list uses less memory # -> list doesn't need to be sorted to use remove duplicates # -> refactoring the code to make it more pythonic #check if the number in a list is pair or even def check_parity(x): for i in x: if i%2==0: # if the rest of the division is 0 then it's pair print "%r is pair" %i else: print "%r is even" %i #check if the number is prime def prime_numbers(l): for x in l: divisor = x-1 multiple = [1, x] # every number is divided by 1 and itself while divisor >1: if x % divisor == 0: #if the number divides by any other multiple.append(divisor) divisor = divisor-1 break else: divisor = divisor-1 if multiple==[1,x]: print "Number %r is prime" %x else: print "Number %r is not prime because it also divides by %r" %(x, multiple[2]) return multiple #removing duplicates in a list def removing_duplicates(x): x.sort() lenght = len(x) newlist = [] i=0 while i<lenght: item = x[i] #hold the first item newlist.append(item) j=i+1 while j<lenght: next_item = x[j] # loop around the list +1 if item==next_item: i=i+1 # if it repeats than skip the next one j=j+1 i=i+1 print newlist return newlist #check if the number is a perfect square def perfect_square(x): impar = 0 status = "Number %r is not perfect square." %x for i in range(1,x,2): impar += i if impar == x: status= "Number %r is a perfect square." %x print status
de2cbd2d97567e6a2ad80e4d4b9279c5e26f924d
rownak-glitch/coding-test-
/task3.py
1,136
4
4
import click courses= {'0':['English grammar','John Smith '], '1': ['Mathematics','Lara Gilbert'], # used dictionary data structure '2': ['Physics','Johanna Kabir'], '3': ['Chemistry','Daniel Robertson'], '4': ['Biology','Larry Copper']} day=0 hour=0 co=0 routine ={co: [day,hour]} @click.group() def main(): pass @main.command() def C(): """List courses with teachers Name""" for sub, teac in courses.values(): print(sub,',',teac) @main.command() def A(): """Create Routine""" for sub,teac in courses.values(): print(sub) global day global hour global co day= click.prompt("Enter Day") hour=click.prompt("Enter Hour") co=click.prompt("Enter course") day= '{}'. format(day) hour='{}'. format(hour) co='{}'. format(co) print(day) print(hour) print(co) @main.command() def B(): """ Show Routine""" global routine routine ={co: [day,hour]} print (routine) if __name__=='__main__': main()
9d1d5795f9004784ed358b7e5d0a25439e801fc1
manoel-alves/Exercicios_Python
/Curso_em_Video-Exercicios/ex065.py
473
3.96875
4
soma = cont = 0 inercia = 'S' while inercia != 'N': x = float(input('Digite um número: ')) if cont == 0: maior = x menor = x elif x > maior: maior = x elif x < menor: menor = x soma += x cont += 1 inercia = str(input('Quer continuar [S/N]? ')).strip().upper() media = soma / cont print(f'Você digitou {cont} números e a média foi {media:.2f}') print(f'O maior valor foi {maior:.0f} e o menor foi {menor:.0f}')
d99d8d3462d55c39056bed829c471b58061a64b8
KristinCovert/Bootcamp
/PythonProjects/test.py
4,737
4.03125
4
__author__ = 'Kristin' import random import time import re from nltk.tokenize import RegexpTokenizer #Welcome to translator & choice of how to put in text to translate def ca_speak_method(): print """\nOh my god, you are like, totally awesome 'cause you want to be more californian.\n""" time.sleep(2.5) print """So Dude, to fully talk like a true Californian you must, like, embrace your inner slang mojo.\n""" time.sleep(5) choice = input("""\nSo how you gonna pour your mojo out? We'll help by translating your words into california-ness! Oh yeah, bro! \n\tYou can totally 1: write your own story or 2: follow some prompts to make a story? 1 or 2 dude? """) return make_story(choice) #text input, two methods def make_story(choice): if choice == 1: text = raw_input("""\nCool Dude! Then tell us your story! We need, like, 5 - 10 sentences. And go ahead, use that CA slang you already know! We might add a function to assess your california-ness!\n""") return text if choice == 2: question1 = raw_input('''\nYou are at the beach. What does it look like? \nThe beach is ''') question2 = raw_input('''\nThere are some hotty surfers riding waves. Describe them to us. I see ''') question3 = raw_input('''\nYou are now taking a walk on the beach. Describe your walk and what you see. As I ''') question4 = raw_input('''\nThere is dead jelly fish on the sand as you walk. Describe the carcass or how you feel. I stumble on ''') question5 = raw_input('''\nWrap up your day and tell us what you do.''') text = str(" The beach is " + question1 + ' I see' + question2 + " As I " + question3 + ' I stumble on' + question4 + question5) return text #class cookie cutter to turn the story into a translated text class CASpeakTranslate(): def __init__(self, story): self.story = story locations = [] text_split = [] joined_text = None translated_story = None #take story and split it into a list but don't undo contractions using NLTK def deconstruct_text(self): self.text_split = RegexpTokenizer("[\w']+|[.,!?;:-]") self.text_split = (self.text_split.tokenize(self.story)) return self.text_split #replace words with slang from dictionary (expand to reading big excel file) def replace_word_slang(self): slang_dict = {'really': ['hella', 'totally', 'fully'], 'gross': ['grody', 'gag me']} for word in self.text_split: for slang in slang_dict: if word == slang: #print (word, random.choice(slang_dict[slang])) slang_choice = random.choice(slang_dict[slang]) self.text_split[self.text_split.index(word)] = slang_choice return self.text_split #create random locations to replace with add-in words def random_location(self): count = 0 while count < 5: location = random.randint(1, len(self.text_split)) self.locations.append(location) count += 1 return self.locations #use locations made above to insert add-ins def random_add(self): add_ins = ['so,', 'like,', 'OMG,'] for location in self.locations: add = random.choice(add_ins) self.text_split.insert(location, add) return self.text_split #add in Dude after each ! def add_in_dude(self): for element in self.text_split: if element == '!': self.text_split.insert(self.text_split.index(element), ', Dude!') self.text_split.remove('!') return self.text_split #join the text def join_text(self): self.joined_text = ' '.join(self.text_split) return self.joined_text #fix the punctuation def fix_punct(self): fix_1 = re.sub(r"(\s+\.)", ".", self.joined_text) fix_2 = re.sub(r"(\s+!)", "!", fix_1) fix_3 = re.sub(r"(\s+,)", ",", fix_2) fix_4 = re.sub(r"(\s+\?)", "?", fix_3) fix_5 = re.sub(r"(\s+,.)", ".", fix_4) fix_6 = re.sub(r"(\s+,,)", ",", fix_5) self.translated_story = re.sub(r"(\s+:)", ";", fix_6) return self.translated_story story = ca_speak_method() ca_speak = CASpeakTranslate(story) ca_speak.deconstruct_text() ca_speak.replace_word_slang() ca_speak.random_location() ca_speak.random_add() ca_speak.add_in_dude() ca_speak.join_text() ca_speak.fix_punct() print ca_speak.translated_story #TODO compare stories 1 vs 2 after play again to see change in CAness # # #file_open = open(pronouns.txt) # # #slang_dict.keys creates list of keys # def CA_score(): # score = 0 # if word in slang_dict.keys(): # score +=1 # return score # # #insdethe class have an attribute that is the score - that a method writes too # # #replacing words with slang but randomly replacing when there are multiple # # #slang words that mean the same thing # # # #compare files - are you getting any better? # #def compare(story1, story2): # # """ # # :param story1: # # :param story2: # # :return: returns similarity of two stories # # # # def play_again(): # # response = raw_input( """ # # Do you want to play again? # # Y or N: """).upper() # # if response == 'Y': # # play() # # else: # # print '\nSee you later Dude!'
b4c747feae3ca65e76b8071d12d8d8a08bddd4ad
guruc-134/Py_programs
/File_Dictionary.py
534
3.609375
4
"""file_name=input("enter the file name") fh=open(file_name) emails=dict() for line in fh: if line.startswith("From") : if not line.startswith("From:"): words=line.split() emails[words[5][:2]]=emails.get(words[5][:2],0)+1 print(emails) print() print(emails.items()) lst=sorted(emails.items()) print(lst) tmp=list() for k,v in lst: print(k,v) tup=(v,k) tmp.append(tup) newlist=sorted(tmp,reverse=False) print(newlist) for v,k in newlist: print(k,v) """ tup=tuple() print(dir(tup))
40ab4926d52be1e6f9ba2bb9e7c655d421e3967c
SudherrSingidi/Learnings
/python/rps.py
5,092
4.0625
4
# from itertools import count # input_1 = input("Enter option for user1: ") # input_1 = input_1.lower() # if input_1 != "scissors" or input_1 != "rock" or input_1 != "paper": # for i in count(): # print("Dear user1,your input is invalid.please enter valid input") # input_2 = input("Enter option for user1: ") # if input_1 == "scissors" or input_1 == "rock" or input_1 == "paper": # break # elif input_1 == "scissors" or input_1 == "rock" or input_1 == "paper": # input_2 = input("Enter option for user2: ") # input_2 = input_2.lower() # if input_2 != "scissors" or input_2 != "rock" or input_2 != "paper": # for y in count(): # print("Dear user2,your input is invalid.please enter valid input") # input_2 = input("Enter option for user2: ") # if input_2 == "scissors" or input_2 == "rock" or input_2 == "paper": # break # else: # if (input_1 == "scissors" and input_2 == "paper") or (input_1 == "paper" and input_2 == "rock") or (input_1 == "rock" and input_2 == "scissors"): # print("User 1 wins!") # else: # print("user 2 wins") import getpass print("Welcome to:\n....Rock....\n.....Paper.....\n......Scissors......\nYou are about to play") while True: try: number_of_games = int(input("How many times you would like to play RPS in this game: ")) if number_of_games <= 0: raise ValueError except ValueError: print("I did not understand that.Please enter a valid number which is greater than 0") continue else: break choice = ' ' user_1 = 0 user_2 = 0 while choice != 'Y' or choice != 'N': choice = input(f"You chose to play RPS {number_of_games} times.Would you like to continue (y/n) ").upper() if choice == 'Y' or choice == 'N': break if choice != 'Y' or choice != 'N': print("I did not understand that.Please enter a valid option") while choice == 'Y': print("Game starts now. Good luck!!!") for r in range(number_of_games): input_1 = getpass.getpass("Enter option for user1: ") input_1 = input_1.lower() # check for valid input from user1 if input_1 != "scissors" and input_1 != "rock" and input_1 != "paper": # If input is invalid,ask user input until the input is valid while input_1 != "scissors" or input_1 != "rock" or input_1 != "paper": print("Dear user1,your input is invalid.please enter valid input") input_1 = getpass.getpass("Enter option for user1: ") if input_1 == "scissors" or input_1 == "rock" or input_1 == "paper": break input_2 = getpass.getpass("Enter option for user2: ") input_2 = input_2.lower() # check for valid input from user2 if input_2 != "scissors" and input_2 != "rock" and input_2 != "paper": # If input is invalid,ask user input until the input is valid while input_2 != "scissors" or input_2 != "rock" or input_2 != "paper": print("Dear user2,your input is invalid.please enter valid input") input_2 = getpass.getpass("Enter option for user2: ") if input_2 == "scissors" or input_2 == "rock" or input_2 == "paper": break # check the winner if (input_1 == "scissors" and input_2 == "paper") or (input_1 == "paper" and input_2 == "rock") or (input_1 == "rock" and input_2 == "scissors"): print("User 1 wins!") user_1 += 1 elif (input_2 == "scissors" and input_1 == "paper") or (input_2 == "paper" and input_1 == "rock") or (input_2 == "rock" and input_1 == "scissors"): print("user 2 wins") user_2 += 1 else: print("Tied") if user_2 > user_1: print(f"User 2 won {user_2} times.So, User 2 wins") elif user_2 < user_1: print(f"User 1 won {user_1} times.So, User 1 wins") elif user_1 == user_2: print("It's a tie") choice = ' ' while choice != 'Y' or choice != 'N': choice = input("Would you like to play another game? (y/n) ").upper() if choice == 'Y' or choice == 'N': break if choice != 'Y' or choice != 'N': print("I did not understand that.Please enter a valid option") if choice == 'Y': while True: try: number_of_games = int(input("How many times you would like to play RPS in this game: ")) except ValueError: print("I did not understand that.Please enter a valid number") continue else: break if number_of_games >= 0: print(f"You chose to play RPS {number_of_games} times") user_1 = 0 user_2 = 0 print("See you next time!.") # from random import * # computer = randint(0,2) # computer = int(computer) # if computer == 0: # computer = "scissors" # elif computer == 1: # computer = "paper" # else: # computer = "rock" # input_2 = input("Enter option for user2: ") # if (computer == "scissors" and input_2 == "paper") or (computer == "paper" and input_2 == "rock") or (computer == "rock" and input_2 == "scissors"): # print("computer wins!") # print("computer options is " + computer) # elif (input_2 == "scissors" and computer == "paper") or (input_2 == "paper" and computer == "rock") or (input_2 == "rock" and computer == "scissors"): # print("user 2 wins") # print("computer options is " + computer) # else: # print("Tied") # print("computer options is " + computer) # print("user2 option is " + input_2)
bef6ab5427693cf403f193728060b74296195b1e
Tim-Sotirhos/statistics-exercises
/probability_distributions.py
6,035
4.4375
4
# Probability Distribution import numpy as np import math from scipy import stats import matplotlib.pyplot as plt import pandas as pd # 1.) A bank found that the average number of cars waiting during the noon hour at a drive-up window follows a Poisson distribution with a mean of 2 cars. # Make a chart of this distribution and answer these questions concerning the probability of cars waiting at the drive-up window. def cars_at_bank_at_noon(): x = range(8) y = stats.poisson(2).pmf(x) plt.figure(figsize=(9, 6)) plt.bar(x, y, edgecolor='black', color='white', width=1) plt.xticks(x) plt.ylabel('P(X = x)') plt.xlabel('Average cars at drive_up window') print(cars_at_bank_at_noon()) # 1.a) What is the probability that no cars drive up in the noon hour? stats.poisson(2).pmf(0) (stats.poisson(2).rvs(10000) == 0).mean() # 1.b) What is the probability that 3 or more cars come through the drive through? stats.poisson(2).sf(2) (stats.poisson(2).rvs(10000) >= 3).mean() # 1.c) How likely is it that the drive through gets at least 1 car? stats.poisson(2).sf(0) (stats.poisson(2).rvs(10000) > 0).mean() # 2.) Grades of State University graduates are normally distributed with a mean of 3.0 and a standard deviation of .3. Calculate the following: # 2.a) What grade point average is required to be in the top 5% of the graduating class? gpa = np.random.normal(3, .3, (10000)) stats.norm(3, .3).isf(.05) np.percentile(gpa, 95) # 2.b) What GPA constitutes the bottom 15% of the class? stats.norm(3, .3).ppf(.15) np.percentile(gpa, 15) # 2.c) An eccentric alumnus left scholarship money for students in the third decile from the bottom of their class. # Determine the range of the third decile. Would a student with a 2.8 grade point average qualify for this scholarship? stats.norm(3, .3).ppf([.2,.3]) # Or stats.norm(3, .3).ppf(.3) stats.norm(3, .3).ppf(.2) np.percentile(gpa, [20, 30]) # 2.d) If I have a GPA of 3.5, what percentile am I in? 1 - stats.norm(3, .3).sf(3.5) # Or stats.norm(3, .3).cdf(3.5) (gpa <= 3.5).mean() # 3.) A marketing website has an average click-through rate of 2%. # One day they observe 4326 visitors and 97 click-throughs. # How likely is it that this many people or more click through? stats.binom(4326, .02).sf(96) ((np.random.random((10000, 4326)) <= .02).sum(axis=1) >= 97).mean() # 4.) You are working on some statistics homework consisting of 100 questions where all of the answers are a probability rounded to the hundreths place. # Looking to save time, you put down random probabilities as the answer to each question. # 4.a) What is the probability that at least one of your first 60 answers is correct? stats.binom(60,.01).sf(0) ((np.random.random((10000, 60)) <= .01).sum(axis=1) > 0).mean() # 5.) The codeup staff tends to get upset when the student break area is not cleaned up. # Suppose that there's a 3% chance that any one student cleans the break area when they visit it, and, # on any given day, about 90% of the 3 active cohorts of 22 students visit the break area. # How likely is it that the break area gets cleaned up each day? # How likely is it that it goes two days without getting cleaned up? # All week? n_students = round(.9*66) # cleanded each day stats.binom(n_students, .03).sf(0) # not cleaned two day (stats.binom(n_students, .03).cdf(0))**2 # not cleaned all week (stats.binom(n_students, .03).cdf(0))**5 # 6.) You want to get lunch at La Panaderia, but notice that the line is usually very long at lunchtime. # After several weeks of careful observation, # you notice that the average number of people in line when your lunch break starts is normally distributed with a mean of 15 and standard deviation of 3. # If it takes 2 minutes for each person to order, and 10 minutes from ordering to getting your food, what is the likelihood that you have at least 15 minutes left to eat your food before you have to go back to class? # Assume you have one hour for lunch, and ignore travel time to and from La Panaderia. mean = 15 std= 3 time_to_order = 2 lunch_hour = 60 eat_time = 15 prep_time = 10 people = round((lunch_hour - eat_time - prep_time - time_to_order) // time_to_order) lunch_line = stats.norm(15,3).cdf(people) lunch_line (np.random.normal(15,3, 10000) <= 16).mean() # 7.) Connect to the employees database and find the average salary of current employees, along with the standard deviation. # Model the distribution of employees salaries with a normal distribution and answer the following questions: def get_db_url(user, password, host, database_name): url = f'mysql+pymysql://{user}:{password}@{host}/{database_name}' return url import env from env import host, user, password url = get_db_url(user,password, host, "employees") url # Read the salaries tables into a dataframes salaries_query = "SELECT * FROM salaries WHERE to_date > NOW()" salaries = pd.read_sql(salaries_query, url) (salaries.tail(25)) average_salary = salaries.salary.mean() std_salary = salaries.salary.std() salary_distribution = stats.norm(average_salary, std_salary) # 7.a) What percent of employees earn less than 60,000? percent_under_60k = salary_distribution.cdf(60000) (salaries.salary < 60000).mean() # 7.b) What percent of employees earn more than 95,000? percent_above_95k = salary_distribution.sf(95000) (salaries.salary > 95000).mean() # 7.c) What percent of employees earn between 65,000 and 80,000? percent_above_65k = salary_distribution.cdf(65000) percent_below_80k = salary_distribution.cdf(80000) percent_between_65k_and_80k = percent_below_80k - percent_above_65k ((salaries.salary > 65000) & (salaries.salary < 80000)).mean() # Or using SF percent_above_65k = salary_distribution.sf(65000) percent_below_80k = salary_distribution.sf(80000) percent_between_65k_and_80k = percent_above_65k - percent_below_80k # 7.d) What do the top 5% of employees make? top_five_percent_salary = salary_distribution.isf(.05) salaries.salary.quantile(.95)
15a967200acede557583b34626d7119df92535b8
tommyphan8/verdant-octo-sniffle
/anagram.py
782
3.671875
4
#O(n^2) def anagram(a, b): temp = list(b) posA = 0 contSearch = True while(posA < len(a) and contSearch): posB = 0 found = False while(posB < len(b) and not found): if a[posA] == temp[posB]: found = True else: posB += 1 if found == True: temp[posB] = None posA += 1 else: contSearch = False return contSearch #O(n) def anagram1(a,b): count = dict() count1 = dict() for x in range(len(a)): if a[x] not in count: count[a[x]] = 0 if b[x] not in count1: count1[b[x]] = 0 count[a[x]] += 1 count1[b[x]] += 1 return count == count1 print(anagram("abcd", "bcda"))
bc270afd2f812ba2968201d391c93affd7e366cd
J14032016/LeetCode-Python
/tests/algorithms/p0094_binary_tree_inorder_traversal_2_test.py
432
3.53125
4
import unittest from leetcode.algorithms.p0094_binary_tree_inorder_traversal_2 \ import Solution, TreeNode class TestBinaryTreeInorderTraversal(unittest.TestCase): def test_binary_tree_inorder_traversal(self): solution = Solution() a = TreeNode(1) b = TreeNode(2) c = TreeNode(3) a.right = b b.left = c self.assertListEqual([1, 3, 2], solution.inorderTraversal(a))
ed3f861200d65ef6c2d8d1be419570d193424b59
isaacmthacker/ProjectEuler
/bouncy.py
1,628
4.3125
4
""" Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420. We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349. Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538. Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%. Find the least number for which the proportion of bouncy numbers is exactly 99%. """ def isBouncy(x): if len(x) >= 3: decreasing = True increasing = True same = True for idx in range(1,len(x)): if x[idx-1] > x[idx]: decreasing = False if x[idx-1] < x[idx]: increasing = False if x[idx-1] != x[idx]: same = False if decreasing or increasing or same: #print (decreasing, increasing, same) return False return True else: return False ratio = 0.0 goalRatio = 0.99 bouncy = 0 nonbouncy = 0 curNum = 1 while ratio != goalRatio: if isBouncy(str(curNum)): bouncy += 1 else: nonbouncy += 1 ratio = float(bouncy)/(nonbouncy+bouncy) curNum += 1 print curNum-1
987992775a32a546fb28126c0f101b25f7065ee5
joshuaMarple/phase-vocoder
/app/Duration.py
2,156
3.59375
4
""" Authors: Fernando (UPDATE HIS INFO) License: GPL 3.0 Description: This file contains functions that allows the user to change the pitch of a .wav Comments: None. """ import subprocess import os from sys import platform as _platform from lib import pydub def changeDuration(filename,percent): """ Input: filename , tones filename (string): the path to the soundfile tones (integer): the number of semitones to change(from negative number to positive number) Outputs: pitchoutput.wav Description: This function will change the pitch of a soundfile """ tempochange = "-tempo="+str(percent) if _platform == "linux" or _platform == "linux2": fn = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'soundpitch') elif _platform == "darwin": fn = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'soundpitchmac') elif _platform == "win32": fn = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'soundpitchwin32.exe') subprocess.call([fn,filename, "duroutput.wav","-speech", tempochange]) return "duroutput.wav" def changeGapDuration(filename,gaptime,gapduration,percentage): """ Input: filename , gaptime, gapduration , tones filename (string): the path to the soundfile gaptime (float): the time to begin changing the pitch gapduration (float): the amount of sound to be changed(from the gaptime start to the end of this length) tones (integer): the number of semitones to change(from negative number to positive number) Outputs: processefile.wav Description: This function will change the pitch of a soundfile """ file = pydub.AudioSegment.from_wav(filename) newdurationpart = file[int((gaptime* 1000)) : int(((gaptime+gapduration) * 1000))] first = file[:int(gaptime * 1000)] last = file[int((gaptime+gapduration) * 1000):] newdurationpart.export("durinput.wav", format="wav") changeDuration("durinput.wav",percentage) newdurationpart = pydub.AudioSegment.from_wav("duroutput.wav") newfile = first + newdurationpart + last newfile.export(filename, format="wav") os.remove("durinput.wav") os.remove("duroutput.wav") return newfile
63157fbd4ebf5dc97075e0dfcb7fe981d2dd1114
DamManc/workbook
/chapter_3/83.py
358
3.765625
4
# Maximum Integer import random x_max = 0 count = 0 for i in range(1, 100): x = int(random.random() * 100) print(x, end="") if x > x_max and i != 1: print(" <== Update") count += 1 x_max = x else: print() print("The maximum value found was %d" % x_max) print("The maximum value was updated %d times" % count)
2259d51d59ef95c6dd830e4559909ad2ed3ea5d5
shuangyangqian/python_road
/utils/one_hundred/example17.py
568
3.84375
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # author # email: shuangyang.qian@easystack.cn # irc: qsyqian # def func(my_str): i = 0 j = 0 k = 0 for n in my_str: if n.isalpha(): i += 1 elif n.isdigit(): j += 1 elif n.isspace(): k += 1 return i, j, k my_str = "asfd afhdueiosfr haslmkdfn ;iha gyhiofgtqwehgklajsdnfg klsagh rwiueohfg" string_num, digit_num, space_num = func(my_str) print "字母有 %d 个。" % string_num print "数字有 %d 个。" % digit_num print "空格有 %d 个。" % space_num
5be9b51e708bbeaef1294169c8781b6c9ede7c44
hariprohandler/dataStructurePython
/queue/queue.py
607
3.84375
4
from collections import deque class Queue: def __init__(self): self.buffer = deque() def enqueue(self, data): # self.buffer.insert(0,data) self.buffer.appendleft(data) def dequeue(self): self.buffer.pop() def is_empty(self): return len(self.buffer) == 0 def size(self): return len(self.buffer) q = Queue() q.enqueue({ 'company': 'ABC', 'timestamp': '15 Apr, 11.01 AM', 'price': 131.10 }) q.enqueue({ 'company': 'DEF', 'timestamp': '15 Apr, 11.02 AM', 'price': 133.10 }) print(q.buffer) q.dequeue() print(q.buffer)
8472aca7a5a65ed83cc485258a50006575da9edd
karanbuddy500/Python-Basic-course-soluions-coursera
/gradedWeek4(4)_1.py
188
3.625
4
# For each character in the string saved in ael, append that character to a list that should be saved in a variable app. ael = "python!" lst = [] for i in ael: lst.append(i) app = lst
f0d67a0970d19fec8106712b90828f23ea54fa2c
yosef8234/test
/hackerrank/python/introduction/loops.py
771
3.984375
4
# -*- coding: utf-8 -*- # Loops are control structures that iterate over a range to perform a certain task. # There are two kinds of loops in Python. # A for loop: # for i in range(0,5): # print i # And a while loop: # i = 0 # while i < 5: # print i # i+=1 # Here, the term range(0,5) returns a list of integers from 00 to 55: [0,1,2,3,4][0,1,2,3,4]. # Task # Read an integer NN. For all non-negative integers i<Ni<N, print i2i2. See the sample for details. # Input Format # The first and only line contains the integer, NN. # Constraints # 1≤N≤201≤N≤20 # Output Format # Print NN lines, one corresponding to each ii. # Sample Input # 5 # Sample Output # 0 # 1 # 4 # 9 # 16 n = int(raw_input()) for x in xrange(n): if x < n: print x*x
0a88f7f5a7a7f96d4f307388b28cad1257634816
khatuu/gwccompilation
/lc.py
947
4.21875
4
#imports the ability to get a random number (we will learn more about this later!) from random import * #Create the list of words you want to choose from. aList = ["Hamburger", "Hot Dog", "Salad", "Chicken", "Fish", "Soup", "Pancakes", "Spaghetti", "Pizza"] dList = ["Ice Cream", "Brownies", "Cookies", "Mochi Ice Cream", "Strawberry Shortcake", "Pie", "Shaved Ice", "Soft Serve"] fList = ["Apple", "Banana", "Mango", "Grapes", "Watermelon", "Pineapple", "Strawberry", "Pear"] #Generates a random integer. response = input("Would you like to eat today? (Y/N)") while response != "N" : if response == "Y" : aRandomIndex = randint(0, len(aList)-1) dRI = randint(0, len(dList)-1) fLI = randint(0, len(fList)-1) print("{}, {}, {}.".format(aList[aRandomIndex], dList[dRI], fList[fLI])) else : print("{} is an invalid input.".format(response)) response = input("Would you like to eat today? (Y/N)")
bc9cd9c915ae480520b142e7850bb0d1aa2a6477
shamoldas/pythonBasic
/while_loop.py
116
4.03125
4
a=int(input("enter a number.\n")) b=int(input("input a number.\n")) while a<=b: print(a,end=' ') a=a+1
a0626a9d3ee955fd89292b166ad61136c5f3f738
pangguoping/python-study
/day4/写博客.py
3,658
3.8125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- ''' with open('aa','r',encoding='utf-8') as f1: for line in f1: line_strip = line.strip() print(line_strip,bool(line_strip)) s = "print(123)" ''' """ '''例1:接收字符串,先把字符串转换为python代码,然后再执行该代码''' s = "print(123)" exec(s) '''例2:接收到的是代码,直接执行该代码''' s = "print(123)" r = compile(s,"<string>","exec") exec(r) '''例3:没有返回值,即没有结果。只能返回None''' s = "print(123)" r = compile(s,"<string>","exec") k = exec(r) print(k) '''例1:将字符串s转换为代码,并执行s的表达式''' s = "8*8" ret = eval(s) print(ret) print(dir(list)) """ """ '''例1:获取divmod()的值''' r = divmod(98,10) #生成的是元组类型 print(r,type(r)) print(r[0]) print(r[1]) '''例2:获取n1,n2的值''' n1,n2 = divmod(98,10) print(n1) print(n2) """ """ '''例1:获取列表大于22的元素,平时做法''' def f1(args): result_list = [] for item in args: if item > 22: result_list.append(item) return result_list list1 = [11,22,33,44,55] r = f1(list1) print(r) """ """ '''例2:使用filter函数实现''' def f2(a): if a > 22: return True li = [11,22,33,44,55] ret = filter(f2,li) print(list(ret)) """ """ '''例3:使用filter函数与lambda''' list1 = [11,22,33,44,55] ret = filter(lambda a:a>22,list1) print(list(ret)) """ """ '''例1:for循环实现''' list1 = [11,22,33,44,55] def f1(arg): result_list = [] for item in arg: result_list.append(item +100) return result_list t = f1(list1) print(t) '''例2:使用map函数实现''' ''' ''' list1 = [11,22,33,44,55] def f2(a): return a + 100 result = map(f2,list1) print(list(result)) '''例3:map函数与lambda''' list1 = [11,22,33,44,55] result = map(lambda a: a+100,list1) print(list(result)) """ """ li = [11,22,33,44,55] result = map(lambda a: a + 200,li) print(list(result)) r = filter(lambda a: a + 200,li) print(list(r)) #filter :函数返回True,将元素添加 #map # 将函数返回元素添加到结果中 '''例1:计算字符串长度''' s = "abcd" k = len(s) print(k) '''例2:计算汉字长度''' s = "北京" k = len(s) print(k) '''例3:按照字节计算汉字长度''' s = "北京" b = bytes(s,encoding='utf-8',) print(len(b)) '''例4:计算列表长度''' list1 = [11,22,33,44,55] print(len(list1)) '''例5:计算字典长度''' dict1 = {"key1":"value1","key2":"value2","key3":"value3"} print(len(dict1)) """ """ '''例1:判断字符串对象是否为str的实例,是返回True,否则返回False''' s = "beijing" r = isinstance(s,str) print(r) '''例2:判断是字符串对象是否为list类的实例,是返回True,否则返回False''' s = "beijing" r = isinstance(s,list) print(r) """ """ li = [11,22,33,44] def f1(arg): arg.append(55) li = f1(li) print(li) """ """ '''例1:把下面的3个列表中的beijing is China输出''' list1 = ["beijing",11,22,33] list2 = ["is",11,22,33] list3 = ["China",11,22,33] r = zip(list1,list2,list3) #print(list(r)) li = list(r) temp = li[0] print(temp) k = " ".join(temp) print(k) list1 = ["beijing",11,22,33] list2 = ["is",11,22,33] list3 = ["China",11,22,33] r = zip(list1,list2,list3) print(list(r)) """ ''' s = "8*8" r = compile(s,"<string>","exec") k = exec(r) #print(k) ''' '''例1''' def foo(): print('foo') foo #表示是函数 foo() #表示执行函数 '''例2:''' def foo(): print('foo') foo = lambda x=1: x+1 foo() #执行下面的lambda表达式,而不再是原来的foo函数,因为函数foo被重新定义
c0b203b9f9944f42c0304fa013e1d3e0e6b9658e
rohithn/tic-tac-toe
/src/game/game.py
2,081
4.3125
4
from abc import abstractmethod from game.board import Board class Game(object): """Base class for the Tic-Tac-Toe game.""" def __init__(self, board: Board): self.board = board @abstractmethod def start(self): """Main class that should be initialized.""" pass def play(self, players): """Starts the game play logic. The play loops for both players until a win or draw state is reached.""" player_1, player_2 = self.get_players(players) print(self.board) while True: """Player 1's turn""" print(player_1.name + "'s turn") """P1 - Get Move""" move_location_1, move_value_1 = player_1.get_move(self.board) """P1 - Perform Move, Value""" self.board.perform_move(move_location_1, move_value_1) print(self.board) """Check Board for Win/Draw""" if self.check_board_state_done(player_1): break """Player 2's turn""" print(player_2.name + "'s turn") """P2 - Get Move, Value""" move_location_2, move_value_2 = player_2.get_move(self.board) """P2 - Perform Move""" self.board.perform_move(move_location_2, move_value_2) print(self.board) """Check Board for Win/Draw""" if self.check_board_state_done(player_2): break def check_board_state_done(self, player) -> bool: """Check Board for Win/Draw""" if self.board.has_winning_pattern: print(player.name + ' wins!') return True if len(list(self.board.possible_moves)) == 0: print('Draw!') return True return False @staticmethod def get_players(players): """"Get first and second players""" first = second = None for player in players: if player.is_first: first = player else: second = player return first, second
3beca9839907a5408d950a538fc1b0637bfa60e2
jinzhe-mu/muwj_python_hm
/01_python基础/introduce_变量命名规则.py
1,964
3.953125
4
""" 变量的命名 目标 标识符和关键字 变量的命名规则 0.1 标识符和关键字 1.1 标识符 标示符就是程序员定义的 变量名、函数名 名字 需要有 见名知义 的效果,见下图: 001_中国山东找蓝翔 标示符可以由 字母、下划线 和 数字 组成 不能以数字开头 不能与关键字重名 思考:下面的标示符哪些是正确的,哪些不正确为什么? fromNo12 from#12 my_Boolean my-Boolean Obj2 2ndObj myInt My_tExt _test test!32 haha(da)tt jack_rose jack&rose GUI G.U.I 1.2 关键字 关键字 就是在 Python 内部已经使用的标识符 关键字 具有特殊的功能和含义 开发者 不允许定义和关键字相同的名字的标示符 通过以下命令可以查看 Python 中的关键字 In [1]: import keyword In [2]: print(keyword.kwlist) 提示:关键字的学习及使用,会在后面的课程中不断介绍 import 关键字 可以导入一个 “工具包” 在 Python 中不同的工具包,提供有不同的工具 02. 变量的命名规则 命名规则 可以被视为一种 惯例,并无绝对与强制 目的是为了 增加代码的识别和可读性 注意 Python 中的 标识符 是 区分大小写的 002_标识符区分大小写 在定义变量时,为了保证代码格式,= 的左右应该各保留一个空格 在 Python 中,如果 变量名 需要由 二个 或 多个单词 组成时,可以按照以下方式命名 每个单词都使用小写字母 单词与单词之间使用 _下划线 连接 例如:first_name、last_name、qq_number、qq_password 驼峰命名法 当 变量名 是由二个或多个单词组成时,还可以利用驼峰命名法来命名 小驼峰式命名法 第一个单词以小写字母开始,后续单词的首字母大写 例如:firstName、lastName 大驼峰式命名法 每一个单词的首字母都采用大写字母 例如:FirstName、LastName、CamelCase 003_驼峰命名法 """
5e7b6da54584cf4801292fc8888363a0e99be121
baxtiyor-gis/python-exe
/main.py
1,988
3.5625
4
from tkinter import * from tkinter import ttk # Create window object app = Tk() app.title("Noemnkaltura xisoblash") app.geometry("800x300") def show(): k = float(kenglik.get()) u = float(uzoqlik.get()) m = masshtab.get() if m == "1:1000 000": print("1:1000000") title = Label(app, text="Siz kiritgan ma`lumotlar", font=("bold", 16), pady=10, padx=10) title.grid(row=0, column=4) k_label = Label(app, text=f"Kenglik: {k}", font=("bold", 14), pady=10, padx=10) k_label.grid(row=1, column=3) y_label = Label(app, text=f"Uzqolik {u}", font=("bold", 14), pady=10, padx=10) y_label.grid(row=2, column=3) # Header app_title = Label(app, text="Koordinatalarni kiriting", font=("bold", 16), pady=10, padx=10) app_title.grid(row=0, column=0) # Kenglik label kenglik_label = Label(app, text="Kenglik", font=("bold", 14), padx=10, pady=5) kenglik_label.grid(row=1, column=0, sticky=W) # Kenglik label kenglik = StringVar() kenglik_form = Entry(app, textvariable=kenglik) kenglik_form.grid(row=1, column=1, sticky=W) # Uzoqlik label uzoqlik_label = Label(app, text="Uzqolik", font=("bold", 14), padx=10, pady=5) uzoqlik_label.grid(row=2, column=0, sticky=W) # Uzoqlik label uzoqlik = StringVar() uzoqlik_form = Entry(app, textvariable=uzoqlik) uzoqlik_form.grid(row=2, column=1, sticky=W) # Select masshtab = StringVar() masshtab_label = Label(app, text="Masshtab tanlang", font=("bold", 14), padx=10, pady=5) masshtab_label.grid(row=3, column=0, sticky=W) # Masshtab select form masshtab_form = ttk.Combobox(app, width=17, textvariable=masshtab) masshtab_form.grid(row=3, column=1, sticky=W) masshtab_form['values'] = ["1:1000 000", "1:500 000", "1:300 000"] masshtab_form.current(0) # form button = Button(app, text="Xisoblash", command=show, padx=5, pady=5, width=15) button.grid(row=4, column=1) # Start programm app.mainloop()
7f93119aa2a0aa197766d48fa5ddfee8814dadec
0x0400/LeetCode
/p53.py
511
3.625
4
# https://leetcode.com/problems/maximum-subarray/ from typing import List class Solution: def maxSubArray(self, nums: List[int]) -> int: maxNum = nums[0] curNum = None for n in nums: if curNum is None: maxNum = max(n, maxNum) if n > 0: curNum = n continue curNum += n maxNum = max(curNum, maxNum) if curNum <= 0: curNum = None return maxNum
9e88b11c27ad53dbd5929bd00f05d18d3a54c6e2
YWFANK/guess
/guess.py
723
3.96875
4
import random lower_bnd = input('Enter an integer as a lower bound: ') upper_bnd = input('Enter an integer as a upper bound: ') lower_bnd = int(lower_bnd) upper_bnd = int(upper_bnd) r = random.randint(lower_bnd, upper_bnd) try_number = 0 while True: print('Enter an integer btw ',lower_bnd,' and ', upper_bnd, ': ') guess = input() guess = int(guess) if guess > r: print('the number is smaller than what you guessed, pls try again.') try_number = try_number + 1 elif guess < r: print('the number is larger than what you guessed, pls try again.') try_number = try_number + 1 else: print('congradulation! The number is ', r) try_number = try_number + 1 print('you tried ', try_number, 'times') break
07ecd9e877922991f9ec8f7be33e6a349edfdfea
Ahmed-Mosharafa/Algorithms-problems-and-training
/modified_kapreker_numbers.py
334
3.578125
4
import math x = int(raw_input()) y = int(raw_input()) answer = "" for i in xrange(x,y+1): ind = "1" squared = i**2 ind += "0" * int(math.ceil(len(str(squared))/2.0)) if (squared%int(ind) + squared/int(ind)) == i: answer += str(i) + " " if answer != "": print answer.strip() else: print "INVALID RANGE"
50c8cefcff8f2afa86b862309ca1a7ea1f3d3e8f
asen-krasimirov/Python-Advanced-Course
/5. Functions Advanced/5.2 Exerceses/Problem 11- Age Assignment.py
319
3.78125
4
def age_assignment(*names, **age_data): ages_by_name = {} for name in names: first_letter = name[0] ages_by_name[name] = age_data[first_letter] return ages_by_name # print(age_assignment("Peter", "George", G=26, P=19)) # print(age_assignment("Amy", "Bill", "Willy", W=36, A=22, B=61))
775c160329e3c6c96aec87bf285fc2d53fe32212
dhruv-rajput/data-structures-and-algo
/random/topdownFibonacci.py
266
3.796875
4
def fib(n, lookup): if n == 0 or n == 1 : lookup[n] = n if lookup[n] is None: lookup[n] = fib(n-1 , lookup) + fib(n-2 , lookup) return lookup[n] n = 9 lookup = [None]*(101) print ("Fibonacci Number is ", fib(n, lookup))
dcd4679882db1fa852c33a5e28255d75864b91f8
Herophillix/cp1404practicals
/prac_05/word_occurences.py
720
4.25
4
""" Count the number of repeated words in a text """ def main(): """Ask the user to input a text, and count the number of repeated words""" count_of_words = {} text = input("Input text: ") for word in text.split(): word = word.lower() if word in count_of_words: count_of_words[word] += 1 else: count_of_words[word] = 1 longest_char_count = 0 for key in count_of_words.keys(): longest_char_count = longest_char_count if longest_char_count > len(key) else len(key) for key in sorted(count_of_words.keys()): print("{0:<{l}}: {1}".format(key, count_of_words[key], l=longest_char_count)) if __name__ == "__main__": main()
e3c21101f139079d4ff885b2e743c9ed33fd3c6f
priyaliverma/python-examples
/is_palindrome.py
847
3.859375
4
a = "pkafbj1483u40ue" # print a.isalnum() # given_string = "Madam I'm Adam" # given_string = given_string.lower() # print given_string # given_string = ''.join(x for x in given_string if x.isalpha()) # print given_string # print given_string[len(given_string)/2] def is_palindrome(given_string): given_string = ''.join(x for x in given_string if x.isalnum()).lower() i = 0 j = len(given_string)-1 palindrome = True while i < j: forward_given_string = given_string[i] print ("forward_given_string", forward_given_string) backward_given_string = given_string[j] print ("backward_given_string", backward_given_string) i += 1 j -= 1 if forward_given_string != backward_given_string: palindrome = False return palindrome result = is_palindrome("Madam I'm Adam") print result
bac7566231977709308df24888c9d6a6ca465bac
prabal1997/Cracking-The-Coding-Interview-Python
/arrays_and_strings/1_1_a.py
816
3.765625
4
import sys input_string = "art"; #ALGORITHM EXPLANATION: we go through each letter, put it into hashmap. If collision occurs, then repetitione existed. #NOTE 1: this runs in O(n) time, assuming the hash-table provides an average rutime of O(1) #NOTE 2: If you were to use the 'try'-'except' approach, know that the runtime would become O(n) because the hashtable would search for the object EVERYWHERE. hashmap, sum_val= {}, 0; expected_sum = len(input_string)*(len(input_string)+1)//2; for index, letter in enumerate(input_string): hashmap[letter] = index+1; for element in hashmap: sum_val += hashmap[element]; #note that the sum HAS to be strictly greater than the expected sum if repetition occurs if (sum_val != expected_sum): print("REPEATITION EXISTS"); else: print("UNIQUE STRING");
2e6aff6ce794ce43cfe47d6fd9d59cadc226a3e5
shahlaaminaei/python-learning
/ex - advance6.py
365
3.671875
4
word_list = {} num = int(input()) while num > 0 : num -= 1 words=input().split() word_list[words[1].strip()]=words[0].strip() word_list[words[2].strip()]=words[0].strip() word_list[words[3].strip()]=words[0].strip() sentence = input().split() result="" for word in sentence: result+=" "+word_list.get(word,word) print(result.strip())
77d8fc8ad7faa260c9f9cfc6785295f782c715ea
murawskikrzysiek/kurs_python
/notes_4_lokaty.py
2,107
3.859375
4
import time def trigger(f): def g(self, *args, **kwargs): while self.do_trigger: time.sleep(0.1) f(self, *args, **kwargs) return g class DepositAccount: def __init__(self, name, investment): self.name = name self.amount_of_money = 1000 self.investment_strategy = investment def charge_interest(self): interest = self.investment_strategy.calculate_interest(self.amount_of_money) self.amount_of_money += interest class InterestCalculator: def __init__(self, DepositAccount): self.do_trigger = True self.day_counter = 0 self.deposit_account = DepositAccount @trigger def charge_interest(self): self.day_counter += 1 if self.day_counter >= 100: self.do_trigger = False self.deposit_account.charge_interest() class Investment: def calculate_interest(self, amount_of_money): if 0 < amount_of_money <= 1200: algorithm = algorithm_1 elif 1200 < amount_of_money <= 1600: algorithm = algorithm_2 else: algorithm = algorithm_3 interest = algorithm(amount_of_money) return interest def algorithm_1(amount_of_money): percentage = 0.005 print("For amount: {} and percentage: {} the interest is: {}".format( amount_of_money, percentage, percentage * amount_of_money )) return percentage * amount_of_money def algorithm_2(amount_of_money): percentage = 0.007 print("For amount: {} and percentage: {} the interest is: {}".format( amount_of_money, percentage, percentage * amount_of_money )) return percentage * amount_of_money def algorithm_3(amount_of_money): percentage = 0.01 print("For amount: {} and percentage: {} the interest is: {}".format( amount_of_money, percentage, percentage * amount_of_money )) return percentage * amount_of_money if __name__ == '__main__': inv = Investment() d = DepositAccount("Andrzej", inv) a = InterestCalculator(d) a.charge_interest()
c0e9a88eb60a9e0f54d0f0313147a2ef2355c5f8
statistics-exercises/t-tests-10
/main.py
1,275
3.78125
4
import matplotlib.pyplot as plt import numpy as np def sample_variance( data ) : # Your code to compute the sample variance goes here def common_variance( data1, data2 ) : # Your code to compute the common variance using the formula in the # description on the left goes here # This code generates the graph -- you should not need to modify from here onwards xvals, total_var, common_var = np.zeros(10), np.zeros(10), np.zeros(10) for i in range(10) : # This line generates 100 samples from two normal distribuions. The first of these # distributions is centered on zero. the second is centered on the value of i. # As we go through the loop the two distributions thus get progressively further and # further appart. samples1, samples2 = np.random.normal(0,1,size=100), np.random.normal(i,1, size=100) xvals[i], common_var[i] = i, common_variance( samples1, samples2 ) # This line calculates the variance and assumes all the data points are from a # single distribution total_var[i] = sample_variance(np.concatenate([samples1, samples2])) # This generates the graph. plt.plot( xvals, total_var, 'ro' ) plt.plot( xvals, common_var, 'bo' ) plt.xlabel("Difference between means") plt.ylabel("Variance") plt.savefig("variance.png")
cd187670b4ca939919d955e25ce6d465f89b33e7
Ham4690/AtCoder
/abc162/b.py
221
3.75
4
def isFizzBuzz (N): if N % 15 == 0 : return 0 elif N % 3 == 0: return 0 elif N % 5 == 0: return 0 else: return N N = int(input()) ans = 0 for i in range(1,N+1): ans += isFizzBuzz(i) print(ans)
bb5b127f00857cc92e2f92ce894d62123cbddba1
ech1/Random-Scripts
/Python/17.py
327
3.921875
4
nterms = 10 n1 = 0 n2 = 1 count = 0 if nterms <= 0: print("Please enter a positive integer") elif nterms == 1: print("Fibo sequence upto", nterms, ":") print(n1) else: print("Fibo sequence upto", nterms,":") while count < nterms: print(n1, end=' , ') nth = n1 + n2 #update values n1 = n2 n2 = nth count += 1
38c4cc3ef45f8de2d06377304a29a3bdfd1fc895
anoop600/Python-Basics-Learn
/4. Looping/random_module.py
985
4.09375
4
import random def get_integer(prompt): while True: temp = input(prompt) if temp.isnumeric(): return int(temp) highest = 10 answer = random.randint(1,highest) print(answer) # TODO: Remove this line after testing print("Please guess number between 1 and 10: ") guess = get_integer("Enter the number : ") # if guess != answer: # if guess < answer: # print("Guess Higher... Guess Again") # else: # print("Guess Lower... Guess Again") # guess = int(input()) # if answer == guess: # print("Guess Successful") # else: # print("Not Correctly guessed") # else: # print("Got it in first Guess") if guess == answer: print("Guess Success") elif guess == 0: exit(0) else: while answer != guess: print("Try again") guess = get_integer("Enter the number : ") if guess == answer: print("Guess Success") break if guess == 0: break
3b4e2a1b82ba6b1f34f2558b65e17daaa34cdd2a
imyourghost/python
/hw1/home_work1.py
2,870
3.9375
4
good_answer=0 user_input = input ('Какой язык мы учим? ') if user_input.lower() == 'python': print ("Красава!\n") good_answer += 1 else: print ("Неправда\n") user_input = input ('Какая фамилия у препода? (ответ пишем на инглише) ') if user_input.lower() == 'sobolev': print ("Он самый\n") good_answer += 1 else: print ("Дядь, стыдно должно быть!\n") user_input = input ('True and False = ? ') if user_input.lower() == 'true': print ("Так точно\n") good_answer += 1 else: print ("НЕТ\n") user_input = input ('4 + 3 = ') if user_input.lower() == '7': print ("Перельман прям!\n") good_answer += 1 else: print ("пздц...\n") user_input = input ('str - строка? (да / нет) ') if user_input.lower() == 'да': print ("str - это три буквы, а не строка\n") good_answer += 1 else: print ("iMalaca\n") user_input = input ('Python сделает тебя умнее? (да / нет) ') if user_input.lower() == 'да': print ("Не питай себя надеждами, ты безнадежен...\n") good_answer += 1 else: print ("Все верно, иди лучше пиваса попей\n") user_input = input ('Python - это жираф? (да / нет) ') if user_input.lower() == 'да': print ("Сам ты жираф)) это червяк!\n") good_answer += 1 else: print ("Умница!\n") user_input = input ('Попытка №2 4 + 3 = ') if user_input.lower() == '7': print ("Ну вот зачем ты так? Нормально ведь общались, а ты умничаешь\n") good_answer += 1 else: print ("Братух, завязывай\n") user_input = input ('Если в python 2.7 написать print(\'YA OSEL\') что получится? ') if user_input.lower() == 'YA OSEL': print ("Бывает...\n") good_answer += 1 else: print ("Читай маны\n") user_input = input ('И на последок... 242 = ') if user_input.lower() == '242': print ("Не будь, как стадо, фантазируй\n") good_answer += 1 else: print ("Ты точно уверен, что 242={} ?" .format (user_input)) print ('\nТы ответил правильно на {} из 10 вопросов... делай выводы' .format (good_answer)) !!!!!! Переделать !!!!!! right_label = 'Правильный ответ!' wrong_label = 'Неправильный ответ!' def ask_question(question, right_answer): global right_answers user_answer = input(question) if right_answer == user_answer: right_answers +=1 print(right_label) else: print(wrong_label) questions = { 'Сколько чегото?': '23', 'А зачем труляля?': 'asdasd' } for k,v in questions.items(): ask_question(k,v)
67074c08182c5958ba967ad5b99a1a431536f251
sshukla31/misc_algos
/misc/coin_dice.py
1,802
4.34375
4
#! /usr/bin/python # -*- coding: utf-8 -*- """ Coin
Flipping
and
Die
Rolls Algorithm Solution Flip
the
coin
three
times and
use
the
three
coin
flips
as
the
bits
of
a
 three bit
number.
If
the
number
is
in
the
range
1
to
6,
output
the
number.

 Otherwise repeat. """ import random # Generate random number between 1 and 2 toss = lambda: random.randint(1, 2) def coin(): """ Return dice value between 1 and 6 using toss function """ done = True number = 0 while done: # We do -1 as we want to get binary value 0 or 1 bit1 = toss() - 1 bit2 = toss() - 1 bit3 = toss() - 1 number = bit1 * 4 + bit2 * 2 + bit3 # We validate aginst 5 becasue we peform +1 addition while return. # If we validate with six, there is probability to return zero # which is invalid for a dice if number <= 5: done = False # we do +1, as dice's minimum value is 1. It shouldn't return 0 return number + 1 def optimized_coin(): """ Return dice value between 1 and 6 using toss function """ done = True number = 0 bit1 = toss() - 1 while done: # We do -1 as we want to get binary value 0 or 1 bit2 = toss() - 1 bit3 = toss() - 1 number = bit1 * 4 + bit2 * 2 + bit3 # We validate aginst 5 becasue we peform +1 addition while return. # If we validate with six, there is probability to return zero # which is invalid for a dice if number <= 5: done = False else: bit1 = bit3 # we do +1, as dice's minimum value is 1. It shouldn't return 0 return number + 1 print optimized_coin()
377584efb23359ce3fbb461618cacfcc9105b3c8
Godson-Gnanaraj/DSA
/arrays/sorting/quick_sort.py
486
3.859375
4
def quick_sort(arr, left, right): if left >= right: return pos = left - 1 for i in range(left, right): if arr[i] <= arr[left]: pos += 1 arr[i], arr[pos] = arr[pos], arr[i] arr[pos], arr[left] = arr[left], arr[pos] quick_sort(arr, left, pos - 1) quick_sort(arr, pos + 1, right) def main(): arr = [1, 0, 3, 5, 6, 8, 9, 2, 4, 7] quick_sort(arr, 0, len(arr)) print(arr) if __name__ == "__main__": main()
a0510527f097819d5cbe0365d6514a8f5736bbdf
randomguy069/Python-tutorial-complete
/Day7/datesandtimes.py
220
4.3125
4
import datetime print(datetime.datetime.now()) yes = datetime.datetime(2017,3,24,11,2,27,0) now1= datetime.datetime.now() print(yes," ",now1) sub = now1 - yes print(sub.days) #prints the number of days between two dates
26fee7fb9a26f97279b3d3553ff8a581afd6409c
apastewk/Twilio-API
/model.py
1,374
3.53125
4
"""Models for my database to store questions questions.""" import os from flask_sqlalchemy import SQLAlchemy # This is the connection to the PostreSQL database. Getting the through the # Flask-SQLAlchemy helper library. db = SQLAlchemy() ################################################################################ # Model definitions class User(db.Model): """User of something website.""" __tablename__ = "users" user_id = db.Column(db.Integer, autoincrement=True, primary_key=True) firstname = db.Column(db.String(20)) lastname = db.Column(db.String(20)) email = db.Column(db.String(64)) phonenumber = db.Column(db.String(10)) question = db.Column(db.String(500)) def __repr__(self): """Provide helpful representation when printed.""" return "<User user_id: {} email: {}>".format(self.user_id, self.email) ################################################################################ def connect_to_db(app, db_uri="postgresql:///twiliodb"): """Connect the database to Flask app.""" app.config['SQLALCHEMY_DATABASE_URI'] = db_uri # app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True db.app = app db.init_app(app) if __name__ == "__main__": """Will conenct to the db.""" from server import app connect_to_db(app) db.create_all() print "Connected to DB."
b465348f21b0be49bf4e0b4da56961902cd7ab8a
circularpenguin/poly
/poly.py
421
3.703125
4
def poly_diff(p): deg_p = len(p) - 1 if deg_p == 0: return [0] else: return [k*p[k] for k in range(1,deg_p+1)] def poly_eval(p,a): """Given a list representing the coefficients of a polynomial in increasing order and a, return p(a)""" cumsum = 0 for n,t in zip(p, range(len(p))): r = n * a ** t cumsum = r + cumsum return cumsum
8c24a4e2555d72445a39f644c5110178b0dc7143
malomodaniels/PyCodes
/Grading_System.py
623
4.3125
4
name = input("Enter your name: ") if name: score = int(input("Enter score: ")) if score > 100: print(f"{name}, please enter a valid score") elif score >= 70: print(f"{name}, your grade is A") elif score>=60: print(f"{name}, your grade is B") elif score>=50: print(f"{name}, your grade is C") elif score>=40: print(f"{name}, your grade is D") else: print(f"Ooops! {name}, your grade is F") else: print ("Ooops! Enter your name to proceed") #name = input("Enter your name: ") #if name == "Arya Stark": #print(f"{name}, Valar Morghulis") #elif name == "John Snow": # print("You know nothing") #else: # print("Carry On!")
cc2f60cafc15fb17482307874330d807a8e77914
karen-edith/Wallbreakers
/Week2/mostCommonWord.py
1,357
3.625
4
from collections import defaultdict class Solution: def mostCommonWord(self, paragraph: str, banned: List[str]) -> str: # create a words counter initiated with 0 as values # create a punctuation array wordsCounter, punctuation = defaultdict(int), ['?', '!', ',', ';', "'", '.'] #remove punctuation from paragraph for j in punctuation: #replace , with a space and other punctuation with '' if j in punctuation and j == ',': paragraph = paragraph.replace(j, ' ') elif j in paragraph: paragraph = paragraph.replace(j, '') # after punctuation removed, split the words in the paragraph into an array words = paragraph.split(' ') # place words (except and spaces and banned words) in the wordsMap for i in range(len(words)): word = words[i].lower() if word not in banned and word!='': # count the number of times each word is used wordsCounter[word] = wordsCounter[word] + 1 #find the maximum value in words map highestFrequency = max(wordsCounter.values()) # print the key(word) that coressponds to that max value for key, value in wordsCounter.items(): if value == highestFrequency: return key
502b1a2bd613b795c4e886d8398ba2d8cbc2ea28
AceRodrigo/CodingDojoStuffs
/Python_Stack/_python/OOP/Rodriguez_Austin_VS_User.py
967
3.59375
4
class User: def __init__(self, name, email): self.name = name self.email = email self.account_balance = 0 def make_deposite(self, amount): self.account_balance+=amount def make_withdraw(self, amount): self.account_balance-=amount def display_user_balance(self): print (self.account_balance) def transfer(self,amount, accTwo): self.account_balance-=amount accTwo.account_balance+=amount Tim=User("Tim","tim@live.com") Tom=User("Tom","tom@live.com") Phil=User("Phil","phil@live.com") Tim.make_deposite(150) Tim.make_deposite(200) Tim.make_deposite(100) Tim.make_deposite(300) Tim.display_user_balance() Tom.make_deposite(299) Tom.make_deposite(766) Tom.make_withdraw(50) Tom.make_withdraw(60) Tom.display_user_balance() Phil.make_deposite(1000) Phil.make_withdraw(100) Phil.make_withdraw(250) Phil.make_withdraw(100) Phil.display_user_balance() Tim.transfer(100,Tom) Tom.display_user_balance()
37de9c37663ff02faff3dcf5b53b3c76149b44e1
MarshalLeeeeee/myLeetCodes
/44-isMatch.py
6,471
4.25
4
''' 44. Wildcard Matching Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). Note: s could be empty and contains only lowercase letters a-z. p could be empty and contains only lowercase letters a-z, and characters like ? or *. Example 1: Input: s = "aa" p = "a" Output: false Explanation: "a" does not match the entire string "aa". Example 2: Input: s = "aa" p = "*" Output: true Explanation: '*' matches any sequence. Example 3: Input: s = "cb" p = "?a" Output: false Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'. Example 4: Input: s = "adceb" p = "*a*b" Output: true Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce". Example 5: Input: s = "acdcb" p = "a*c?b" Output: false ''' class Solution: # work in logic # but in some sample, the time exceeds limit def match(self,s,p,cnt): print(s,p,cnt) if s and not p: return False if not s and not p: return True if len(s) < cnt: return False if len(p) == 1: if p[0] == '*': return True elif p[0] == '?': if len(s) == 1: return True else: return False else: if p[0] == s[0] and len(s) == 1: return True else: return False left, right = 0, len(p)-1 if p[left] == '*': if p[right] == '*': if len(p) == 3: if p[left+1] == '?': return True else: return p[left+1] in s else: start = 0 while(start < len(s)-cnt): res = self.match(s[start:],p[1:],cnt) if res: return True start+=1 return False elif p[right] == '?': return self.match(s[0:-1],p[0:-1],cnt-1) else: if s[-1]!=p[right]: return False else: return self.match(s[0:-1],p[0:-1],cnt-1) elif p[left] == '?': if p[right] == '*': return self.match(s[1:],p[1:],cnt-1) elif p[right] == '?': return self.match(s[1:-1],p[1:-1],cnt-2) else: if s[-1]!=p[right]: return False else: return self.match(s[1:-1],p[1:-1],cnt-2) else: if p[right] == '*': if s[0]!=p[left]: return False else: return self.match(s[1:],p[1:],cnt-1) elif p[right] == '?': if s[0]!=p[left]: return False else: return self.match(s[1:-1],p[1:-1],cnt-2) else: if s[0]!=p[left] or s[-1]!=p[right]: return False else: return self.match(s[1:-1],p[1:-1],cnt-2) def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ if s and not p: return False if not s and not p: return True si = 0 newp, cntp = '', 0 for pi, pc in enumerate(p): if pc == '*': if pi < len(p)-1: if p[pi+1] == '*': continue else: newp += '*' else: newp += '*' else: newp += pc cntp += 1 p = newp return self.match(s,p,cntp) class Solution2: # kpm does not work because of the kpm array does not work for '?' def charMatch(self,s,c): if c == '?' or s == '?': return True else: return s == c def strMatch(self,s,p): length = len(s) if len(p) != length: return False for i,sx in enumerate(s): if not self.charMatch(sx,p[i]): return False return True def subMatch(self,s,p,start,end): if not p: return 0 elif not s: return -1 else: curr = start pLen = len(p) while curr < end - pLen + 1: if self.strMatch(p,s[curr:curr+pLen]): return curr else: curr += 1 return -1 def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ if s and not p: return False if not s and not p: return True newp = '' for pi, pc in enumerate(p): if pc == '*': if pi < len(p)-1: if p[pi+1] == '*': continue else: newp += '*' else: newp += '*' else: newp += pc p, start = newp, 0 psplit = p.split('*') splitNum = len(psplit) if splitNum == 1: return self.strMatch(psplit[0],s) else: for i,x in enumerate(psplit): if i == 0: head = self.subMatch(s,x,start,len(s)) if head != 0: return False else: start = head + len(x) elif i < splitNum - 1: head = self.subMatch(s,x,start,len(s)) if head == -1: return False else: start = head + len(x) else: head = self.subMatch(s[::-1],x[::-1],0,len(s)-start) if head != 0: return False else: return True if __name__ == '__main__': #print(Solution().isMatch("babbbbaabababaabbababaababaabbaabababbaaababbababaaaaaabbabaaaabababbabbababbbaaaababbbabbbbbbbbbbaabbb","b**bb**a**bba*b**a*bbb**aba***babbb*aa****aabb*bbb***a")) ''' print(Solution2().isMatch( \ "abbabaa \ abba \ bba \ ababb \ abbbbbabbbabbbabaa \ aaab \ a \ bababbbabababaabbababaabbbbbbaaaabababbbaabbbbaabbbbababababbaabbaababaabbbababababbbbaaabbbbbabaaaabbababbbbaababaabbababbbbbababbbabaaaaa \ a \ aabbbbba \ abaaababaaaabb" ,"**aa*****ba*a*bb**aa*ab****a*aaaaaa***a*aaaa**bbabb*b*b**aaaaaaaaa*a********ba*bbb***a*ba*bb*bb**a*b*bb")) ''' print(Solution2().isMatch("mississippi","m??*ss*?i*pi"))
84eddcd4b549d80a56d868e6e12a362b9a0794d4
ljordan51/ToolBox-Unittest
/unittest_practice.py
390
3.65625
4
import unittest def sort_and_rm_neg_num(num_list): edited = [] for num in num_list: if num >= 0: edited.append(num) return sorted(edited) class TestMethod(unittest.TestCase): def test_func(self): self.assertEqual(sort_and_rm_neg_num([3, -4, 2, 6, -1, -8, 7, 3, 2, 1]), [1, 2, 2, 3, 3, 6, 7]) if __name__ == '__main__': unittest.main()
a461534953cf4d367e2ce0b81d25b99d01624c26
sourabhcode/python
/listoverlap_old.py
602
4
4
#!/usr/bin/python x = input ("What is size of first list:") print "Size1 :", x y = input ("What is size of second list:") print "Size2 :", y list1 = list() list2 = list() list3 = list() for i in range(x): num1 = input("enter the number:") n1 = list1.append(num1) print "first list is:", list1 for i in range(y): num2 = input("enter the number:") n2 = list2.append(num2) print "second list is:", list2 if x <= y : for j in range(x) : for k in range(y) : if list1[j] == list2[k] : list3.append(list1[j]) else : pass else : pass print "sorted list:", list3
be9618b3747fb76326efe50764e4872f874049b8
FidelSol/-Python-GeekBrains
/-Python-GeekBrains--_7_PYTHON/урок №7 Соловьев Ф.М..py
3,707
3.703125
4
# Задание №1 class Matrix: def __init__(self, *args): self.list_of_lists = [] for n in args: self.list_of_lists.append(n) def __str__(self): for n in range(0, len(self.list_of_lists)): print(self.list_of_lists[n]) if len(self.list_of_lists[n]) != len(self.list_of_lists[0]): return f"Неверно введены данные для матрицы!" break return f'Матрица {len(self.list_of_lists)} на {len(self.list_of_lists[0])}' def __add__(self, other): self.new_list_of_lists = [] for x in range(0, len(self.list_of_lists)): self.sum_matrix = [self.list_of_lists[x][n] + other.list_of_lists[x][n] for n in range(0, len(self.list_of_lists[0]))] self.new_list_of_lists.append(self.sum_matrix) for n in range(0, len(self.new_list_of_lists)): print(self.new_list_of_lists[n]) return f'Матрица {len(self.new_list_of_lists)} на {len(self.new_list_of_lists[0])}' m1 = Matrix([1, 1, 1], [2, 2, 2], [3, 3, 3]) print(m1) m2 = Matrix([1, 1, 1], [2, 2, 2], [3, 3, 3]) print(m2) print(m1 + m2) # Задание №2 class Coat: def __init__(self, v): self.consumption = round(v / 6.5 + 0.5) def __str__(self): return f'Пальто - расход {self.consumption}' class Suit: def __init__(self, h): self.consumption = round(2 * h + 0.3) def __str__(self): return f'Костюм - расход {self.consumption}' class Clothes: def __init__(self): self.consumption = 0 self.main_list = [] def __str__(self): return f'Одежда' def add_main(self, v, h): self.main_list.append(Coat(v)) self.main_list.append(Suit(h)) @property def main_consuption(self): for el in self.main_list: self.consumption += el.consumption print('Полный расход') return self.consumption c = Coat(40) s = Suit(30) print(c) print(s) cl = Clothes() print(cl) cl.add_main(30, 40) print(cl.main_consuption) # Задание №3 class Cell: def __init__(self, number): self.number = number def __str__(self): return f'Количество ячеек в клетке - {self.number}' def __add__(self, other): print(f'Сложение клеток. {Cell(self.number + other.number)}') return Cell(self.number + other.number) def __sub__(self, other): if self.number > other.number: print(f'Разница клеток. {Cell(self.number - other.number)}') return Cell(self.number - other.number) elif self.number < other.number: print(f'Разница клеток. {Cell(other.number - self.number)}') return Cell(other.number - self.number) else: print(f'Деление невозможно!') def __mul__(self, other): print(f'Умножение клеток. {Cell(other.number * self.number)}') return Cell(other.number * self.number) def __truediv__(self, other): print(f'Деление клеток. {Cell(other.number / self.number)}') return Cell(other.number / self.number) def make_order(self): x = '*****/n' y = '*' line_cell = (self.number // 5) * x + (self.number - (5 * (self.number // 5))) * y print(f'Ячейки: ') print(line_cell) return line_cell c1 = Cell(10) print(c1) c2 = Cell(7) print(c2) print(c1 + c2) print(c2 - c1) print(c1 * c2) print(c1 / c2) c1.make_order() c2.make_order()
3d380924980b41e28c1a20f538cc441199213b77
Vortes/Regular-Expressions
/basic.py
226
4.125
4
import re #* Say you want to find a phone number using regular expression message = 'Call me at 732-668-6908 or 646-671-0903' phone_number = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') mo = phone_number.findall(message) print(mo)
2062b8bb8ddb6764dce15e2319b107bf68470cba
stevenzim/lrec-2018
/src/waseem.py
1,262
3.5625
4
'''Function to load Waseem/Hovy tweets set 1 and classes from csv and return lists of data''' # Load datasets import csv # shuffle data (the tsv files are grouped by racism, sexism and none) import random from random import shuffle random.seed(21) def get_hate_data(): X_hate_raw = [] Y_hate_raw = [] with open('resources/hate_speech_corps/NAACL_SRW_2016_DOWNLOADED.csv', 'rb') as tweet_tsv: tweet_tsv = csv.reader(tweet_tsv, delimiter='\t') for row in tweet_tsv: X_hate_raw.append(row[2]) Y_hate_raw.append(row[1]) randomised_hate_idxs = range(len(X_hate_raw)) shuffle(randomised_hate_idxs) X_hate = [] Y_hate = [] Y_hate_binary = [] for idx in randomised_hate_idxs: # we don't want tweets that were not available (~700 tweets of 16,883 set were not available for download) if X_hate_raw[idx] == 'Not Available': continue else: # create a multiclass set and binary set X_hate.append(X_hate_raw[idx]) Y_hate.append(Y_hate_raw[idx]) if Y_hate_raw[idx] == 'none': Y_hate_binary.append(False) else: Y_hate_binary.append(True) return X_hate, Y_hate
81638aa69effdaf7490439113a999edd9f6ad03e
priyanshukumarcs049/Python
/Day2/The Minion Game.py
381
3.65625
4
def minion_game(string): # your code goes here vowels = 'AEIOU' kevin = 0 stuart = 0 for i in range(len(s)): if s[i] in vowels: kevin += (len(s)-i) else: stuart += (len(s)-i) if kevin > stuart: print ("Kevin", kevin) elif kevin < stuart: print ("Stuart", stuart) else: print ("Draw")
40dd98b54f00d94e43877d046e0b5341f225fd9f
GeraldineE/Curso-python
/interfaces_graficas/tkinter/tk_label.py
232
3.78125
4
from tkinter import * root = Tk() labelframe = LabelFrame(root, text = "This is a LabelFrame") labelframe.pack(fill = "both", expand = "yes") left = Label(labelframe, text = "Inside the LabelFrame") left.pack() root.mainloop()
49760a6eddd8f0b9c7b3ced820b961a0ea3a9015
bellfive/utils
/python/backup/backup_jwfreeNote.py
873
3.59375
4
# -*- coding: utf-8 -*- # backupToZip.py import zipfile, os def backupToZip(folder) : folder = os.path.abspath(folder) number = 1 while True: zipfileName = os.path.basename(folder)+'_'+str(number)+'.zip' if not os.path.exists(zipfileName): break number +=1 print 'Creating %s....' % zipfileName backupZip = zipfile.ZipFile(zipfileName, 'w') for folderName, subfolders, filenames in os.walk(folder): print('Adding files in %s...' % folderName) backupZip.write(folderName) for filename in filenames: newBase = os.path.basename(folder) + '_' if filename.startswith(newBase) and filename.endswith('.zip'): print "newBase: " + newBase + " filename: " + filename continue # don't backup zip file backupZip.write(os.path.join(folderName,filename)) backupZip.close() print ('Done...') backupToZip('D:\\01) Data\\jwfreeNote Data')
1159db0477e002d466638fa23cb7592073746a28
Carl-Aslund/project-euler
/problem010.py
566
3.984375
4
from math import sqrt def primeSieve(n): """Uses the Sieve of Erastothenes to find all primes less than n.""" primes = [] for i in range(2,n): isPrime = True root = sqrt(i) for p in primes: if p > root: break if i%p == 0: isPrime = False break if isPrime: primes.append(i) return primes def sumPrimes(n): """Sums all primes under n.""" primes = primeSieve(n) return sum(primes) print(sumPrimes(2000000)) # 142913828922
8f5ddf39ad90e9bc52e45f61a2601ecfef437f02
alecbar/data-structures-and-algorithms
/Binary Search/binary_search.py
688
4.0625
4
# Binary Search Algorithm # O(log n) def binary_search(arr, item): """ Takes a sorted list of items and an item to look for Reeturns the index of the item in the list or none if not found """ low = 0 # Frst index high = len(arr) - 1 # Last index while low <= high: mid = (low + high)// 2 # Middle index guess = arr[mid] # Check if item in middle index if guess == item: return mid # Otherwise, determine if we should look at the # beggining or end of the list on the next pass if guess > item: high = mid - 1 else: low = mid + 1 return None
d8b8496522424bb9a51e45a23987c338583b2c86
NoouFoox/DoubanCrawler
/homework/t2.py
1,434
3.71875
4
# -*- coding:utf-8 -*- # @author: 贺俊浩🐱 # @file: t2.py # @time: 2021/6/29 8:48 itemlist = [ {"name": "板烧鸡腿堡", "pice": 16}, {"name": "巨无霸", "pice": 15}, {"name": "麻辣鸡腿堡", "pice": 16}, {"name": "芝士汉堡包", "pice": 19}, {"name": "培根牛肉堡", "pice": 19} ] print("{0:*>48}".format("")) print("欢迎光临小包子的汉堡店!") print("本店售卖宇宙无敌汉堡包!") print("本店为爱心折扣店,如果你是爱心会员,优惠更大哦!") print("尊敬的客户,每次只能品尝一种汉堡哦!") for item in itemlist: print("{}.{:10}{}元".format(itemlist.index(item) + 1, item["name"], item["pice"])) print("{0:*>48}".format("")) humberger_number = eval(input("请输入要购买的汉堡编号:")) humberger_quantity = eval(input("请输入要购买的汉堡数量:")) humberger_price = itemlist[humberger_quantity]["pice"] total_money = humberger_price * humberger_quantity vip_money = total_money * 0.7 print("您购买的汉堡是{}号汉堡,共购买{}个,总计{}元".format(humberger_number, humberger_quantity, total_money)) print("您可以享受会员价,折后总价:{}".format(round(vip_money, 3))) print("{0:*>48}".format("")) print("{}".format("做一枚有态度、有思想的汉堡店(我骄傲)!")) print("{:>22}".format("祝您今日购物愉快!")) print("{:>24}".format("欢迎您再次光临!")) print("{0:*>48}".format(""))
fc19c923f8aad596bff9e6705649012d6c7bddec
m-amoit/Python-recap
/BuildingSkills/is_triangle.py
583
4.34375
4
def is_triangle(a, b, c): ''' Check whether the given lengths can form a triangle. If any of the three lengths is greater than the sum of the other two, then you cannot form a triangle. Otherwise you can. Print 'yes' if you can form a triangle, Otherwise print 'yes'. ''' if a > b + c: return 'No' elif b > a + c: return 'No' elif c > a + b: return 'No' return 'Yes' def get_length(): a = int(raw_input('Input length 1 \n')) b = int(raw_input('Input length 2 \n')) c = int(raw_input('Input length 3 \n')) return is_triangle(a, b, c) print get_length()
16318a40dbaf739fb6a258fa498cdee8b923f3ae
catr1ne55/epam_training_python
/lec1/hw/task5.py
159
3.734375
4
a = int(input()) b = int(input()) if a < b: a, b = b, a while True: rn = a % b if rn % b == 0: print(b) break a = b b = rn
91e6200a2fdc685c48d9868a513df48edb91958a
tkim92/Python-Programming
/school_labs/lab2/olympic.py
1,202
3.875
4
import turtle turtle.showturtle() def Drawcircle(radius): turtle.speed(0) scaled_radius = radius/100 #bluecircle turtle.penup() turtle.left(180) turtle.forward(300*scaled_radius) turtle.left(90) turtle.pensize(7) turtle.pendown() turtle.color("blue") turtle.circle(radius) #blackcircle turtle.left(90) turtle.penup() turtle.forward(225*scaled_radius) turtle.right(90) turtle.color("black") turtle.pendown() turtle.circle(radius) #redcircle turtle.left(90) turtle.penup() turtle.forward(225*scaled_radius) turtle.right(90) turtle.color("red") turtle.pendown() turtle.circle(radius) #yellocircle turtle.right(90) turtle.penup() turtle.forward(240*scaled_radius) turtle.left(90) turtle.forward(100*scaled_radius) turtle.right(90) turtle.forward(100*scaled_radius) turtle.left(90) turtle.pendown() turtle.color("yellow") turtle.circle(radius) #greencircle turtle.left(90) turtle.penup() turtle.color("green") turtle.forward(230*scaled_radius) turtle.right(90) turtle.pendown() turtle.circle(radius) Drawcircle(120)