blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
93949f6f6a31648204ffc3a0d10e5b69ebec9374
RavenAyn/Astrophys-Hons
/Activity 1/Raven_Q1.py
288
3.59375
4
a=85 c=input('Guess a number between 0 and 99: ') b=int(c) i=1 if (b<a): print('sorry, thats too low') elif (b>a): print('oops, youre too high') elif (b==a): print('Well done! You got it!') else: print('THOSE ARENT THE RULES, SO YOU DONT GET TO PLAY')
2c4183b3eea82f1dffd479a633ed773c0bc9d03a
Artarin/Python-Trashbox
/ArrayAllTasks.py
9,855
3.734375
4
Выведите все элементы списка с четными индексами (то есть A[0], A[2], A[4], ...). a=input().split() for i in range (0, len(a) ,2): print (a[i], end=' ' ) Выведите все четные элементы списка. При этом используйте цикл for, перебирающий элементы списка, а не их индексы! a = input ().split () s=[] for i in a: i = int (i) if i % 2 == 0: print (i, end=' ') Дан список чисел. Выведите все элементы списка, которые больше предыдущего элемента. a= [int(numbers) for numbers in input().split()] for i in range (1 , len (a)): if a[i] > a[i-1]: print (a[i], end=' ') Дан список чисел. Если в нем есть два соседних элемента одного знака, выведите эти числа. Если соседних элементов одного знака нет — не выводите ничего. Если таких пар соседей несколько — выведите первую пару. List = [int(a) for a in input().split()] for i in range (1, len(List)): if List[i - 1] < 0 and List[i] <0 or List [i-1]> 0 and List[i]>0: # if List [i-1] * List [i] > 0 print (List[i-1], List [i]) break Дан список чисел. Определите, сколько в этом списке элементов, которые больше двух своих соседей, и выведите количество таких элементов. Крайние элементы списка никогда не учитываются, поскольку у них недостаточно соседей. List = [int(i) for i in input().split()] NumOfMax=0 for i in range (1, len(List)-1): if List[i] > List[i-1] and List[i] > List[i+1]: NumOfMax+=1 print (NumOfMax) Дан список чисел. Выведите значение наибольшего элемента в списке, а затем индекс этого элемента в списке. Если наибольших элементов несколько, выведите индекс первого из них. numbers = [int(i) for i in input().split()] print (max(numbers), numbers.index(max(numbers))) Петя перешёл в другую школу. На уроке физкультуры ему понадобилось определить своё место в строю. Помогите ему это сделать. Программа получает на вход невозрастающую последовательность натуральных чисел, означающих рост каждого человека в строю. После этого вводится число X – рост Пети. Все числа во входных данных натуральные и не превышают 200. Выведите номер, под которым Петя должен встать в строй. Если в строю есть люди с одинаковым ростом, таким же, как у Пети, то он должен встать после них. list_height = [int(i) for i in input().split()] new_sportsmen=int(input()) for i in range (len(list_height)): if new_sportsmen > list_height[i]: print (i+1) break if min(list_height) >= new_sportsmen: print (i+2) Дан список, упорядоченный по неубыванию элементов в нем. Определите, сколько в нем различных элементов. List = [int(i) for i in input().split()] quantity=1 for i in range (1, len(List)): if List[i-1] != List[i]: quantity += 1 print (quantity) Переставьте соседние элементы списка (A[0] c A[1], A[2] c A[3] и т. д.). Если элементов нечетное число, то последний элемент остается на своем месте. a = [int(i) for i in input().split()] i=1 while i < len(a): a[i], a[i-1] = a[i-1], a[i] i+=2 print (' '.join([str(i) for i in a])) В списке все элементы различны. Поменяйте местами минимальный и максимальный элемент этого списка. List = [int(i) for i in input().split()] a = List.index(min(List)) b = List.index(max(List)) List[a], List[b] = List[b], List[a] print (' '.join([str(i) for i in List])) Дан список из чисел и индекс элемента в списке k. Удалите из списка элемент с индексом k, сдвинув влево все элементы, стоящие правее элемента с индексом k. Программа получает на вход список, затем число k. Программа сдвигает все элементы, а после этого удаляет последний элемент списка при помощи метода pop() без параметров. Программа должна осуществлять сдвиг непосредственно в списке, а не делать это при выводе элементов. Также нельзя использовать дополнительный список. Также не следует использовать метод pop(k) с параметром. a = [int(i) for i in input().split()] k=int(input()) for i in range (k, len(a) - 1): a[i] = a [i + 1] a.pop() print (' '.join([str(i) for i in a])) Дан список целых чисел, число k и значение C. Необходимо вставить в список на позицию с индексом k элемент, равный C, сдвинув все элементы, имевшие индекс не менее k, вправо. Поскольку при этом количество элементов в списке увеличивается, после считывания списка в его конец нужно будет добавить новый элемент, используя метод append. Вставку необходимо осуществлять уже в считанном списке, не делая этого при выводе и не создавая дополнительного списка. numbers = [int(i) for i in input().split()] k, c = [int(i) for i in input().split()] numbers.append(c) for i in range (len(numbers)-1, k, -1): numbers[i], numbers[i-1] = numbers [i-1], numbers [i] print (' '.join([str(i) for i in numbers])) Дан список чисел. Посчитайте, сколько в нем пар элементов, равных друг другу. Считается, что любые два элемента, равные друг другу образуют одну пару, которую необходимо посчитать. a = [int(i) for i in input().split()] duplex = 0 for i in range (0, len(a)-1): b=a[i+1:] duplex+=b.count(a[i]) print (duplex) Дан список. Выведите те его элементы, которые встречаются в списке только один раз. Элементы нужно выводить в том порядке, в котором они встречаются в списке. a = [int(i) for i in input().split()] for i in (a): if a.count(i) == 1: print (i, end=' ') Условие N кеглей выставили в один ряд, занумеровав их слева направо числами от 1 до N. Затем по этому ряду бросили K шаров, при этом i-й шар сбил все кегли с номерами от li до ri включительно. Определите, какие кегли остались стоять на месте. Программа получает на вход количество кеглей N и количество бросков K. Далее идет K пар чисел li, ri, при этом 1≤ li≤ ri≤ N. Программа должна вывести последовательность из N символов, где j-й символ есть “I”, если j-я кегля осталась стоять, или “.”, если j-я кегля была сбита. n, k = [int(i) for i in input().split()] towers = ['I']*n for i in range (k): drops = [int(l) for l in input().split()] towers[drops[0]-1:drops[1]] = ['.']* (drops[1]-drops[0]+1) print (''.join(towers)) Известно, что на доске 8×8 можно расставить 8 ферзей так, чтобы они не били друг друга. Вам дана расстановка 8 ферзей на доске, определите, есть ли среди них пара бьющих друг друга. Программа получает на вход восемь пар чисел, каждое число от 1 до 8 — координаты 8 ферзей. Если ферзи не бьют друг друга, выведите слово NO, иначе выведите YES. queen = [] gor = [] vert = [] answer = 'NO' for i in range (8): queen = ([int(j) for j in input().split()]) gor += [queen[0]] vert += [queen[1]] for i in range (8): for j in range (i+1, 8): if gor[i] == gor[j] or vert[i] == vert[j]: answer = 'YES' break if abs(gor[i] - gor[j]) == abs(vert[i] - vert[j]): answer = 'YES' print (answer)
28bb9ea2d5b95f329afd1a3727dabc11b6101a5d
martinwangjun/python_study
/08_io/file_open.py
636
3.65625
4
#!/usr/bin/env python8 # -*- coding: utf-8 -*- # f = open('somefile.txt', 'w', encoding='utf-8') # f.write('你在不经意间看见过什么不该看见的东西或者事情?') # f.close() # with open('somefile.txt', 'w', encoding='utf-8') as f: # num = f.write('你在不经意间看见过什么不该看见的东西或者事情?') # print(num) # 读写文件 with open('somefile.txt', 'a+', encoding='utf-8') as f: # num = f.write('贵州现在天天都是发展大数据') # print(num) text = f.read() print(text) f.write('你在不经意间看见过什么不该看见的东西或者事情?')
892220b95cab1dd1250a9d407692503242a2bb28
YashaswiRahut/codecademy
/chapter 14 - 10.py
211
3.53125
4
def censor(text, word): a = text.split() s = '*' * len(word) count = 0 for j in a: if j == word: a[count] = s count += 1 result =' '.join(a) return result
10ffe80d69d5fd13d0af332e864c08f6abd4271a
NoSpectators/python-examples
/python_scripts_for_sharing/no_teen_sum.py
440
3.671875
4
def main(): array = [no_teen_sum(1,2,3), no_teen_sum(2,13,1), no_teen_sum(2,1,14)] print_results(array) def print_results(arr): for i in arr: print 'the sum of the array (excluding teens) except 15 and 16 is', i def no_teen_sum(a,b,c): return fix_teen(a) + fix_teen(b) + fix_teen(c) def fix_teen(n): if n in range(13,20): if n in range(15,17): return n return 0 return n main()
0e0c7e2e723792249519744fb1f42ba045f2512b
whywhs/Leetcode
/Leetcode622_M.py
2,428
4.1875
4
#循环队列,先入先出的结构,可以进行广度优先搜索,寻找最短距离。需要注意的点有几个: #1、end的更新是要在操作之前,因为在操作之后的话,就会错位。 #2、0与None均为否,所以,不能单纯以if 数组中的元素来进行判断。 class MyCircularQueue(object): def __init__(self, k): """ Initialize your data structure here. Set the size of the queue to be k. :type k: int """ self.queue = [None]*k self.start = 0 self.end = 0 self.len = k def enQueue(self, value): """ Insert an element into the circular queue. Return true if the operation is successful. :type value: int :rtype: bool """ if None in self.queue: self.end = self.end+1 if self.end == self.len+1: self.end=self.end-self.len self.queue[self.end-1]=value #print(self.queue) return True return False def deQueue(self): """ Delete an element from the circular queue. Return true if the operation is successful. :rtype: bool """ if self.queue[self.start]!=None: self.queue[self.start]=None self.start = self.start+1 if self.start == self.len: self.start = self.start-self.len #print(self.queue) return True return False def Front(self): """ Get the front item from the queue. :rtype: int """ if self.queue[self.start]==None: return -1 return self.queue[self.start] def Rear(self): """ Get the last item from the queue. :rtype: int """ if self.queue[self.end-1]==None: return -1 return self.queue[self.end-1] def isEmpty(self): """ Checks whether the circular queue is empty or not. :rtype: bool """ for i in self.queue: if i!=None: return False return True def isFull(self): """ Checks whether the circular queue is full or not. :rtype: bool """ for i in self.queue: if i==None: return False return True
fd223188c477a998889358305790770a077c894d
zoemarschner/zbin
/bin/wkstr.py
1,569
3.640625
4
import argparse import os, json, sys, math import datetime """ set the WEEK STRINGS as enviroment variable, so that it can be referenced in code for example, for labelling folders of research pictures the format is WKSTR_[day of week symobl] = [month][day]_[yr] the week "starts" at the next day--so if it is Tuesday """ WEEK_SYMBOLS = ['M', 'T', 'W', 'Th', 'F', 'S', 'Su'] def strings_for_next_week(wrap=False): today = datetime.date.today() out = {} for i in range(7): date = datetime.date.today() + datetime.timedelta(days=i + (1 if wrap else 0)) date_symbol = WEEK_SYMBOLS[date.isoweekday()-1] daystr = date.strftime("%b%-dth_%y") daystr = daystr.replace('th', ordinal_for(date.day)).lower() out[f'WKSTR_{date_symbol}'] = f'{daystr}' return out def ordinal_for(day): if day >= 10 and day <= 20: return "th" if day % 10 == 1: return "st" if day % 10 == 2: return "nd" if day % 10 == 2: return "rd" return "th" def print_export_command(variables): print('export ', end='') for name, value in variables.items(): print(f'{name}={value} ', end='') parser = argparse.ArgumentParser(description=' Sets the WEEK STRINGS as enviorment variables. \nThe format is WKSTR_[day of week symobl] = [month][day]_[yr]') parser.add_argument('-w', dest='wrap', action='store_const', const=True, default=False, help='Wrap the week, so that the week string for the current weekday will be set to the date for the next instance of that day') args = parser.parse_args() print_export_command(strings_for_next_week(wrap=args.wrap))
674c63dfaa1a44c7e3f8ee3565cc4f1da42f60f1
Naatoo/advent-of-code-2019
/day5/solution.py
5,144
3.765625
4
from typing import List, Generator def get_program() -> List[int]: with open("input.txt") as file: program: List[int] = [int(num) for num in file.read().split(",")] return program def process_program_part_1(program: List[int], input_value: int) -> List[int]: index: int = 0 while True: instruction_value: str = str(program[index]) opcode: int = int(instruction_value[-2:]) if opcode == 99: yield 'opcode_99' mode_par_1, mode_par_2, mode_par_3 = (int(instruction_value[digit_index]) if len(instruction_value) >= abs(digit_index) else 0 for digit_index in range(-3, -6, -1)) assert all(par in (0, 1) for par in (mode_par_1, mode_par_2, mode_par_3)), \ f"{mode_par_1}, {mode_par_2}, {mode_par_3}" if opcode in [1, 2, 3]: if opcode in [1, 2]: input_1, input_2 = (program[index + instruction_index + 1] if par == 1 else program[program[index + instruction_index + 1]] for instruction_index, par in enumerate((mode_par_1, mode_par_2))) write_value: int = get_score(opcode, input_1, input_2) write_address: int = program[index + 3] index += 4 else: write_value: int = input_value write_address: int = program[index + 1] index += 2 program[write_address] = write_value elif opcode == 4: yield_value: int = program[index + 1] if mode_par_1 == 1 else program[program[index + 1]] yield yield_value index += 2 else: raise ValueError(f"Opcode={opcode} is not in (1, 2, 3, 4, 99)") def get_score(opcode: int, input_1: int, input_2: int) -> int: score: int if opcode == 1: score = input_1 + input_2 elif opcode == 2: score = input_1 * input_2 return score def get_diagnostic_code(program: List[int], input_value: int, part: int) -> int: func = process_program_part_1 if part == 1 else process_program_part_2 generated_codes: Generator = func(program, input_value) for code in generated_codes: try: assert code == 0 except AssertionError: diagnostic_code: int = code break next_code = next(generated_codes) if next_code == 'opcode_99': return diagnostic_code else: raise ValueError(f"Diagnostic_code={diagnostic_code}, next_code={next_code}") def process_program_part_2(program: List[int], input_value: int) -> List[int]: index: int = 0 while True: instruction_value: str = str(program[index]) opcode: int = int(instruction_value[-2:]) if opcode == 99: yield 'opcode_99' mode_par_1, mode_par_2, mode_par_3 = (int(instruction_value[digit_index]) if len(instruction_value) >= abs(digit_index) else 0 for digit_index in range(-3, -6, -1)) assert all(par in (0, 1) for par in (mode_par_1, mode_par_2, mode_par_3)), \ f"{mode_par_1}, {mode_par_2}, {mode_par_3}" input_1, input_2 = (program[index + instruction_index + 1] if par == 1 else program[program[index + instruction_index + 1]] for instruction_index, par in enumerate((mode_par_1, mode_par_2))) if opcode in [1, 2, 3]: if opcode in [1, 2]: write_value: int = get_score(opcode, input_1, input_2) write_address: int = program[index + 3] index += 4 else: write_value: int = input_value write_address: int = program[index + 1] index += 2 program[write_address] = write_value elif opcode == 4: yield_value: int = program[index + 1] if mode_par_1 == 1 else program[program[index + 1]] yield yield_value index += 2 elif opcode == 5: if input_1 != 0: index = input_2 else: index += 3 elif opcode == 6: if input_1 == 0: index = input_2 else: index += 3 elif opcode in (7, 8): third_param = program[index + 3] if opcode == 7 and input_1 < input_2: val: int = 1 elif opcode == 8 and input_1 == input_2: val: int = 1 else: val: int = 0 program[third_param] = val index += 4 else: raise ValueError(f"Opcode={opcode} is not in (1, 2, 3, 4, 5, 6, 7, 8 99)") if __name__ == "__main__": part_1_result: int = get_diagnostic_code(get_program(), input_value=1, part=1) print("PART1:", part_1_result) part_2_result: int = get_diagnostic_code(get_program(), input_value=5, part=2) print("PART2:", part_2_result)
b94ad91eace020a548ba690be4e0455fc380411b
kileyneushul/python_stack
/_python/OOP/Week 2/store/store_and_products.py
1,521
3.6875
4
class Store: def __init__(self, name): self.name = name self.product = [] #methods def add_product(self, new_product): self.product.append(new_product) return self def sell_product(self, id): for i in self.product: id = i print("Item #{}:").format(id) return self class Product: def __init__(self, name, price, category): self.name = name self.price = price self.category = category #methods def update_price(self, percent_change, is_increased): if is_increased == True: self.price += percent_change else: self.price -= percent_change return self def print_info(self): print("Name: {}, Category: {}, Price: ${}").format(self.name, self.category, self.price) return self #creation vons = Store("Vons") costco = Store("Costco") wholefoods = Store("Whole Foods") vons.add_product("Watermelon").add_product("Mango").add_product("Papaya").add_product("Strawberries") costco.add_product("Muffins").add_product("Pizza").add_product("Chicken Bake").add_product("Trail Mix") wholefoods.add_product("Alternative Chips").add_product("Coconut Yogurt").add_product("Sushi Veggie Roll").add_product("Silk Almond Milks") #remove a product vons.sell_product(0) print(vons.product) print(costco.product) print(wholefoods.product) print(vons.product)
459c61a02e6c1e4cf1e8d9ef609cd1c6f50b7f6c
Rony82012/Python_proj
/entropy.py
269
3.875
4
import math pi = [float(x) for x in input('Please Enter values of type FLOAT:\n').split()] #result = 0 def entropy(pi): result = 0 for i in pi: summ = -i * math.log(i,2) result = result + summ #print(result) #print (result) return result print (entropy(pi))
7d37d5f038c68e703f24aa38b5302065016f1c24
24rochak/GeeksforGeeks
/Searching/InterpolationSearch.py
1,699
4.15625
4
def interpolation_search(arr: [int], key: int, low: int, high: int) -> int: """ Performs Interpolation Search over given array. Works best when elements are uniformly distributed. Time complexity : O(log(log(n))), worst case : O(n) :param arr: Sorted Input Array. :param key: Value to be searched for. :param low: Starting index of target array. :param high: Ending index of target array. :return: Index of key if it is present in the array else -1. """ # Check if array is valid or not. if low <= high: # If corners are reached, to avoid division by 0 error, check here itself. if low == high: if arr[low] == key : # Return index of low if key is present. return low; return -1; # Calculate location of pos. pos = low + int(((key - arr[low]) * (high - low)) / (arr[high] - arr[low])) if arr[pos] == key: # Return index of pos if key is present. return pos; elif arr[pos] > key: # Perform interpolation_search on left sub-array. return interpolation_search(arr, key, low, pos - 1) else: # Perform interpolation_search on right sub-array. return interpolation_search(arr, key, pos + 1, high) else: return -1 if __name__ == '__main__': # Test array arr = [10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47] key = 33 # Perform interpolation_search loc = interpolation_search(arr, key, 0, len(arr) - 1) # Display the index of key print("Key is present at index : ", loc)
3231aa95223b038a426c8db49aea4c793001cc7c
qianjinfighter/py_tutorials
/earlier-2020/python_mod_tutorials/py_thread/threading_local.py
832
3.78125
4
# -*- coding: utf-8 -*- """ threading.local 是为了方便在线程中使用全局变量而产生 每个线程的全局变量互不干扰 """ from threading import local, enumerate, Thread, currentThread local_data = local() local_data.name = 'local_data' class TestThread(Thread): def run(self): print currentThread() print local_data.__dict__ local_data.name = self.getName() local_data.add_by_sub_thread = self.getName() print local_data.__dict__ if __name__ == '__main__': print currentThread() print local_data.__dict__ print '----------------' t1 = TestThread() t1.start() t1.join() print '----------------' t2 = TestThread() t2.start() t2.join() print '----------------' print currentThread() print local_data.__dict__
8ba9ef7e5f237a61739780d3e8686fef289545c9
JoannaEbreso/PythonProgress
/perfectSquare.py
424
4.03125
4
numberInput=input("Enter a number: ") number=int(numberInput) factor=1 sum_of_factors=0 while factor<number: if number%factor==0: sum_of_factors=sum_of_factors+factor factor=factor+1 if sum_of_factors==number: print(number, "is a perfect square") else: print(number,"is not a perfect square") if sum_of_factors<number: print(number, "is deficient") else: print(number, "is abundant")
abd77a79d18e65a771cb2d11e1980aafe0d06702
Alialmandoz/Calculadora
/calculadora_cli.py
1,034
3.734375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys from tokenize import tokenize def validate_token(token): return token.isnumeric() or is_operator(token) def validate_tokens(tokens): for token in tokens: if not validate_token(token): return False return True def is_operator(character): return character == '*' or character == '/' or character == '+' or character == '-' def evaluate(expresion): non_valid_expresion_error_message = "expresion inválida" tokens = tokenize(expresion) if validate_tokens(tokens): try: out = eval(expresion) print("resultado: " + str(out)) return out except SyntaxError: print(non_valid_expresion_error_message) except ZeroDivisionError: print("Division por cero no esta definida") else: print(non_valid_expresion_error_message) # if len(sys.argv) > 1: # evaluate(sys.argv[1]) # else: # print("usage: calculadora_cli.py <expresion>")
c47f2007dde6d4007107b17f2d045b7415c4cdc8
utshav2008/python_training
/random/rough.py
1,227
4.09375
4
class Node: def __init__(self, data=None): self.data = data self.next = None class LinkedList: def __init__(self): self.head = Node() def append(self, data): new_node = Node(data) cur = self.head while cur.next != None: cur = cur.next cur.next = new_node def display(self): cur = self.head elem = [] while cur.next != None: cur = cur.next elem.append(cur.data) print(elem) def insert(self, data, index): new_node = Node(data) cur = self.head i=0 while i != index: cur = cur.next i+=1 next_node = cur.next cur.next = new_node new_node.next = next_node def erase(self,index): cur = self.head i = 0 while i != index: last = cur cur = cur.next i+=1 last.next = cur.next l1 = LinkedList() l1.append(12) l1.append(13) l1.append(14) l1.insert(26,0) l1.display() l1.erase(1) l1.display() # l1.length() # l1.insert(55,1) # l1.insert(5,2) # l1.insert(65,3) # l1.display() # l1.erase(1) # l1.erase(2) # l1.erase(3) # l1.display()
36b3ecf91bc98817e51573cd169da775376b4a0f
ahmadalvin92/Praktikum-08
/List.py
908
3.75
4
#--------------1----------------- a = [1, 5, 6, 3, 6, 9, 11, 20, 12] b = [7, 4, 5, 6, 7, 1, 12, 5, 9] #--------------2---------------- a.insert(3,10) b.insert(2,15) #--------------3---------------- a.append(4) b.append(8) #--------------4---------------- a.sort() b.sort() #--------------5---------------- c = a[0:8] d = b[2:10] #--------------6---------------- e = [] for i in range(len(c)) : element = c[i] + d[i] e.append(element) #--------------7---------------- dataTuple = tuple(e) #--------------8---------------- minTuple = min(dataTuple) maksTuple = max(dataTuple) sumTuple = sum(dataTuple) #--------------9---------------- myString = "python adalah bahasa pemrograman yang menyenangkan" #--------------10--------------- charPenyusun = set(myString) #--------------11---------------- listPenyusun = list(charPenyusun) listPenyusun.sort()
d2c1e79e01846a148c2ec55f8ea9c272f8934145
mgbo/My_Exercise
/Дистанционная_подготовка/Программирование_на_python/14_Двумерные_массивы/_example.py
482
3.765625
4
A = [[1,2,3],[4,5,6],[7,8,9]] def print_M(A): s='' for row in range(len(A)): for col in range(len(A[row])): s+=str(A[row][col])+' ' s=s+'\n' return s.strip() def print_M_1(A): for i in range(len(A)): for j in range(len(A[i])): print (A[i][j],end=' ') print() def display(A): for row in A: for elem in row: print (elem,end=' ') print () #print(print_M(A)) print_M_1(A) print ("----------") for row in A: print(' '.join(list(map(str, row))))
d5322c82c60a9b46789fc7bed74dcb2e0baf8a77
sagark9040/LeetcodePython
/py_basics/string.py
556
4.15625
4
x = 'Coke' y = 'Pepsi' z = 'Sprite' #concatenate print (x + ' & ' + y + ' & ' + z) #repeat print ("repeat coke: ", x*2) #slicing .. substring from position sub1 = x[2:] print(sub1) #slicing .. substring from and to sub_from_to = x[1:3] print(x, "1:3", sub_from_to) # Slicing .. string.charAt char_at = y[0] + y[1] print(char_at) #reverse a string s = 'sAGARnambi' print(s[::-1]) print(s[::2], '..', s[1::-2]) #capitalize print("orig:", s) s = str.upper(s) print("upper:", s) s = str.lower(s) print("lower:", s) s = s.replace("sagar", "new") print(s)
bf25880407695f534344635b54a7d0704ba5f691
linwenfang/PycharmProject
/LearningText/OOP/Car.py
4,119
3.75
4
#coding=gbk # class Car: # def __init__(self,newNum,newColor): # self.wheelNum=newNum#wheelNumΪCarһ # self.color=newColor#colorΪCarһ # def __str__(self): # msg="color="+self.color+" wheelnum="+str(self.wheelNum)#ôҲ # return msg # def move(self): # print('runing...') # def tools(self): # print('ڽ....') # class Animal: # def __init__(self,name): # self.name=name # def printName(self): # print('my name is '+self.name) # '''Եеķ''' # def myPrint(anima): # anima.printName() # dog1=Animal('beibei') # myPrint(dog1) # dog1.printName() # # BMW=Car(4,'blue') # BMW.move() # AUDI=Car(4,'red') # print(BMW.color) # print(BMW.wheelNum) # print(BMW) # print(AUDI) # # class People(object): # # def __init__(self, name): # self.__name = name # self.name=name # # def getName(self): # return self.__name,self.name # # def setName(self, newName): # if len(newName) >= 5: # self.__name = newName # else: # print("error:ֳҪڻߵ5") # # xiaoming = People("dongGe") # xiaoming.name='ahahhahaha' # print(xiaoming.getName()) # xiaoming.setName("wanger") # print(xiaoming.getName()) # # xiaoming.setName("lisi") # print(xiaoming.getName()) import time # class test_del: # def __init__(self,name): # print("init") # self.__name=name # def __del__(self): # print("del") # print("%sҪɾ"%self.__name) # dog=test_del('һ') # del dog # cat=test_del('ڶ') # cat2 = cat # cat3 = cat # # print("--- ɾcat") # # del cat # print("--- ɾcat2") # # del cat2 # print("--- ɾcat3") # del cat3 # # print("2Ӻ") # time.sleep(2) '''˽Կͨøķʣ˽зDzԷʵ''' # class Cat(object): # def __init__(self,name,color='black'): # self.__name=name # self.color=color # def run(self): # print("%s can run"%self.__name) # def __test(self): # print("pravite") # print(self.__name) # print(self.color) # def test(self): # print("public") # print(self.__name) # print(self.color) # class Bosi(Cat): # def setNewName(self,newName): # self.__name=newName # def eat(self): # print("%s is eating..."%self.__name) # def run(self): # print("%s is runing..."%self.__name) # bs=Bosi('indinan','white') # bs.setNewName('liuhaha') #coding=utf-8 # class base(object): # def test(self): # print('----base test----') # class A(base): # def test(self): # print('----A test----') # # # һ # class B(base): # def test(self): # print('----B test----') # # # һ̳࣬AB # class C(A,B): # pass # # # obj_C = C() # obj_C.test() # # print(C.__mro__) #Բ鿴CĶʱȺ˳ # class Cat(object): # def __init__(self,name): # self.name=name # def sayhello(self): # print("say hello ---1---") # class Bosi(Cat): # def sayhello(self): # print("say hello ---2---") # super().sayhello()#дøsayhello # bosi=Bosi('huahua') # bosi.sayhello() # '''̬''' # class F1(object): # def show(self): # print("F1 show") # class S1(F1): # def show(self): # print("S1 show") # class S2(F1): # def show(self): # print("S2 show") # def Func(obj): # print(obj.show()) # # s1_obj=S1() # Func(s1_obj) # s2_obj=S2() # Func(s2_obj) # '''''' # class People: # address='china' # print(People.address) # p=People() # print(p.address) # p.address='janpan' # print(p.address) # print(People.address) # People.address='janpan' # print(p.address) # print(People.address)
3c6640c2a62f2a3b16b224e7fc4333e53ad3db33
anku255/HackerRank
/30-Days-of-Code/Day 3: Intro to Conditional Statements.py
444
4.375
4
""" Given an integer n , , perform the following conditional actions: If n is odd, print Weird If n is even and in the inclusive range of 2 to 5, print Not Weird If n is even and in the inclusive range of 6 to 20, print Weird If n is even and greater than 20, print Not Weird """ N = int(raw_input().strip()) if N%2 !=0 : print "Weird" elif 2<= N <=5: print "Not Weird" elif 6<= N <=20: print "Weird" else: print "Not Weird"
40defa4be5fbbb2d4edb1cf2afd448fa5855ec4a
ssp4all/computer-simulation-and-modeling
/random/tests/independence/Runs Above and Below Mean.py
701
3.796875
4
import re, math runs = [float(x) for x in input("Enter the random sequece: ").split(',') if 0<=float(x)<1] alpha = float(input("Enter the critical value: ")) mn, mx = [float(x) for x in input("Enter range of random sequence: ").split('-') if 0<=float(x)<1] N = len(runs) mean = (mn+mx)/2 for i in range(N): runs[i] = '-' if runs[i]<mean else '+' runs = ''.join(runs) n1 = runs.count('+') n2 = runs.count('-') runs = re.findall(r'\++|-+',runs) b = len(runs) mean = ((2*n1*n2)/N)+0.5 variance = (2*n1*n2*(2*n1*n2-N))/(N**2*(N-1)) z = (b-mean)/math.sqrt(variance) if -alpha < z < alpha: print("\nThe random sequence is independent") else: print("\nThe random sequence is not independent")
03b676eaf86e60d0798b7dfcb7f0c699ca90cd9c
chenjienan/python-leetcode
/OA/Microsoft/numbers_with_equal_digit_sum.py
804
4.1875
4
def getDigitSum(num): sum = 0 while num: sum += num % 10 num // 10 # return the max sum of two numbers in an array, whose digits add up to an equal sum # algorithm: # scan the array, store the numbers whose digits add up to an equal sum in a hash map # if one number has the same digit sum, update the max value and store the larger value in the map def maxDigitSum(arr): # key: digit sum # value hash_map = {} res = -1 # store the max value of a pair for num in arr: digit_sum = getDigitSum(num) if digit_sum in hash_map: last_num = hash_map[digit_sum] res = max(res, num + last_num) hash_map[digit_sum] = max(last_num, num) else: hash_map[digit_sum] = num return res
c43d0dedd0c954a2f9236df614324e125e003608
rich-03/TGC-Learn2Prog
/Lecture09/Exercise09-09.py
530
3.953125
4
def findincrease(val1, val2): if val2 > val1: return val2 - val1 else: return 0 salary1 = float(input("Enter previous salary")) benefits1 = float(input("Enter previous benefits")) bonus1 = float(input("Enter previous bonus")) salary2 = float(input("Enter new salary")) benefits2 = float(input("Enter new benefits")) bonus2 = float(input("Enter new bonus")) salaryincrease = findincrease(salary1, salary2) benefitsincrease = findincrease(benefits1, benefits2) bonusincrease = findincrease(bonus1, bonus2)
171dd446f2c4b171f299ec5e6a2fd50ffd63f1e7
Zapfly/Udemy-Rest-APIs-with-Flask-Alchemy-
/SECTION_1_and_2/13)advanced set operations/13)advanced set operations.py
377
3.859375
4
friends = {"Bob", "Rolf", "Anne"} abroad = {"Bob", "Anne"} local_friends = friends.difference(abroad) print(local_friends) #alternatively... local2 = {"Rolf"} abroad2 = {"Bob", "Anne"} friends2 = local2.union(abroad2) print(friends2) #New ex art = {"Bob", "Jen", "Rolf", "Charlie"} science = {"Bob", "Jen", "Adam", "Anne"} both = art.intersection(science) print(both)
621ea002c2e86433310582b4f035cfc997dbea3c
superyaooo/LanguageLearning
/Python/Learn Python The Hard Way/ex12s.py
251
3.609375
4
fingers = raw_input("How many fingers do you have?") toes = raw_input("How many toes do you have?") print """ \toh my!\n\tdo you really have %r fingers and %r toes?!""" % (fingers, toes) # use \n before \t to make the TAB valid.
7fed7deece26222ffa5bffa91808b990ce934728
iicoom/Note
/DataBase/redis/Redis-Pool.py
2,562
3.796875
4
# https://stackoverflow.com/questions/31663288/how-do-i-properly-use-connection-pools-in-redis # settings.py: import redis def get_redis_connection(): return redis.StrictRedis(host='localhost', port=6379, db=0) # task1.py import settings connection = settings.get_redis_connection() def do_something1(): return connection.hgetall(...) # task2.py import settings connection = settings.get_redis_connection() def do_something1(): return connection.hgetall(...) # So each task file has its own redis instance (which presumably is very expensive). # What's the best way of optimizing this process. Is it possible to use connection pools for this example? # You could choose to setup the connection pool in the init method and make the pool global # (you can look at other options if uncomfortable with global). redis_pool = None def init(): global redis_pool print("PID %d: initializing redis pool..." % os.getpid()) redis_pool = redis.ConnectionPool(host='10.0.0.1', port=6379, db=0) # You can then retrieve the connection from a pool like this: redis_conn = redis.Redis(connection_pool=redis_pool) redis-cli info Redis-py provides a connection pool for you from which you can retrieve a connection. Connection pools create a set of connections which you can use as needed (and when done - the connection is returned to the connection pool for further reuse). Trying to create connections on the fly without discarding them (i.e. not using a pool or not using the pool correctly) will leave you with way too many connections to redis (until you hit the connection limit). You could choose to setup the connection pool in the init method and make the pool global (you can look at other options if uncomfortable with global). redis_pool = None def init(): global redis_pool print("PID %d: initializing redis pool..." % os.getpid()) redis_pool = redis.ConnectionPool(host='10.0.0.1', port=6379, db=0) You can then retrieve the connection from a pool like this: redis_conn = redis.Redis(connection_pool=redis_pool) Also, I am assuming you are using hiredis along with redis-py as it should improve performance in certain cases. Have you also checked the number of connections open to the redis server with your existing setup as it most likely is quite high? You can use the INFO commmand to get that information: # redis-cli info # Check for the Clients section in which you will see the "connected_clients" field that will tell you how many connections # you have open to the redis server at that instant.
a867e39fc7609b52ec6177cd58c7d2c3b5ddbcb2
gabgc/YouTube-to-Spotify
/src/video.py
1,733
3.65625
4
class Video(object): """ This class models a YouTube video with all the necessary information to search through a playlist. """ __search_query__ = None artist = None def __init__(self, video_title): self.video_title = video_title self.set_search_query(self.video_title) self.__parse_artist__() def get_search_query(self): return self.__search_query__ def set_search_query(self, sq): self.__search_query__ = Video.simplifyTitle(sq) @staticmethod def simplifyTitle(title): #Credit to github user srajangarg for most of this if title is "": return title title = title.replace('"', "") import re title = re.sub("[\(\[].*?[\)\]]", "", title) tobe = ["Official", "OFFICIAL", "Music", "MUSIC", "Video", "VIDEO", "Original", "ORIGINAL", "Audio", "AUDIO", "Lyric", "LYRIC", "Lyrics", "LYRICS", "Out", "OUT", "Now", "NOW"] for string in tobe: title.replace(string, "") featuring = ["feat", "ft", "Ft", "Feat", "Featuring", "with", ',', "&"] for feat in featuring: index = title.find(feat) if index is not -1: findDash = title.find("-") if findDash is not -1 and index < findDash: str1 = title[index:findDash-1] title = title.replace(str1, "") else: title = title[:index] break return title def __parse_artist__(self): title = self.get_search_query() self.artist = title[:title.find("-") - 1]
d9b299034601d7a3ca7ca263a7cc00ac9d9b854f
ricardojrdez/avl-tree
/avlnode.py
1,686
3.828125
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- '''Auxiliary class to define the node of an AVL tree A node is composed of a key and a value (optionally None). This abstraction enables you to use the AVL as a structure to store elements with an associated key. ''' __author__ = "Ricardo J. Rodríguez" __copyright__ = "Copyright 2020, University of Zaragoza, Spain" __credits__ = ["Ricardo J. Rodríguez"] __license__ = "GPL" __version__ = "1.0" __maintainer__ = "Ricardo J. Rodríguez" __email__ = "rjrodriguez@unizar.es" __status__ = "Production" class AVLNode: def __init__(self, key, value=None): self.key = key self.value = value self.left = None self.right = None self.height = 1 def __str__(self): #_str = '{0}[{1}:{2}]{3}'.format(self.key, self.height, self.get_balance_factor(), 'L' if self._is_leaf() else ' ') _str = '{0}{1}'.format(self.key, '[' + str(self.value) + ']' if self.value is not None else '') return _str def _is_leaf(self) -> bool: return (self.left == None and self.right == None) def get_balance_factor(self) -> int: return self.get_height(self.right) - self.get_height(self.left) def get_height(self) -> int: return self.height def get_height(self, node) -> int: if node is None: return 0 else: return node.height def is_unbalanced(self) -> bool: return (abs(self.get_balance_factor()) == 2) def update_height(self): self.height = max(self.get_height(self.left), self.get_height(self.right)) + 1 def update_content(self, node): # updates the content values self.key = node.key self.value = node.value
c784a049285078d35a26eb6823a27fe9d65f390c
intellihr/interlagos
/interlagos/generic/lemmatizer.py
427
3.53125
4
from nltk.stem import WordNetLemmatizer def lemmatize(tokens): """Reduce each token to its lemma form by using wordnet. Todo: * Support customizable lemmatizer Args: tokens (list of str): A list of tokens. Returns: list of str: A list of lemmatized tokens. """ wordnet_lemmatizer = WordNetLemmatizer() return [wordnet_lemmatizer.lemmatize(token) for token in tokens]
925c50beb77ee65156d39de440324e730afe4ba8
polinaleonova/PYthon_prometeus
/5.2.py
557
3.546875
4
__author__ = 'polina' def counter(a, b): str_a = str(a) list_b = str(list(set(str(b)))) list_res = [] for i in str_a : if list_b.find(i) != -1: list_res.append(i) return len(set(list_res)) # # counter(98123560, 79266) # # proposed version # def counter(a, b): # num = 0 # a_str = str(a) # b_str = str(b) # found = '' # for char_b in b_str: # if a_str.find(char_b) != -1 and found.find(char_b) == -1: # num = num + 1 # found = found + char_b # return num
8d5be276fd5673e8954ceb97a06bd126f26e3cd5
pinetree408/apss
/brackets2.py
910
3.65625
4
def solve(formula): opening = '({[' closing = ')}]' stack = [] for i in range(len(formula)): if formula[i] in opening: stack.append(formula[i]) else: if len(stack) == 0: return False top_idx = len(stack)-1 if opening.index(stack[top_idx]) != closing.index(formula[i]): return False stack.pop() return len(stack) == 0 def brackets2(input_case): global CACHE input_list = list( map( lambda x: [i for i in x.strip().split(' ')], input_case.split('\n') ) ) case_num = int(input_list[0][0]) input_list = input_list[1:] for i in range(case_num): print solve(input_list[i][0]) if __name__ == '__main__': input_case = \ '''3 ()() ({[}]) ({}[(){}])''' brackets2(input_case)
75d86608cc7d2004738e5711f70bea47635b2504
pglen/pgpygtk
/neural/neural-009/tenticle.py
3,514
3.640625
4
#!/usr/bin/env python # ------------------------------------------------------------------------ # Neural network tenticle. verbose = 0 import trans from neuutil import * # ------------------------------------------------------------------------ # Basic building block of the neuron's input: class tenticle(): def __init__(self, parent, tent, curr): # Additions self.bias = neurand() self.post = neurand() # Multiplications self.weight = neurand() self.multi = neurand() self.mularr = [] for aa in range(10): self.mularr.append(neurand()) # Ins and outs self.input = neurand() self.output = neurand() self.tent = tent self.curr = curr self.parent = parent if verbose: print self.tent, # -------------------------------------------------------------------- # Calculate output def fire(self, parent): #res = (self.input) * (self.weight) res = (self.input + self.bias) * (self.weight) '''res = self.input + self.bias for aa in range(10): if aa % 2 == 0: res += self.mularr[aa] else: res += self.mularr[aa]''' #res = (self.input) * (self.weight + self.bias) #res = (self.input + self.bias - self.post) * (self.weight) #res = (self.input + self.bias) * (self.input + self.post) * self.weight #res = (self.input + self.bias) * (self.weight) / (self.input + self.post) * (self.multi) #res = ((self.input + self.bias) * (self.weight + self.post)) * (self.multi + self.post) #res = ((self.input + self.bias) * (self.weight + self.post)) + (self.bias) * (self.multi) #res = (self.input) * (1. + self.weight) + self.bias #print parent.level, parent.num, self.curr, \ # "input", self.input, "weight", self.weight, "bias", self.bias, "res", res #print "res", res, #return trans.tfunc(res) #return trans.tfunc2(res) return res # Pretty print tenticle def getstr(self): return " [in: %0.3f" % self.input, "w: %0.3f" % self.weight, \ "b: %0.3f ]" % self.bias, \ "p: %0.3f ]" % self.post, # Tip a tenticle by a random amount def randtip(self, net, neu, val): net.last_tent = self net.last_weight = self.weight net.last_bias = self.bias net.last_post = self.post net.last_multi = self.multi net.last_bias2 = self.parent.bias net.last_mularr = self.mularr[:] #rr = random.randint(0, 9) #self.mularr[rr] += neurand() rr = random.randint(0, 4) if rr == 0: self.weight += neurand2() #self.weight += val elif rr == 1: self.bias += neurand2() #self.bias += val elif rr == 2: self.parent.bias += neurand2() #self.parent.bias += val elif rr == 3: self.post += neurand2() #self.post += val elif rr == 4: self.multi += neurand2() #self.multi += val else: print "bad random index"
14186f9487362aebd00b202255eb0d8138ede703
antoinetlc/tensorflow_classifiers
/mnist_2layers.py
4,725
4.15625
4
import tensorflow as tf import numpy as np import pylab import matplotlib.pyplot as plt from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets """ Three steps to use tensorflow. 1 - Build the inference Graph 2 - Build the loss graph and return the loss tensor 3 - Write a training function that apply the gradient updates """ def mnist_inferenceGraph(images, dimension, hiddenUnits1, hiddenUnits2, numberClasses): """Build the MNIST inference graph args: images : images placeholder (data) dimension : size of the images hiddenUnits1 : Size of the first layer of hidden units hiddenUnits2 : Size of the second layer of hidden units numberClasses : number of classes to classify outputs: tensor with the computed logits """ with tf.name_scope("hiddenLayer1"): weights = tf.Variable(tf.truncated_normal([dimension, hiddenUnits1], stddev = 1.0/tf.sqrt(float(dimension)), name ="weights")) biases = tf.Variable(tf.zeros([hiddenUnits1], name="biases")) activationHidden1 = tf.nn.relu(tf.matmul(images, weights)+biases) with tf.name_scope("hiddenLayer2"): weights = tf.Variable(tf.truncated_normal([hiddenUnits1, hiddenUnits2], stddev = 1.0/tf.sqrt(float(hiddenUnits1)), name="weights")) biases = tf.Variable(tf.zeros([hiddenUnits2]), name="biases") activationHidden2 = tf.nn.relu(tf.matmul(activationHidden1, weights)+biases) with tf.name_scope("softmax_linear"): weights = tf.Variable(tf.truncated_normal([hiddenUnits2, numberClasses], stddev=1.0/tf.sqrt(float(hiddenUnits2)), name="weights")) biases = tf.Variable(tf.zeros([numberClasses]), name = "biases") finalLogits = tf.matmul(activationHidden2, weights)+biases return finalLogits def mnist_loss(labels, logits): """ args: labels and logits (predicted labels) returns The loss function value """ loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = labels, logits = logits)); return loss def mnist_training(xData, yData, learningRate, dimension, hiddenUnits1, hiddenUnits2, numberClasses): """ args: xData, yData : placeholders for the images data and the labels learningRate : value of the learning rate dimension : size of the images hiddenUnits1 : Size of the first layer of hidden units hiddenUnits2 : Size of the second layer of hidden units numberClasses : number of classes to classify returns train_step : The training operation with Gradient descent loss : The tensor of the loss logits : The tensor of the logits """ logits = mnist_inferenceGraph(xData, dimension, hiddenUnits1, hiddenUnits2, numberClasses) loss = mnist_loss(yData, logits) #Gradient descent optimizer train_step = tf.train.GradientDescentOptimizer(learningRate).minimize(loss) return train_step, loss, logits def main(): """ Main function to execute the code """ #Models sizes NUMBER_CLASSES = 10 WIDTH_IMAGE = 28 HEIGHT_IMAGE = 28 DIMENSION = WIDTH_IMAGE*HEIGHT_IMAGE BATCH_SIZE = 100 #Model parameters HIDDEN_UNITS1 = 128 HIDDEN_UNITS2 = 32 TRAINING_STEPS = 10000 #Load Data TRAIN_DIRECTORY = "MNIST_data" mnist = read_data_sets(TRAIN_DIRECTORY, one_hot = True) #Data placeholders xData = tf.placeholder(tf.float32, [None, DIMENSION]) yData = tf.placeholder(tf.float32, [None, NUMBER_CLASSES]) #One hot representation train_step, loss, logits = mnist_training(xData, yData, 0.01, DIMENSION, HIDDEN_UNITS1, HIDDEN_UNITS2, NUMBER_CLASSES) #Tensorflow session init = tf.global_variables_initializer() sess = tf.InteractiveSession() sess.run(init) #Apply gradient descent lossValues = [] for i in range(TRAINING_STEPS): xBatch, yBatch = mnist.train.next_batch(BATCH_SIZE) _, currentLoss = sess.run([train_step, loss], {xData:xBatch, yData:yBatch}) lossValues.append(currentLoss) #Computes the accuracy yPredicted = tf.nn.softmax(logits) correctPrediction = tf.equal(tf.argmax(yData, axis=1),tf.argmax(yPredicted, axis=1)) testAccuracy = tf.reduce_mean(tf.cast(correctPrediction, tf.float32)) print("Accuracy : %f ", sess.run([testAccuracy], {xData: mnist.test.images, yData:mnist.test.labels})) plt.plot(lossValues) plt.show() if __name__ == "__main__": main()
b26b98c9cc771f066afddf6c1a32caf0ca746bf3
eistre91/ThinkPython2
/Chapter15/notes15.py
521
3.796875
4
import math class Point: """Represents a point in 2-D space. attributes:x, y """ def distance_between_points(p1, p2): return math.sqrt( (p1.x - p2.x)**2 + (p1.y - p2.y)**2 ) class Rectangle: """Represents a rectangle. attributes: width, height, corner. """ box = Rectangle() box.width = 100.0 box.height = 200.0 box.corner = Point() box.corner.x = 0.0 box.corner.y = 0.0 p1 = Point() p1.x = 3.0 p1.y = 4.0 import copy p2 = copy.copy(p1) #there's also copy.deepcopy for getting at objects #inside objects
09562852096161a06dd3ef8e60347865068bb8fe
ranjanrajiv00/python-algo
/ds/linkedlist/linked-list.py
634
4.0625
4
import node class LinkedList: def __init__(self): self.head = None self.tail = None def insert(self, data): newNode = node.Node(data) if self.head == None: self.head = self.tail = newNode else: self.tail.next = newNode self.tail = newNode def display(self): current = self.head while current != None: print(current.data) current = current.next linkedList = LinkedList() linkedList.insert(10) linkedList.insert(20) linkedList.insert(30) linkedList.insert(40) linkedList.insert(50) linkedList.display()
d11b2ee91e18116b796f3fcb4309d8483f5ef58f
Lidor115/KNN-Decision-Tree-and-Naive-Bayes
/Node.py
551
4.125
4
class Node: """ node class - label (of the node yes or no) and the subtree this class is for the ID3 algorithm that add nodes to the tree """ def __init__(self, label,subtree): """ initialize the node :param label: the label of the node (yes or no) :param subtree: the subtree """ self.label = label self.subtree = subtree def __str__(self): """ return the label of the node :return: the label of the node """ return self.label
10173f3c9e494bc3c1a91552dc4c6354434eaab5
Tecmax/journaldev
/Python-3/basic_examples/python_comparison_operators.py
1,569
4.1875
4
# Learn how to override comparison operators for custom objects class Data: id = 0 def __init__(self, i): self.id = i def __eq__(self, other): print('== operator overloaded') if isinstance(other, Data): return True if self.id == other.id else False else: return False def __ne__(self, other): print('!= operator overloaded') if isinstance(other, Data): return True if self.id != other.id else False else: return False def __gt__(self, other): print('> operator overloaded') if isinstance(other, Data): return True if self.id > other.id else False else: return False def __lt__(self, other): print('< operator overloaded') if isinstance(other, Data): return True if self.id < other.id else False else: return False def __le__(self, other): print('<= operator overloaded') if isinstance(other, Data): return True if self.id <= other.id else False else: return False def __ge__(self, other): print('>= operator overloaded') if isinstance(other, Data): return True if self.id >= other.id else False else: return False d1 = Data(10) d2 = Data(7) print(f'd1 == d2 = {d1 == d2}') print(f'd1 != d2 = {d1 != d2}') print(f'd1 > d2 = {d1 > d2}') print(f'd1 < d2 = {d1 < d2}') print(f'd1 <= d2 = {d1 <= d2}') print(f'd1 >= d2 = {d1 >= d2}')
bb8651a4083e0c657a79fe68c1db98b52196f768
darkjune/back
/bobblesort.py
417
3.765625
4
__author__ = 'user' def sort(numbers): for i in range(len(numbers)): '''count how many num being processing''' print 'i:',i for j in range(i): '''in counted num, processing one by one''' print 'j:',j if numbers[j]>numbers[j+1]: numbers[j],numbers[j+1]=numbers[j+1],numbers[j] print numbers numbers = [34,12,8,21,55] sort(numbers)
7d46e5687efb46b3dff7ad70a5e92c26f06469cb
jhu-library-applications/file-management
/renameFilesInMultipleDirectories.py
2,839
3.75
4
import csv from datetime import datetime import time import argparse import os parser = argparse.ArgumentParser() parser.add_argument('-d', '--directory', help='the directory of the files to be renamed. optional - if not provided, the script will ask for input') parser.add_argument('-f', '--fileNameCSV', help='the CSV file of name changes. optional - if not provided, the script will ask for input') parser.add_argument('-m', '--makeChanges', help='Enter "true" to if the script should actually rename the files (otherwise, it will only create a log of the expected file name changes). optional - if not provided, the script will to "false"') args = parser.parse_args() if args.directory: directory = args.directory else: directory = input('Enter the directory of the files to be renamed: ') if args.fileNameCSV: fileNameCSV = args.fileNameCSV else: fileNameCSV = input('Enter the CSV file of name changes (including \'.csv\'): ') if args.makeChanges: makeChanges = args.makeChanges else: makeChanges = input('Enter "true" to if the script should actually rename the files (otherwise, it will only create a log of the expected file name changes): ') directoryName = directory.replace('/', '') directoryName = directoryName.replace(':', '') print(directoryName) startTime = time.time() f = csv.writer(open('renameLog'+directoryName+datetime.now().strftime('%Y-%m-%d %H.%M.%S')+'.csv','wb')) f.writerow(['oldFileName'] + ['newFileName']) for filePath, subFolders, fileNames in os.walk(directory, topdown=True): for fileName in fileNames: with open(fileNameCSV) as csvfile: reader = csv.DictReader(csvfile) for row in reader: oldFileName = row['fileName'] newFileName = row['newFileName'] currentFolderName = row['currentFilePath'] if fileName == oldFileName and filePath == currentFolderName: oldPath = os.path.join(filePath, fileName) newPath = os.path.join(filePath, newFileName) print('anticipated changes: '+oldPath+', '+newPath) f.writerow([oldPath] + [newPath]) if makeChanges == 'true': if os.path.exists(newPath): print("Error renaming '%s' to '%s': destination file already exists." % (oldPath, newPath)) else: os.rename(oldPath, newPath) else: print('log of expected file name changes created only, no files renamed') elapsedTime = time.time() - startTime m, s = divmod(elapsedTime, 60) h, m = divmod(m, 60) print('Total script run time: ', '%d:%02d:%02d' % (h, m, s))
3392662cef7b89fd1ad11e6b2d3983b051a6dc4f
jakesjacob/FDM-Training-3
/Exercises/database_example.py
7,914
3.921875
4
import sqlite3 from _sqlite3 import OperationalError class Banking: """Banking application will manage database connectivity""" def __init__(self): """This initialiser/class constructor will create the database currency_manager.db, if it doesn't exist and open a connection to it""" connection = sqlite3.connect("currency_manager.db") cursor = connection.cursor() def welcomeMessage(self): """welcomeMessage will print a welcome message""" print("\nWelcome to Banking Management Software!\n") def createTable_Customers(self): """createTable_Customers will create the database table(s)""" connection = sqlite3.connect("currency_manager.db") cursor = connection.cursor() cursor.execute('DROP TABLE IF EXISTS customers') cursor.execute( "CREATE TABLE customers (cust_id INTEGER, cust_name TEXT, currentAcc_num INTEGER, SavingAcc_num INTEGER)") connection.close() def insert_initailDataSet(self): """insert_initailDataSet will add initial data to the database table(s)""" try: connection = sqlite3.connect("currency_manager.db") cursor = connection.cursor() starter_accounts = [ (710, "Matt", 334003, 5162022), (510, "Jon", 334004, 5162032), (310, "Liz", 334005, 5162042), (220, "Beth", 334006, 5162052), (880, "Tom", 334007, 5162062), (500, "Judith", 334008, 5162072), (290, "Raymond", 334009, 5162082), (420, "Frances", 334010, 5162020) ] cursor.executemany( 'INSERT INTO customers VALUES (?,?,?,?)', starter_accounts) connection.commit() print("Bulk rows added successfully") except OperationalError as errMsg: print(errMsg) except: print("error on INSERT many records at a time") connection.rollback() else: print("Success, no error!") finally: connection.close() def createNewAccount(self, custId, custName, currentAcc, SavingAcc): """createNewAccount will add specified data to the database table(s)""" try: connection = sqlite3.connect("currency_manager.db") cursor = connection.cursor() cursor.execute("INSERT INTO customers (cust_id, cust_name, currentAcc_num, SavingAcc_num) VALUES (? , ? , ? , ?)", (custId, custName, currentAcc, SavingAcc)) connection.commit() print("one record added successfully") except OperationalError as errMsg: print(errMsg) except: print("error on INSERT") connection.rollback() else: print("Success, no error!") finally: connection.close() def fetchAllAccount(self): """fetchAllAccount will fetch/select all the data in the table""" rowSet = () try: connection = sqlite3.connect("currency_manager.db") cursor = connection.cursor() rowSet = cursor.execute( "SELECT cust_id, cust_name, currentAcc_num, SavingAcc_num FROM customers").fetchall() except OperationalError as errMsg: print(errMsg) except: print("error on Fetch") connection.rollback() finally: connection.close() return rowSet def fetchAccountId_first(self): """fetchAccountId_first will fetch/select the first account that was created/ has the smallest id """ rowSet = () try: connection = sqlite3.connect("currency_manager.db") cursor = connection.cursor() rowSet = cursor.execute( "SELECT MIN(cust_id) FROM customers").fetchall() except OperationalError as errMsg: print(errMsg) except: print("error on Fetch") connection.rollback() finally: connection.close() return rowSet def fetchAccountId_Highest(self): """fetchAccountId_Highest will fetch/select last account created/ most recent/lastest id """ rowSet = () try: connection = sqlite3.connect("currency_manager.db") cursor = connection.cursor() rowSet = cursor.execute( "SELECT MAX(cust_id) FROM customers").fetchall() except OperationalError as errMsg: print(errMsg) except: print("error on Fetch") connection.rollback() finally: connection.close() return rowSet def fetchAccount_By_Id(self, findThis_id): """ fetchAccount_By_Id will fetch / select matching data for the specified id. """ rowSet = () try: connection = sqlite3.connect("currency_manager.db") cursor = connection.cursor() rowSet = cursor.execute( "SELECT cust_id, cust_name, currentAcc_num, SavingAcc_num FROM customers WHERE cust_id = ?", (findThis_id,), ).fetchall() except OperationalError as errMsg: print(errMsg) except: print("error on Fetch") connection.rollback() finally: connection.close() return rowSet def fetchAccount_By_Name(self, findThis_name): """fetchAccount_By_Name will fetch/select matching data for the specified name""" rowSet = () try: connection = sqlite3.connect("currency_manager.db") cursor = connection.cursor() rowSet = cursor.execute( "SELECT cust_id, cust_name, currentAcc_num, SavingAcc_num FROM customers WHERE cust_name = ?", (findThis_name,), ).fetchall() except OperationalError as errMsg: print(errMsg) except: print("error on Fetch") connection.rollback() finally: connection.close() return rowSet def UpdateAccount_Detail(self, findThis_id, New_name): """UpdateAccount_Detail will Update customer name for the given ID""" try: connection = sqlite3.connect("currency_manager.db") cursor = connection.cursor() cursor.execute( "UPDATE customers SET cust_name = :who WHERE cust_id = :whoseID", {"who": New_name, "whoseID": findThis_id} ) connection.commit() print("Account_Detail for:", findThis_id, " Updated successfully") except OperationalError as errMsg: print(errMsg) except: print("error on INSERT") connection.rollback() else: print("Success, no error!") finally: connection.close() def DeleteAccount_Record(self, findThis_id): """DeleteAccount_Record will delete row by id""" try: connection = sqlite3.connect("currency_manager.db") cursor = connection.cursor() cursor.execute( "DELETE FROM customers WHERE cust_id = ?", (findThis_id,)) connection.commit() print("Account_Detail for:", findThis_id, " has been deleted successfully") except OperationalError as errMsg: print(errMsg) except: print("error on INSERT") connection.rollback() else: print("Success, no error!") finally: connection.close() ''' test1 = Banking() test1.welcomeMessage() #### One-off or reset #### test1.createTable_Customers() test1.insert_initailDataSet() help(test1) '''
da6794a579f4ef13c7730a789782536afe981327
abhishekushwaha610/assist
/assistant.py
4,799
3.59375
4
import wikipedia import pyttsx3 import speech_recognition as sr import webbrowser as wb import sys import smtplib import os import wolframalpha global a a=True '''This is simple assitant. In this you need to enter wolframalpha ID and also need to enter your Gmail ID in send_mail()''' ############################said######################### engine=pyttsx3.init() def say(audio): ''' this function makes text to speech''' print(audio) engine.say(audio) engine.runAndWait() #------------------------------------------------------ ##########wolframe alpha############### client=wolframalpha.Client('''enter_your_wolframe_alpha_here''') #####################take############################# def take(): '''take() is like a main function it listen the voice''' r=sr.Recognizer() with sr.Microphone() as source: print('listening....') audio=r.listen(source) try: text=r.recognize_google(audio) print(text) Text= text.lower() main(Text) except: print('sorry') ##########################new_listen####################### def new_listen(): '''this function recognize the voice but it use for email sending''' r=sr.Recognizer() with sr.Microphone() as source: print('listening....') audio=r.listen(source) try: text=r.recognize_google(audio) #print(text) Text= text.lower() return Text except: new_listen() ############-############### send mail fun c######################### def send_mail(reciever): try: server=smtplib.SMTP('smtp.gmail.com',587) server.starttls() mymail='your_mail@gmail.com'#here write your own gmail with open('pass.txt','r') as f:#i use external txt file for password password=f.readline() server.login(mymail,password) say('say message') message=new_listen() print(message) server.sendmail(mymail,reciever,message) say('mail sent') server.quit() except: print('mail not send') #############################main############################ def main(Text): #Text=take() global a dic={ 'what is your name?':'my name is zarvis', } if 'abhishek' in Text: say('he is boss') elif 'hello' in Text or 'omega'==Text: say('hi sir! how may i help you ?') elif 'exit' in Text: say('see you later') quit() sys.exit() elif 'open' in Text: #print(Text.find('open')) ans=Text[Text.find('open')+5:] say(f'opening {ans}') wb.open(f'http://www.{ans.replace(" ","")}.com') elif 'on google' in Text: say('searching on google') wb.open(Text.replace('on google','')) elif 'what is' in Text or 'who' in Text: say('searching!') ans=wikipedia.summary(Text,sentences=2) say(ans) elif 'image' in Text: link=Text.replace('image','') say('opening image') wb.open(f'https://www.google.com/search?tbm=isch&source=hp&biw=1536&bih=722&ei=wBEWXe3qB9K7rQHU46joBQ&q={link}&oq=amitbchchan&gs_l=img.3..0l10.8210.15359..17495...3.0..1.365.2771.0j2j6j3......0....1..gws-wiz-img.....0..35i39.OxGpGdUWEg4') elif 'email' in Text: say('what you want write gmail or say gmail') while True: ask=new_listen() print(ask) if 'write' in ask: say('alright') reciever=input('enter Gmail>') send_mail(reciever) break elif 'say' in ask: say('say reciever gmail') reciever=new_listen().replace(' ','') print(reciever) send_mail(reciever) break else: print('say again') elif 'play' in Text: #song=Text.find('play').replace(' ','-') wb.open(f"""https://www.jiosaavn.com/search/{Text.replace('play','').replace(' ','-')}""") elif 'bye' in Text or 'stop' in Text: a=False say('thankyou!') else: try: ans=client.query(Text) res=next(ans.results).text say(res) except: say('opening google') search=Text.replace(' ','') wb.open(f"https://www.google.com/search?source=hp&ei=zloXXeSHMJjorQH52J_ACA&q={search}&oq=bhopal&gs_l=psy-ab.3..0l2j0i131j0l7.1770.3077..3740...0.0..0.291.1443.0j4j3......0....1..gws-wiz.....0..35i39.ZRWvFIYZ2mA") if __name__=="__main__": say('hello Boss!') a=True while a==True: say('ask somthing!') take()
765b132d874f72b5d191e70498e9c1403ee43f8d
SergioVenicio/GOF
/behavioral/command/command.py
1,060
3.84375
4
from abc import ABC, abstractmethod class Receiver: def proccess_int(self, payload): return f'[INT] {self.proccess(payload)}' def proccess(self, payload): return f'{payload}' class Command(ABC): @abstractmethod def execute(self) -> None: raise NotImplementedError() class SimpleCommand(Command): def __init__(self, payload: str) -> None: self._payload = payload def execute(self): return self._payload class ComplexCommand(Command): def __init__(self, receiver: Receiver, payload): self._receiver = receiver self._payload = payload def execute(self): if isinstance(self._payload, int): return self._receiver.proccess_int(self._payload) return self._receiver.proccess(self._payload) if __name__ == '__main__': receiver = Receiver() print(SimpleCommand('simple').execute()) for payload in [1, 'payload', {'my': 'dict'}]: comand = ComplexCommand(receiver, payload) print(comand.execute())
27d2f26610df00cbb20e299fb80c7bc402d47562
Decade1/INFDEV02-1_0919821
/Reverse/Reverse/Reverse.py
128
3.71875
4
rev = raw_input("What sentence should be reversed? ") i = len(rev) while i >= 1: print "\b" + rev[i - 1], i -= 1 print
ef5fbeb5206e02443d02354a0521ec83f27cded6
evilbeaver12/HackerRank_Python
/01_basic_data_types.py
4,516
4.40625
4
''' All Domains > Python > Basic Data Types https://www.hackerrank.com/domains/python/py-basic-data-types/difficulty/all/page/1 ''' from profilehooks import profile def lists(): ''' Consider a list (list = []). You can perform the following commands: 1. insert i e: Insert integer e at position i. 2. print: Print the list. 3. remove e: Delete the first occurrence of integer e. 4. append e: Insert integer e at the end of the list. 5. sort: Sort the list. 6. pop: Pop the last element from the list. 7. reverse: Reverse the list. Initialize your list and read in the value of n followed by n lines of commands where each command will be of the 7 types listed above. Iterate through each command in order and perform the corresponding operation on your list. ''' nums_list = [] for _ in range(int(input())): command = input().split() if command[0] == "print": print(nums_list) else: eval("nums_list." + command[0] + "(" + ",".join(command[1:]) + ")") def tuples(): ''' Given an integer n, and n space-separated integers as input, create a tuple t, of those n integers. Then compute and print the result of hash(t). ''' n = input() print(hash(tuple(list(map(int, input().split()))))) def list_comprehensions(): ''' You are given three integers X, Y and Z representing the dimensions of a cuboid. You have to print a list of all possible coordinates on a 3D grid where the sum of X_i + Y_i + Z_i is not equal to N. If X = 2, the possible values of X_i can be 0, 1 and 2. The same applies to Y and Z. ''' X, Y, Z, N = (int(input()) for _ in range(4)) print([[x, y, z] for x in range(X + 1) for y in range(Y + 1) for z in range(Z + 1) if x + y + z != N]) # @profile def find_the_second_largest_mine(): ''' You are given N numbers. Store them in a list and find the second largest number. ''' n = int(input()) numbers = [int(x) for x in input().split()] max_value = max(numbers) numbers = [x for x in numbers if x != max_value] print(max(numbers)) # @profile def find_the_second_largest_1(): ''' You are given N numbers. Store them in a list and find the second largest number. ''' n, a = int(input()), list(set([int(x) for x in input().split()])) print(sorted(a)[len(a) - 2]) def nested_lists(): ''' Given the names and grades for each student in a Physics class of N students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line. ''' n = int(input()) students = [] first = 100 second = 100 for _ in range(n): name = input() score = float(input()) if score < first: second = first first = score elif score < second and score != first: second = score students.append([name, score]) second_students = [s[0] for s in students if s[1] == second] for student in sorted(second_students): print(student) def nested_lists_minimal(): ''' Same as before with minimal lines of code. ''' students = [[input(), float(input())] for _ in range(int(input()))] second = sorted([s[1] for s in students])[1] print('\n'.join(sorted([s[0] for s in students if s[1] == second]))) def find_the_percentage(): ''' You have a record of N students. Each record contains the student's name, and their percent marks in Maths, Physics and Chemistry. The marks can be floating values. The user enters some integer N followed by the names and marks for N students. You are required to save the record in a dictionary data type. The user then enters a student's name. Output the average percentage marks obtained by that student, correct to two decimal places. ''' students = {} for _ in range(int(input())): student = input().split() students[student[0]] = [float(s) for s in student[1:]] scores = students[input()] print('%.2f' % (sum(scores) / len(scores))) # lists() # tuples() # list_comprehensions() # find_the_second_largest_number_mine() # find_the_second_largest_number_1() # nested_lists() # nested_lists_minimal() find_the_percentage()
33175504098d5f5cdd1dd27c4d784b844bbbcced
jy2881/AndrewNg-ML-python
/ex5/plot.py
1,166
3.5
4
#-*-coding:utf-8 -*- __author__ = 'Jy2881' import numpy as np import matplotlib.pyplot as plt import polyFeatures def plotNormal(X,y): plt.scatter(X,y,color='r',marker='X',s=70,linewidths=0.01) plt.xlabel('Change in water level (x)') plt.ylabel('Water flowing out of the dam (y)') return plt def plotLC(X1,y1,X2,y2): plt.plot(X1,y1,color='y',label='Train') # plt.legend('Train') plt.plot(X2,y2,color='g',label='Cross Validation') # plt.legend('Cross Validation') plt.title('Learning curve for linear regression') plt.xlabel('Number of training examples') plt.ylabel('Error') plt.axis([0,13,0,150]) plt.legend() return plt def plotFit(X,y,mu, sigma, theta, p,xlambda): plotNormal(X,y) plt.title('Polynomial Regression Fit (lambda = %f)'%xlambda) x = np.arange((np.min(X)-15),(np.max(X)+25),0.05) l = len(x) x = x.reshape(l,1) # Map the X values X_poly = polyFeatures.polyFeatures(x, p) X_poly = X_poly-mu X_poly = X_poly/sigma # Add ones X_poly = np.c_[(np.ones([x.shape[0], 1]),X_poly)] # Plot plt.plot(x,np.dot(X_poly,theta),color='b') return plt
f7b58ae0f24bcfe8460803ec62aec4787615b422
Bar-BelliedCuckooshrike/EstudosPython
/Definindo_funcoes.py
190
4.0625
4
""" Funções: """ #definindo a função: def say_hi(): print('Hello, world! :D') #chamando a função: say_hi() print('--------') for n in range(3): say_hi() print('---------')
462c70de3914c598f5721a197cb331505e5efd1c
christopherwj/a_code_a_day
/python/morse_code_translater/morsecode.py
784
3.609375
4
#import pandas as pd d = { 'a' : '.-', 'b' : '-...', 'c' : '-.-.', 'd' : '-..', 'e' : '.', 'f' : '..-.', 'g' : '--.', 'h' : '..', 'i' : '..', 'j' : '.---', 'k' : '-.-', 'l' : '.-..', 'm' : '--', 'n' : '-.', 'o' : '---', 'p' : ' .--.', 'q' : '--.-', 'r' : '.-.', 's' : '...', 't' : '-', 'u' : '..-', 'v' : '...-', 'w' : '.--', 'x' : '-..-', 'y' : '-.--', 'z' : '--..', } #file_object = open("wordlist.txt", "r") #def smorase() dash = 0 dot = 0 file_contents = open('wordlist.txt') for line in file_contents: for letter in line: convertedLetter = d.get(letter) dash += str(convertedLetter).count("-") dot += str(convertedLetter).count(".") print('the amount of dashes are {}'.format(dash)) print('the amount of dots are {}'.format(dot))
293602c5371afa07839b3af0b3286daf153d8c97
Usama-Cookie/SaylaniPython
/Random-5.py
253
3.90625
4
foods = ('pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream') print('Old menu is:') for food in foods: print(food) foods = ('pizza', 'Zinger', 'carrot cake', 'Salad', 'ice cream') print('New menu is:') for food in foods: print(food)
ba333b3477c429cdb5d9472095e9371cf159dc7d
BigNianNGS/AI
/python_base/json_storage.py
1,316
3.78125
4
''' 保存 json文件 dump as srite load as read ''' import json # ~ nums = [2,3,4,5,6,7,8,9,9] # ~ filename = 'nums.json' # ~ with open(filename,'w') as w_obj: # ~ json.dump(nums,w_obj) # ~ with open(filename,'r') as r_obj: # ~ json = json.load(r_obj) # ~ print(json) # ~ filename2 = 'username.json' # ~ try: # ~ with open(filename2,'r') as r_obj: # ~ username = json.load(r_obj) # ~ except FileNotFoundError: # ~ username = input('please input your name:') # ~ with open(filename2,'w') as w_obj: # ~ json.dump(username,w_obj) # ~ print('we already rememmer your name') # ~ else: # ~ print('welcome come back: '+username) #重构 使代码更加的清晰 并且容易理解 容易扩展 def get_stored_username(): filename = 'username.json' try: with open(filename,'r') as r_obj: username = json.load(r_obj) except FileNotFoundError: return None else: return username def write_into_username(): username = input('please input your name:') filename2 = 'username.json' with open(filename2,'w') as w_obj: json.dump(username,w_obj) return username def great_user(): username = get_stored_username() if username: print('welcome back ' + username) else: username = write_into_username() print('we already rememmer your name'+ username) great_user()
dc4e1a66e05f8db95dda9efbdc9c4dfc3748b791
IDSF21/assignment-2-samarthgowda
/main.py
4,335
3.5625
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import streamlit as st @st.cache def load_songs(): df = pd.read_csv("./data.csv") df = df.drop_duplicates(["id", "name"], keep="last") df = df.dropna(how="any") df["year"] = df["year"].astype(int) return df songs = load_songs() @st.cache def get_years(songs): return list(np.sort(songs["year"].unique())) years = get_years(songs) @st.cache def calculate_songs_agg(songs): songs_agg = songs.groupby("year").agg( { "acousticness": np.mean, "danceability": np.mean, "duration_ms": np.mean, "energy": np.mean, "instrumentalness": np.mean, "liveness": np.mean, "loudness": np.mean, "popularity": np.mean, "speechiness": np.mean, "tempo": np.mean, "valence": np.mean } ) songs_agg.index = pd.to_datetime(songs_agg.index, format="%Y") return songs_agg songs_agg = calculate_songs_agg(songs) with st.container(): """ # 🎶 How Music has Changed from 1921-2020 Information about these songs are from Spotify Web API. Dataset provided from [Kaggle](https://www.kaggle.com/ektanegi/spotifydata-19212020). """ if st.checkbox("Show raw dataframe of Spotify 1921-2020 Songs Dataset"): songs if st.checkbox("Show dataframe of average values for different columns in Spotify Songs grouped by Year"): songs_agg with st.container(): """ ### 📅 Understanding how different aspects of songs have changed over time Overtime, song attributes have changed a lot. Take a look at how certain attributes are very similar overtime from 1921 to 2020 and how other attributes change drastically over the last century. """ overall_variable_select = st.selectbox( "Select the variable that you would like to explore.", [ "acousticness", "danceability", "duration_ms", "energy", "instrumentalness", "liveness", "loudness", "speechiness", "tempo", "valence" ], key="overall_variable", ) songs_agg_data = songs_agg[[overall_variable_select]] songs_agg_data["year"] = songs_agg_data.index fig, ax = plt.subplots() ax.plot("year", overall_variable_select, data=songs_agg_data) ax.set_xlabel("Release Year") ax.set_ylabel(overall_variable_select) ax.set_title(f"{overall_variable_select} vs Release Year for Spotify Song Data 1921-2021") st.pyplot(fig) with st.container(): """ ### 🔊 Understanding the distribution of aspects of songs for a given release year range Select a start year, end year, and a song attribute and observe the distribution of the song attribute's distribution over the date range. There are interesting differences between certain attributes as you change the start and end years. """ col1, col2 = st.columns(2) with col1: start_year, end_year = st.select_slider("Select a range of years to explore", options=years, value=[years[0], years[-1]]) with col2: year_variable_select = st.selectbox( "Select the variable that you would like to explore", [ "acousticness", "danceability", "duration_ms", "energy", "instrumentalness", "liveness", "loudness", "speechiness", "tempo", "valence" ], key="year_variable", ) with st.container(): after_start = songs["year"] >= start_year before_end = songs["year"] <= end_year between_years = after_start & before_end songs_data = songs.loc[between_years] songs_data = songs_data[["year", year_variable_select]] fig, ax = plt.subplots() ax.hist(songs_data[year_variable_select]) ax.set_ylabel(f"Frequency") ax.set_xlabel(year_variable_select) ax.set_title(f"Frequency of {year_variable_select} for Spotify Song Data {start_year} to {end_year}") st.pyplot(fig)
bd40e322dc72e68c0fe8543aa584d9121328d1bf
crgmaitner/Python
/operations.py
590
3.640625
4
#operations.py nums = [0,1,1,5,4,5,9,7,8,9] def count(nums, n): num = 0 for n in nums: if n == n: num = num + 1 return num def isin(nums, n): for i in nums: if i == n: return True return False def index(nums, n): for i in range(len(nums)): if n == nums[i]: return i return None def reverse(nums): for i in range(len(nums)): nums2 = [] i.reverse() return i print(count(nums, 5)) print(isin(nums, 17)) print(index(nums, 3)) print(reverse(nums))
2ae48e860b5103b19e6e5fdedbf901ad9e7001ef
HankPym/PymTool
/python/Strings.py
215
3.546875
4
# String print("Well \t Hello") # Prints /t as a tab # Raw string print(r"Well \t Hello") # Prints /t as text # Multiline multiLine = """This is a multiline string. It consists of two lines.""" print(multiLine)
ff94fe0fdef367fcb9b5aad970e89863ddb10ba5
green-fox-academy/Unicorn-raya
/week-01/day-5/vertical_flip.py
1,057
4
4
# Vertical flipping # Create a program that can vertically flip a matrix. def matrices_check(mat_1): # mat_1_row = len(mat_1) # mat_2_row = len(mat_2) # if mat_1_row != mat_2_row: # print("dif row") # return False mat_1_col = len(mat_1[0]) for i in mat_1: if len(i) != mat_1_col: print("dif cols in mat1") return False # mat_2_col = len(mat_2[0]) # for i in mat_2: # if len(i) != mat_2_col: # print("dif cols in mat2") # return False # if mat_1_col != mat_2_col: # print("dif cols") # return False return True def mat_vartical_flip(mat): row = len(mat) col = len(mat[0]) for row_index in range(row): for col_index in range(col//2): mat[row_index][col_index],mat[row_index][row-1-col_index] = mat[row_index][row-1-col_index],mat[row_index][col_index] return mat mat1 = [[1,2,3,4,5],[5,4,3,2,1]] mat2 =[[1,2,3,4],[4,3,2,1]] print(mat_vartical_flip(mat1)) print(mat_vartical_flip(mat2))
2dd6b979fb19fa0288fd44bcf8c571581ccc7d35
moontree/leetcode
/version1/1219_Path_with_Maximum_Gold.py
3,268
4.3125
4
""" In a gold mine grid of size m * n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty. Return the maximum amount of gold you can collect under the conditions: Every time you are located in a cell you will collect all the gold in that cell. From your position you can walk one step to the left, right, up or down. You can't visit the same cell more than once. Never visit a cell with 0 gold. You can start and stop collecting gold from any position in the grid that has some gold. Example 1: Input: grid = [[0,6,0],[5,8,7],[0,9,0]] Output: 24 Explanation: [[0,6,0], [5,8,7], [0,9,0]] Path to get the maximum gold, 9 -> 8 -> 7. Example 2: Input: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]] Output: 28 Explanation: [[1,0,7], [2,0,6], [3,4,5], [0,3,0], [9,0,20]] Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7. Constraints: 1 <= grid.length, grid[i].length <= 15 0 <= grid[i][j] <= 100 There are at most 25 cells containing gold. """ class Solution(object): def getMaximumGold(self, grid): """ :type grid: List[List[int]] :rtype: int """ r, c = len(grid), len(grid[0]) directions = [[-1, 0], [1, 0], [0, -1], [0, 1]] def helper(si, sj): used = [[0 for _ in range(c)] for _ in range(r)] used[si][sj] = 1 res = [0] def dfs(i, j, v, res): res[0] = max(res[0], v) for di, dj in directions: ni, nj = di + i, dj + j if 0 <= ni < r and 0 <= nj < c and grid[ni][nj] and not used[ni][nj]: used[ni][nj] = 1 dfs(ni, nj, v + grid[ni][nj], res) used[ni][nj] = 0 dfs(si, sj, grid[si][sj], res) return res[0] res = 0 for i in range(r): for j in range(c): if grid[i][j]: v = helper(i, j) if v > res: res = v return res examples = [ { "input": { "grid":[ [0, 6, 0], [5, 8, 7], [0, 9, 0] ], }, "output": 24 }, { "input": { "grid": [ [1, 0, 7], [2, 0, 6], [3, 4, 5], [0, 3, 0], [9, 0, 20] ], }, "output": 28 }, { "input": { "grid": [ [1, 0, 7, 0, 0, 0], [2, 0, 6, 0, 1, 0], [3, 5, 6, 7, 4, 2], [4, 3, 1, 0, 2, 0], [3, 0, 5, 0, 20, 0] ], }, "output": 60 }, ] import time if __name__ == '__main__': solution = Solution() for n in dir(solution): if not n.startswith('__'): func = getattr(solution, n) print(func) for example in examples: print '----------' start = time.time() v = func(**example['input']) end = time.time() print v, v == example['output'], end - start
082fb1a89a7cb02ffc700733a63dce0825b0d231
projectinnovatenewark/csx
/Students/Semester1/reviews/4_additional_reviews/6_condtionals_review.py
1,068
4.1875
4
# TItle: Conditionals # Conditionals are used to determine if certain blocks of code will run or not. Below are a few # examples of the different types of conditionals statements: num1 = 40 num2 = 0 num3 = 40 if (num1 == num3): # This is an if statement. It executes exactly as it reads. #"If something is true, then execute some code." print(f"num1 is equal to num3") elif (num2 < 0): # This is an elif statement. elif statements will only run when all above if # statements are false. Like an if statement, elif statements test on a condition. print(f"num2: {num2} is a negative number") else: # This is an else statement. This will only execute if all other conditions are not met. print("None of the above were true!") # Python supports the usual logical conditions from mathematics: # == : equal to # != : is not equal to # > : greater than # >= : greater than or equal to # < : less than # <= : less than or equal to # TODO: Hey Teacher, change around the values of the above variable to achieve different outcomes.
10d9b5b3dfbeac1c78e8ad7cef15919e44cd2172
kljushin/cursor_homeworks
/hw13/hw13_task1.py
653
3.796875
4
# 1. Write the method that return the number of threads currently in execution. # Also prepare the method that will be executed with threads and run during the first method counting. from threading import Thread import time import random def some_func(delay): time.sleep(delay) if __name__ == '__main__': threads = [Thread(target=some_func, daemon=True, args=(random.randint(5, 10),))for _ in range(10)] for thread in threads: thread.start() while any([t.is_alive() for t in threads]): print(f'{[t.is_alive() for t in threads].count(True)} threads is alive') time.sleep(1) print('All threads complete')
5c3fca85ea743f5419e74871b1cc570fb693a212
qh4321/1_python_crash_course
/Chapter_6/pizza.py
1,211
3.609375
4
## pizza = { 'crust' : 'thick', 'toppings' : ['mushrooms', 'extra cheese'], } print('You ordered a ' + pizza['crust'] + '-crust pizza with the following toppiongs:') for topping in pizza['toppings']: print('\t' + topping) ## favorite_languages = { 'Jelly' : ['python', 'r', 'C'], 'lala' : ['c'], 'lili' : ['C++', 'java'], 'phil' : ['lango', 'ruby', 'matlab'], } for name, languages in favorite_languages.items(): if len(languages) == 1: print('\n' + name.title() + "'s favoruite language is:") else: print('\n' + name.title() + "'s favorite languages are:") for language in languages: print('\t' +language.title()) ## many_users users = { 'aeinstein' : { 'first' : 'albert', 'last' : 'einstein', 'location' : 'princeton', }, 'mcurie' : { 'first' : 'marie', 'last' : 'curie', 'location' : 'paris', }, } for username, user_info in users.items(): print("\nUsername: " + username) full_name = user_info['first'] + ' ' + user_info['last'] location = user_info['location'] print('\tFull name: ' + full_name.title()) print('\tLocation: ' + location.title())
3cf69357dce45f6d57d142947a4063c8d9147386
peesarimahesh/python_learning
/loops_1.py
2,088
3.90625
4
# Question 1: Accept two int values from the user and return their product. # If the product is greater than 1000, then return their sum val = 1 val1 = 0 while True: num = input('Enter the values:') if num == 'done': break try: num1 = float(num) except: print('Invalid input') continue val = val * int(num) val1 = val1 + int(num) if val > 1000: val = val1 print(val) # Question 2: Given a range of numbers. Iterate from o^th number to the end number # and print the sum of the current number and previous number j = 0 for i in [1,2,3,4,5,6]: j = j + i print(j) # Question 3: Accept string from the user and display only those characters # which are present at an even index str = input('Enter a string value:') #cnt = len(str) for i,c in enumerate(str): if i % 2 == 0: #print(i) print(c) # solution2, copied for i in range(0, len(str), 2): print(str[i]) # Question 4: Given a string and an int n, remove characters from string starting # from zero up to n and return a new string str = input('Enter a string value:') num = input('Enter a string value:') val = '' for i in range(len(str)): if i >= int(num): val = val + str[i] print(val) # Question 5: Given a list of ints, return True if first and last number of a list is same num = input('Enter a number value:') if num[0] == num[len(num)-1]: print('True') # Question 6: Given a list of numbers, Iterate it and print only those numbers which are divisible of 5 l1 = [5,7,9,10,11,13,15,17,20,21,25,30] for i in range(len(l1)-1): if l1[i] % 5 == 0: print(l1[i]) # Question 7: Return the number of times that the string “Emma” appears anywhere in the given string str = "Emma is a good developer. Emma is also a writer." print(str.count("Emma")) # Question 8: Print the following pattern #1 #2 2 #3 3 3 #4 4 4 4 #5 5 5 5 5 for i in range(6): for j in range(i): print(i, end = ' ') print("") # Question 9: Reverse a given number and return true if it is the same as the original number
487b9a5b9b154ebaa3b08809aa1ea03bf37590a7
laohur/EasyLeetcode
/hard/Design.py
8,015
4.125
4
1. LRU Cache Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item. The cache is initialized with a positive capacity. Follow up: Could you do both operations in O(1) time complexity? Example: LRUCache cache = new LRUCache( 2 /* capacity */ ); cache.put(1, 1); cache.put(2, 2); cache.get(1); // returns 1 cache.put(3, 3); // evicts key 2 cache.get(2); // returns -1 (not found) cache.put(4, 4); // evicts key 1 cache.get(1); // returns -1 (not found) cache.get(3); // returns 3 cache.get(4); // returns 4 from typing import List class Node: def __init__(self,key=0,val=0): self.key=key self.val=val self.prev=None self.next=None class LRUCache: def __init__(self, capacity: int): self.capacity=capacity self.dict=dict() self.head,self.tail=Node(),Node() self.head.next=self.tail self.tail.prev=self.head def _remove(self,node): node.next.prev=node.prev node.prev.next=node.next def _append(self,node): self.tail.prev.next=node node.prev=self.tail.prev self.tail.prev=node node.next=self.tail def get(self, key: int) -> int: if key not in self.dict: return -1 node=self.dict[key] self._remove(node) self._append(node) return node.val def put(self, key: int, value: int) -> None: if key not in self.dict: node=Node(key,value) self.dict[key]=node else: node=self.dict[key] node.val=value self._remove(node) self._append(node) if len(self.dict)>self.capacity: key=self.head.next.key node=self.dict[key] del self.dict[key] # self.dict.pop(key) self._remove(node) # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value) if __name__ == '__main__': lru= LRUCache(2) lru.put(1,1) lru.put(2,2) lru.get(1) lru.put(3,3) lru.get(2) orderdict movetoend 2. Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. Example: Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // returns true trie.search("app"); // returns false trie.startsWith("app"); // returns true trie.insert("app"); trie.search("app"); // returns true Note: You may assume that all inputs are consist of lowercase letters a-z. All inputs are guaranteed to be non-empty strings. class Trie: def __init__(self): """ Initialize your data structure here. """ self.children = [None] * 26 self.tail=False def insert(self, word: str) -> None: """ Inserts a word into the trie. """ if len(word) == 0: return idx=ord(word[0])-ord('a') if not self.children[idx]: self.children[idx] = Trie() if len(word)==1: self.children[idx].tail=True else: self.children[idx].insert(word[1:]) def search(self, word: str) -> bool: """ Returns if the word is in the trie. """ if len(word)==0: return True idx=ord(word[0])-ord('a') if not self.children[idx]: return False if len(word) == 1: return self.children[idx].tail return self.children[idx].search(word[1:]) def startsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ word=prefix if len(word) == 0 : return True idx=ord(word[0])-ord('a') if self.children[idx] is None: return False return self.children[idx].startsWith(word[1:]) # Your Trie object will be instantiated and called as such: # obj = Trie() # obj.insert(word) # param_2 = obj.search(word) # param_3 = obj.startsWith(prefix) 3.Flatten Nested List Iterator Given a nested list of integers, implement an iterator to flatten it. Each element is either an integer, or a list -- whose elements may also be integers or other lists. Example 1: Input: [[1,1],2,[1,1]] Output: [1,1,2,1,1] Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]. Example 2: Input: [1,[4,[6]]] Output: [1,4,6] Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]. # """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ #class NestedInteger: # def isInteger(self) -> bool: # """ # @return True if this NestedInteger holds a single integer, rather than a nested list. # """ # # def getInteger(self) -> int: # """ # @return the single integer that this NestedInteger holds, if it holds a single integer # Return None if this NestedInteger holds a nested list # """ # # def getList(self) -> [NestedInteger]: # """ # @return the nested list that this NestedInteger holds, if it holds a nested list # Return None if this NestedInteger holds a single integer # """ class NestedIterator: def __init__(self, nestedList: [NestedInteger]): self.list=[] self.flatten(nestedList) self.pos=0 print(self.list) def flatten(self,nestedList: [NestedInteger]): for lst in nestedList: if lst.isInteger(): self.list.append(lst.getInteger()) else: self.flatten(lst.getList()) def next(self) -> int: re=self.list[self.pos] self.pos+=1 return re def hasNext(self) -> bool: return self.pos<len(self.list) # Your NestedIterator object will be instantiated and called as such: # i, v = NestedIterator(nestedList), [] # while i.hasNext(): v.append(i.next()) 3.Find Median from Data Stream Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value. For example, [2,3,4], the median is 3 [2,3], the median is (2 + 3) / 2 = 2.5 Design a data structure that supports the following two operations: void addNum(int num) - Add a integer number from the data stream to the data structure. double findMedian() - Return the median of all elements so far. Example: addNum(1) addNum(2) findMedian() -> 1.5 addNum(3) findMedian() -> 2 Follow up: If all integer numbers from the stream are between 0 and 100, how would you optimize it? If 99% of all integer numbers from the stream are between 0 and 100, how would you optimize it? import bisect class MedianFinder: def __init__(self): """ initialize your data structure here. """ self.list=[] def addNum(self, num: int) -> None: pos=bisect.bisect_left(self.list,num) self.list.insert(pos,num) # print(num,pos,self.list) def findMedian(self) -> float: i=len(self.list)//2 j= (len(self.list)-1)//2 # print(i,j,len(self.list)) return (self.list[i]+self.list[j])/2 # Your MedianFinder object will be instantiated and called as such: # obj = MedianFinder() # obj.addNum(num) # param_2 = obj.findMedian()
8ba639d2a42c654cb4bdc29ac279796e34272af3
WillemJan/Misc
/xbox/background.py
3,144
3.515625
4
#!/usr/bin/python2.4 # -*- coding: utf-8 -*- ''' Willem Jan Faber (http://www.fe2.nl) ''' # System lib imports import os import random import urllib # PyGame imports from pygame import * from pygame.locals import * # Own library imports from config import * class Background: """ Load new images from disk, scale them and show the weather from time to time. """ # New background image new = None # Current background image current = None # Counter to show the wearher in the Netherlands counter = 0 # Interval to show the weather map of the Netherlands next_wearher_show = int(random.random()*10) + 5 def __init__(self): # Get a list of images from disk self.background_images = os.listdir(BACKGROUND_IMAGES) # Load the image from disk and scale it self.current = self._load_new() self.current = self.current.convert_alpha() self.current = self._aspect_scale(self.current, (SCREEN_WIDTH-100, SCREEN_HEIGHT-100)) def _load_new(self): # Try to load the new image image_random = random.choice(self.background_images) try: image_data = image.load(os.path.join(BACKGROUND_IMAGES, image_random)) except error: self.background_images.remove(image_random) self._load_new() return image_data def get_new(self): """ Get new images from disk, and scale them, while keeping the aspect. """ self.counter += 1 if self.counter == self.next_wearher_show: # Set the next interval to show the weather next_wearher_show = int(random.random()*10) + 5 # Fether the dutch weather map data = urllib.urlopen(KNMI_URL).read() # Write weather map to disk fh = open('/tmp/weer.png', 'wb') fh.write(data) fh.close() self.new = self._load_new() else: # Get a random image from disk self.new = self._load_new() self.new = self.new.convert() self.new = self._aspect_scale(self.new, (SCREEN_WIDTH, SCREEN_HEIGHT)) print self.new.get_size() def swap(self): self.current = self.new def _aspect_scale(self, img,(bx,by)): """ Got this routine from: http://www.pygame.org/pcr/transform_scale/aspect_scale.py """ ix,iy = img.get_size() if ix > iy: # fit to width scale_factor = bx/float(ix) sy = scale_factor * iy if sy > by: scale_factor = by / float(iy) sx = scale_factor * ix sy = by else: sx = bx else: # fit to height scale_factor = by / float(iy) sx = scale_factor * ix if sx > bx: scale_factor = bx/float(ix) sx = bx sy = scale_factor * iy else: sy = by return transform.scale(img, (sx,sy))
64c5048869629500402e42b0678bc797ddd031ef
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4501/codes/1716_2508.py
198
3.5625
4
num = int(input("No. de aproximacao: ")) cont = 1 a = 3 while(cont < num): den = (cont * 2) * (cont * 2 + 1) * (cont * 2 + 2) a = a + (-1)**(cont + 1) * 4 / den cont = cont + 1 print(round(a, 8))
898a105069818e5ec2872c6adf32bd0a06846771
xiaosean/leetcode_python
/Q919_Complete-Binary-Tree-Inserter.py
1,599
4.09375
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class CBTInserter: def _bfs(self, node): if node is None: return None for _node in [node.left, node.right]: if _node: self.node_list += [_node] if node.right is None and self.empty_index is None: self.empty_index = self.traverse_index def __init__(self, root: TreeNode): if root is None: return None self.traverse_index = 0 self.empty_index = None self.node_list = [root] self.traverse_index = 0 while self.traverse_index < len(self.node_list): self._bfs(self.node_list[self.traverse_index]) self.traverse_index += 1 if self.empty_index is None: self.empty_index = 0 return None def insert(self, v: int) -> int: parent_node = self.node_list[self.empty_index] new_node = TreeNode(v) self.node_list += [new_node] if parent_node.left is None: parent_node.left = new_node else: parent_node.right = new_node self.empty_index += 1 return parent_node.val def get_root(self) -> TreeNode: return self.node_list[0] # Your CBTInserter object will be instantiated and called as such: # obj = CBTInserter(root) # param_1 = obj.insert(v) # param_2 = obj.get_root()
c48db8a917183c33cb32301047a09070c042f38c
DTavaszi/Excercise
/Excercise/Excercise.py
1,361
3.890625
4
import shlex def largestCombination(): n, k = shlex.split(input('Enter n, k: ')) n = int(n) k = int(k) stringer = input('Enter the string composed of "a" and "b": ') arr = [] temp = stringer[0] count = 0 for i in range(0, len(stringer), 1): if(temp == stringer[i]): count+=1 else: arr.append(count) count = 1 temp = stringer[i] arr.append(count) print("") print(arr) max = 0 tempi = 0 for i in range(0, len(arr)-1, 1): tempk = k j = i+1 count = arr[i] while(tempk >= 0 and j <= len(arr)-1): if(i%2 == j%2): count+=arr[j] #print("% " + str(j) + " " + str(count) + " " + str(tempk)) else: if(arr[j] <= tempk): count+=arr[j] tempk-=arr[j] #print(str(j) + " " + str(count) + " " + str(tempk)) else: break j+=1 if(count > max): max = count tempi = i print(str(max) + " - " + str(tempi)) #abbaabbaababbaaababa #abbaabbaababbaaabbbb def main(): largestCombination() main()
bc5fbb05caa8c2228097b0fa81935bca65bdc9da
Asperas13/leetcode
/problems/290.py
536
3.71875
4
class Solution: def wordPattern(self, pattern: str, str: str) -> bool: pattern_to_word = {} words = str.split(' ') if len(words) != len(pattern) or len(set(words)) != len(set(pattern)): return False size = len(words) for i in range(size): if pattern[i] not in pattern_to_word: pattern_to_word[pattern[i]] = words[i] else: if pattern_to_word[pattern[i]] != words[i]: return False return True
107b282fdefc7d16383230a226201ede81129712
Glavrab/quote_bot
/library.py
364
3.5625
4
import json import random import codecs def get_a_quote() -> str: """Get a random quote from a json file""" filename = 'quotes.json' with open(filename): file_with_quotes = json.load(codecs.open(filename, 'r', 'utf-8-sig')) number_of_quote = random.randint(0, 6) quote = file_with_quotes[number_of_quote] return quote
d29d1c4f18b9c68c27f88c65aecbd495ac49d837
sprumin/Mailprogramming
/2019-04-23.py
343
3.796875
4
# n 번째 피보나치 수를 구하는 프로그램을 작성하시오. def fibonacci(n): f_list = [0 for i in range(n + 1)] f_list[1] = 1 for i in range(2, n + 1): f_list[i] = f_list[i - 1] + f_list[i - 2] return f_list[n] def main(): print(fibonacci(int(input()))) if __name__ == "__main__": main()
9d563b4a7762c8276a6ce41960fa783f595a834e
wocoburguesa/Python_the_Hard_Way
/ex33.py
497
4.125
4
i = 0 numbers = [] while i < 6: print "At the top i is %d" % i numbers.append(i) i += 1 print "Numbers now: ", numbers print "At the bottom i is %d" % i print "The numbers: ", for num in numbers: print num, print def loop(n, inc): nums = [] count = 0 while count < n: nums.append(count) count += inc return nums print loop(int(raw_input("Ingrese un numero para loopear: ")), int(raw_input("Ingrese un incremento: ")))
90e0dd3e0bf0a8ed162da150e4e1424b84dec604
kalyan-ch/SltnsCrkdCpp
/CdFtsIntQ/findNveSbStr.py
652
3.765625
4
def findSubstrings(words, parts): res = [] for w in words: match = "" lngst = 0 pos = len(w) for p in parts: if p in w: if len(p) > lngst or (len(p) == lngst and w.index(p) < pos): lngst = len(p) pos = w.index(p) match = p if lngst > 0: ind = w.index(match) res.append(w[0:ind]+"["+match+"]"+w[ind+len(match):]) else: res.append(w) return res if __name__ == '__main__': print findSubstrings(["Apple","Melon","Watermelon","Orange"],["a","mel","lon","el","An"])
49a25dd9a402c49e7b9d7f30cb8ae86edf987e1e
zebratesting/Python
/PythonBasic/string.py
950
4.34375
4
""" name="yam" my_new_name="Tester" my_info="I started my career" print(f'my name is:{name} \nmy new name is: {my_new_name}\nmy information is:{my_info}') space is also one character str="Python scripting" print(str[0:9]) print(str[::-1]) print(len(str)) print(str[-1]) str1 ="is better" print(str+" "+ str1)--Concitation x="hiL" print(dir(x)) print(x.swapcase()) print(x.title()) print(x.capitalize()) print(x.casefold()) str="Python" print(str.startswith("P")) print(str.islower()) print(str.istitle()) print(str.istitle()) print(str.isnumeric()) help(str) #Join menthod for strings x="python" print("\n".join(x)) print("\t".join(x)) print("*".join(x)) print(x) #Center for strings x="m a looser" print(x.center(20)) print(x.center(20,"y")) print(x.strip()) print(x.strip('looser')) print(x.lstrip('m')) print(x.split()) """ x="iam a looser" print(x.find("i",0)) print(x.index('l',3,9)) print(x.find("q")) print(x.index("q"))
c324388d5b746c8846711e8412f731100ad4324a
nicegood123/traya-python-tkinter
/MainForm.py
624
3.625
4
from tkinter import Tk, Frame, PhotoImage, Label import InfoFrame, TopFrame, ButtonsFrame, ContentFrame def setMainForm(): window = Tk() window.title("Athlete Information System") window.configure(background="#880e0e", width=840, height=375) window.resizable(0,0) logoFrame = Frame(window, width="245", height="70", bg="#880e0e") logoFrame.place(x=0, y=1) img_logo = PhotoImage(file="umlogo.png") Label(logoFrame, image=img_logo, bd=0).place(x=43, y=5) InfoFrame.setInfoFrame() TopFrame.setTopFrame() ButtonsFrame.setButtonsFrame() ContentFrame.setContentFrame() window.mainloop() #a56868 #880e0e #0a101a
2f7baa4c27258687ec64a18bbea1fb4c73b7f7f2
alepeteporico/Ejercicio_XML_JSON
/programa_json.py
1,235
3.890625
4
import json with open("movies.json") as fichero: datos=json.load(fichero) while True: print("================================================================================") print("1.Listar el título, año y duración de todas las películas.") print("2.Mostrar los títulos de las películas y el número de actores/actrices que tiene cada una.") print("3.Mostrar las películas que contengan en la sinopsis dos palabras dadas.") print("4.Mostrar las películas en las que ha trabajado un actor dado.") print("5.Mostrar el título y la url del póster de las tres películas con una media de puntuaciones más alta y lanzadas entre dos fechas dadas.") print("6.Salir") print("================================================================================") elec=int(input("Elige una opción: ")) print("") if elec==6: break elif elec==1: lista_peliculas=[] lista_año=[] lista_peliculas=(datos.get("title")) lista_año=(datos.get("year")) for pelicula in lista_peliculas: print("-",pelicula) for año in lista_año: print("-",año) print("--------------")
b23631548a14b8cbb8bbea523fc26d19e7385027
twtrubiks/python-notes
/dataclasses_tutorial.py
993
4.03125
4
# ref. https://docs.python.org/3/library/dataclasses.html from dataclasses import dataclass, field class InventoryItemOLD: def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0): self.name = name self.unit_price = unit_price self.quantity_on_hand = quantity_on_hand self.total = self.unit_price * self.quantity_on_hand def __repr__(self) -> str: return f"{self.__class__.__name__}(name='{self.name}', unit_price={self.unit_price}, quantity_on_hand={self.quantity_on_hand}, total={self.total})" @dataclass(frozen=False) class InventoryItem: """Class for keeping track of an item in inventory.""" name: str unit_price: float quantity_on_hand: int = 0 total: float = field(init=False) def __post_init__(self): self.total = self.unit_price * self.quantity_on_hand if __name__ == "__main__": print(InventoryItemOLD("twtrubiks", 100, 2)) print(InventoryItem("twtrubiks", 100, 2))
45d541b04e37d4953e56cce0d62b1cb293722147
JKFjkf/FaceTest
/Test_11/test_1.py
386
3.578125
4
#Python-遍历列表时删除元素的正确做法 #遍历在新在列表操作,删除时在原来的列表操作 a = [1,2,3,4,5,6,7,8] print(id(a)) print(id(a[:])) for i in a[:]: if i > 5: pass else: a.remove(i) print(a) print('-----------') print(id(a)) #filter a=[1,2,3,4,5,6,7,8] print(id(a)) b = filter(lambda x: x>5,a) print(list(b)) print(id(b))
119dfeb3df60dc4eb9ca6048b69538ef9a28f289
Ruchithaakula/Python_Assignment9
/Assignment9_empty or not.py
272
3.671875
4
#!/usr/bin/env python # coding: utf-8 # In[2]: def Enquiry(lis1): if len(lis1) == 0: return 0 else: return 1 lis1 = [1,3,5] if Enquiry(lis1): print ("The list is not empty") else: print("Empty List") # In[ ]:
3521b6bf98febaacfd7b547d6bb7287b2967906b
LyricLy/python-snippets
/tuple_linkedlist.py
542
3.59375
4
#!/usr/bin/env python3 # encoding: utf-8 import functools import typing def make_node(data, next=None): if next is None: return (data,) return (data,next) nums = make_node(0, make_node(1, make_node(2))) def linkedlist(data: typing.Sequence): if not data: return () if len(data) == 1: return make_node(data[0]) return make_node(data[0], linkedlist(data[1:])) def linkedlist(data: Iterable): if not data: return () data = iter(data) return make_node(next(data), data) linkedlist = lambda data: reduce(make_node, data, ())
aaa6462dbac18a20c1a3150045f6a77c24f27382
BooYang-CS/python3_code
/11/11_5.py
1,921
4.1875
4
#itertools #python 的内建模块itertools提供了非常有用的用于操作迭代对象的函数 ''' import itertools natuals=itertools.count(1) for n in natuals: print(n) ''' #count()会创建一个无限的迭代器,所以上述代码会打印出自然数序列,根本停不下来,只能按ctrl+C退出 #cycle()会把传入的一个序列无限重复下去 ''' import itertools cs=itertools.cycle('ABC')#注意字符串也是序列的一种 for c in cs: print(c) ''' #同样也会无限循环下去 #repeat()负责把一个元素无限重复下去,不过如果提供第二个参数就可以限定重复次数 import itertools ns=itertools.repeat('A',3) for n in ns: print(n) #无限序列只有在for迭代时才会无限迭代下去,如果只是创建一个迭代对象,它不会事先把无限个元素生成出来,事实上也不可能在内存中创建无限个元素 #无限序列虽然可以无限迭代下去,但是通常我们会通过takewhile()等函数根据条件判断来截取出一个有限的序列 import itertools natuals=itertools.count(3)#创建从3开始的一个无限迭代器 ns=itertools.takewhile(lambda x:x<10,natuals) print(list(ns)) #chain()可以把一组迭代对象串联起来,形成一个更大的迭代器 for c in itertools.chain('ABC','XYZ'): print(c) #groupby()把迭代器中相邻的重复元素挑出来放在一起 for key,group in itertools.groupby('AAABBBCCCAAAS'): print(key,list(group)) ''' A ['A', 'A', 'A'] B ['B', 'B', 'B'] C ['C', 'C', 'C'] A ['A', 'A', 'A'] S ['S'] 实际上挑选规则是通过函数完成的,只要作用于函数的两个元素返回的值相等,这两个元素就被认为是在一组的,而函数返回值作为组的key。 如果我们要忽略大小写分组,就可以让元素'A'和'a'都返回相同的key ''' for key,group in itertools.groupby('AabbBcCcAaaS',lambda c:c.upper()): print(key,list(group))
333d04713abd70a71ed7f9eedafc72a742d2e75f
PompeyWayner/ou
/TMA02/TM112_TMA02_Q3_WS2343.py
605
4
4
# Compute the range of toy sales # Input: a list of toy sales, positive integers toy_sales = [7, 6, 0, 10] # Maximum possible range # Sub-problem: find the lowest and highest sales lowest = toy_sales[0] highest = toy_sales[0] for sales in range(1, len(toy_sales)): if toy_sales[sales] < lowest: lowest = toy_sales[sales] elif toy_sales[sales] > highest: highest = toy_sales[sales] # Sub-problem: compute the range of highest and lowest sales range = highest - lowest # Output: range, integer, maybe zero print("The range of the toy sales is",highest, "-", lowest, "=", range)
67bec57b73ca4f18e410ddc40653ba9de31357b3
inkyu0103/BOJ
/오답 문제 복습/same sum.py
995
3.875
4
""" 두 큐의 합을 같게 만들자. 1. 합을 비교한다. 2. 큰 쪽 큐의 원소를 하나 뽑는다. 3. 작은쪽에 넣는다. 4. 같을 때까지 반복한다. 언제 만들 수 없을까? 가장 큰 원소가 나머지의 합보다 큰 경우 """ from collections import deque def solution(queue1, queue2): total = queue1 + queue2 if sum(total) - max(total) < max(total): return -1 answer = 0 deque1 = deque(queue1) deque2 = deque(queue2) print(deque1, deque2) deque1_sum, deque2_sum = sum(deque1), sum(deque2) while deque1_sum != deque2_sum: if deque1_sum > deque2_sum: deque2.append(deque1.popleft()) deque2_sum += deque2[-1] deque1_sum -= deque2[-1] elif deque1_sum < deque2_sum: deque1.append(deque2.popleft()) deque1_sum += deque1[-1] deque2_sum -= deque1[-1] answer += 1 return answer solution([3, 2, 7, 2], [4, 6, 5, 1])
65559f28577bd58c6e963b58f8230a4537472dc5
sindretallaksrud/INF200-2019-Exersices
/exersices/Ex05/myrand.py
2,461
4
4
# -*- coding: utf-8 -*- __author__ = 'Sindre Tallaksrud' __email__ = 'sindrtal@nmbu.no' class LCGRand: def __init__(self, seed): self.seed = seed self.count = 0 self.r = [0] def rand(self): self.r[0] = self.seed self.r.append(0) a = 7**5 m = 2**31-1 self.r[self.count + 1] = a * self.r[self.count] % m self.count += 1 return self.r[self.count] def random_sequence(self, length): return RandIter(self, length) def infinite_random_sequence(self): """ Generate an infinite sequence of random numbers. Yields ------ int A random number. """ while True: yield self.rand() class RandIter: def __init__(self, random_number_generator, length): """ Arguments --------- random_number_generator : A random number generator with a ``rand`` method that takes no arguments and returns a random number. length : int The number of random numbers to generate """ self.generator = random_number_generator self.length = length self.num_generated_numbers = None def __iter__(self): if self.num_generated_numbers is not None: raise RuntimeError() self.num_generated_numbers = 0 return self """ Initialise the iterator. Returns ------- self : RandIter Raises ------ RuntimeError If iter is called twice on the same RandIter object. """ def __next__(self): """ Generate the next random number. Returns ------- int A random number. Raises ------ RuntimeError If the ``__next__`` method is called before ``__iter__``. StopIteration If ``self.length`` random numbers are generated. """ if self.num_generated_numbers is None: raise RuntimeError() if self.num_generated_numbers == self.length: raise StopIteration self.num_generated_numbers += 1 return self.generator.rand() generator = LCGRand(1) for rand in generator.random_sequence(10): print(rand) i = 0 while i < 100: rand = generator.infinite_random_sequence() print(f'The {i}-th random number is {next(rand)}') i += 1
0b12608f5c7049258c3083d2c3f27215881ee078
krwenholz/FerryTimeliness
/src/wsdot_data_request_reader.py
2,859
3.8125
4
import time import csv from datetime import datetime """ This file reads in data from the WSDOT Vessel Track data to store in a PostgreSQL database. A popular choice (used here) is to write the data into files with vessel, departure, arrival, eta_departure/arrival, actual_departure/arrival, and date. Times are stored as seconds from the start of the day (00:00). The date is actually stored as a date. """ def make_time(daytime): """ Use just the time of day to make an integer value for the time. """ return time.mktime(time.strptime('1970-01-01 ' + daytime, '%Y-%m-%d %H:%M')) - 28800 def write_to_database(datas, data_file): """ Takes in a data reader for the csv file and puts it all in a table. """ FMT = '%m/%d/%Y %H:%M' FMT_DATE = '%m/%d/%Y' print 'Preparing to write data for ', datas.next() csv_string = "%s, %s, %s, %d, %d, %d, %d, %s\n" failed_data = 0 bad_time = 0 write_attempts = 0 data_file.write('vessel, departing, arriving, scheduled_departure, actual_departure, initial_eta, actual_arrival, date\n') for row in datas: try: if (datetime.strptime(row[4], FMT) - datetime.strptime(row[7], FMT)).total_seconds() > 0: # Departure - Arrival > 0 is bad bad_time += 1 try: # First, we tackle the departure data query_data = (row[0], row[1], row[2], make_time(row[3].split(' ')[1]), make_time(row[4].split(' ')[1]), make_time(row[6].split(' ')[1]), make_time(row[7].split(' ')[1]), datetime.strptime(row[8], FMT_DATE).date()) if not 'NULL' in query_data: # We don't want to write NULLs into our final data write_attempts += 1 data_file.write(csv_string % query_data) #cur.execute(query_string, query_data) except: # Something went wrong, probably a null failed_data += 1 except: # Probably a NULL in the time failed_data += 1 print "Found ", bad_time, " lines of bad time data. (not written)" print "Found ", failed_data, " lines of bad data. (not written)" print "Attempted to write ", write_attempts, " lines of data." data_file.close() # conn.commit() # cur.close() # conn.close() ########## # Now make the nice looking calls to read data and such. ########## fname = '../Data/data_request_October2012.csv' reader = csv.reader(open(fname, 'rb')) data_dir = '../Data/' data_file = open(data_dir + 'ferry_data.csv', 'w') write_to_database(reader, data_file)
2fb48b258d218b93ef1872314cfce92bc352a5dd
santoshbebe/Pylearning
/LearningPrograms/Functions1.py
302
3.78125
4
def my_print_var_args(*args): str1 = "" for ele in args: str1 = str1 + ' ' +str(ele) print(str1) def my_print(l1): print(l1) str1 = "" for ele in l1: str1 = str1 + ' ' + str(ele) print(str1) my_print((1,"Python", 3.14)) my_print_var_args(1,"Python", 3.14)
0353aff7b75eea7357ff94693318c8bc56c391f0
taison2000/Python
/Decorators/Decorators2.py
2,414
4.34375
4
#!C:\Python34\python.exe #!/Python34/python #!/usr/bin/python # -*- coding: utf-8 -*- ## ---------------------------------------------------------------------------- """ Decorator ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A decorator is a function that takes one function as input and returns another function. Note: - A function could have more than one decorator. """ import os import time ##----------------------------------------------------------------------------- ''' decorator function ''' def document_it( func ): def new_function( *args, **kwargs ): print('Running function: ', func.__name__) print('Positional arguments: ', args) print('Keyword arguments: ', kwargs) result = func( *args, **kwargs ) print('Result: ', result) return result + 2 return new_function def square_it( func ): def new_function( *args, **kwargs ): result = func( *args, **kwargs ) return result * result return new_function ##----------------------------------------------------------------------------- ## automatically decorator """ Function to test decorator """ @document_it @square_it def add_ints( a, b ): return a + b # reverse the order of decorators @square_it @document_it def add_two( a, b ): return a + b # ----------------------------------------------------------------------------- # Main program - This is the main function # ----------------------------------------------------------------------------- def main(): print() r1 = add_ints(12, 45) print('r1: ', r1) print() r2 = add_two(12, 45) print('r2: ', r2) pass #------------------------------------------------------------------------------ # ----------------------------------------------------------------------------- # Code entry # ----------------------------------------------------------------------------- if __name__ == "__main__": main() ##----------------------------------------------------------------------------- """ Resources: - https://wiki.python.org/moin/Generators """ ##----------------------------------------------------------------------------- """ Note: - No ++ or --, use a+=1 or a-=1 - print ("Variable %d", %Val) print ("Variable %d %d", % (Val1, Val2)) """ ''' 3 single quote string '''
18ae9189e7d169ff3d6601978af140a6f8a14f14
AkshayKumarTripathi/Algorithms-And-Data-Structures
/Day 24 (Dynamic Programming)/word break.py
600
3.640625
4
word = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" record = ["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"] length=len(word) table=[-1]*(length) record=set(record) def solve(i=0): if table[i]!=-1: return table[i] if i==length: return True for k in range(i,length): if word[:k+1] in record and solve(k+1): table[i] = True return True table[i] = False return table[i] print(solve())
136a6aa0c778ac61364395fc5ccc046994d1a2c5
julianalvarezcaro/holbertonschool-higher_level_programming
/0x02-python-import_modules/iwasinalpha.py
125
3.765625
4
#!/usr/bin/python3 def alpha(): for letter in range(65, 91): print("{}".format(chr(letter)), end='') print()
4f3e8017dc6e1001c8673a4bf10856ea4ad4ad00
Lavanya411/phython_fundamentals_b11
/ok.py
324
3.5
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: # In[ ]: # In[21]: class dog: def __init__(self,name,age): self.name=name self.age=age def sit(self): print(f"my dog name is {self.name}") def roll_over(self): print(f"{self.name} is roll over") # In[ ]:
cad187aa9ceaf804146687ee6a648fe925acfb99
mjzac/advent-of-code
/2019/1.py
484
3.8125
4
# https://adventofcode.com/2019/day/1 def get_fuel(mass): return mass // 3 - 2 def get_fuel_with_additional_fuel(mass, total_fuel=0): if mass <= 0: return total_fuel fuel = max(get_fuel(mass), 0) return get_fuel_with_additional_fuel(fuel, total_fuel + fuel) with open("1input.txt") as f: fuel_required = 0 for line in f: module_mass = int(line) fuel_required += get_fuel_with_additional_fuel(module_mass) print(fuel_required)
dbf0379f93ca3b660fbf32a3df0e3e25cf521b6a
hrishikeshtak/Coding_Practises_Solutions
/leetcode/LeetCode-150/Arrays-and-Hashing/1-Two-Sum.py
899
3.9375
4
""" 1. Two Sum Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. """ from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: # hashmap to store (target - nums[i], index) pair hashmap = {} for i, num in enumerate(nums): diff = target - num if diff in hashmap: return [i, hashmap[diff]] hashmap[num] = i if __name__ == '__main__': nums = [2,7,11,15] target = 9 print(f"twoSum: {Solution().twoSum(nums, target)}")
9f47ec422dd89ffac79522bf33c133eebb8eacb9
abigelow-io/python
/logics/middle_element.py
225
3.6875
4
def middle_element(lst): length = len(lst) modifier = int(length/2) if length%2 != 0: return lst[(modifier)] else: lower_mid = lst[(modifier)-1] upper_mid = lst[modifier] return (lower_mid+upper_mid)/2
2fa8aeda6265004d34d47362e05342c75c3f1e7d
bshee/aoc2017
/day1/inverse_captcha_part2.py
414
4.03125
4
#!/usr/bin/env python3 # Consider taking from a file. sequence = input('Input the sequence: ') length = len(sequence) # Would be good to sanity check sequence is numbers and even length but ehhhh. sumDigits = 0 for index, value in enumerate(sequence): nextIndex = (index + length // 2) % length nextValue = sequence[nextIndex] if value == nextValue: sumDigits += int(value) print(sumDigits)
3a65864ffcba59a2db4d8b3e18cddc5c66445693
ehedaoo/Automate
/Collatz_Sequence.py
238
4.125
4
def collatz(ret): if ret%2 == 0: print(ret//2) return (ret//2) elif ret%2 == 1: print(3*ret+1) return (3*ret+1) num = int(input("Enter number: ")) while num != 1: num = collatz(num)
7768db3184fcb6e2253aa8da21bd8f919109c957
mnishiguchi/python_notebook
/MIT6001x/week2/pset1_longestSubstring.py
742
4.25
4
''' Assume s is a string of lower case characters. Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print Longest substring in alphabetical order is: beggh ''' s = raw_input('Type a string of lower case characters: ') longest = '' for i in range(len(s)) : probe = s[i:] prev = '' candidate = '' for char in probe : if char >= prev : candidate = candidate + char prev = char else : break if len(candidate) > len(longest) : longest = candidate print longest
069d5578e35fd2c4a723af83a03852f4417b18d7
edgeworthZ/first_year_log
/Lab_Quiz/sudoku.py
1,599
3.796875
4
def IsSudokuValid(line, cType): if(sum(line[1]) == sum(set(line[1]))): # This line is safe return True else: # Something is wrong, find duplicate numbers' locations for n in [1,2,3,4,5,6,7,8,9]: if line[1].count(n) > 1: # Found duplicate for i in range(len(line[1])): # Get index of each duplicate number if line[1][i] == n: if cType == 'row': #print('row:',line[0],'col:',i+1) res.add(chr(ord('A')-1+line[0])+str(i+1)) elif cType == 'col': res.add(chr(ord('A')-1+(i+1))+str(line[0])) return False def CheckSudoku(grid): wrongRows = [row for row in enumerate(grid, 1) if not IsSudokuValid(row, 'row')] # Check Rows transposedGrid = list(zip(*grid)) wrongCols = [col for col in enumerate(transposedGrid, 1) if not IsSudokuValid(col, 'col')] # Check Cols squares = [] for i in range(0,9,3): # Check Squares for j in range(0,9,3): square = list(col for rows in grid[i:i+3] for col in rows[j:j+3]) #print(square) squares.append(square) wrongSquares = [square for square in enumerate(squares, 1) if not IsSudokuValid(square, 'square')] return not(wrongRows or wrongCols or wrongSquares) grid = list() res = set() for i in range(9): grid.append([int(x) for x in input().split()]) if CheckSudoku(grid): print('Correct!') else: print('Incorrect!') print(*sorted(res))
595c7936e359039fe17a5047b1e158b3030aa09b
sbghub/library-of-string-functions
/string_prac.py
6,604
4
4
# -*- coding: utf-8 -*- """ Created on Sun Jul 24 11:13:33 2016 @author: Somak """ import numpy as np import unittest #(1.) checks if all the characters in a string are unique def isCharUnique(word): #tries to convert word to a string if it isn't one if type(word) is not str: try: word = str(word) except: return "error: not a string and couldn't convert to one" elif len(word)==1: return True #runs through each letter and checks if it matches any letters after it #assumes it's True and returns False if a letter matches a letter after it i = 0 while i < len(word)/2 + 1: j = 1 while j < len(word): if i==j: j += 1 if word[i]==word[j]: return False j += 1 i += 1 return True #(2.) checks if two words are permutations of one another def isPermut(A, B): #returns error message if A and B aren't strings if type(A) is not str or type(B) is not str: return "error: one or both aren't strings" A = list(A) B = list(B) #returns False if they aren't the same length if len(A)!=len(B): return False #tries to match each letter in A to the letters left in B #pops matching letters in B #moves onto the next letter in A when there's a match or if A went through all the letters in B a = 0 while a < len(A): b = 0 while b < len(B): if A[a]==B[b]: B.pop(b) break b += 1 a += 1 #assumes they're permutations, returns True unless proven otherwise #returns False if B isn't empty / if there are any letters that didn't match form A to B if len(B)!=0: return False return True #(3.) replaces spaces with %20 like in urls def urlIfy(string): #returns error message if string isn't a string if type(string) is not str: return "error: not a string" #replace spaces with %20 and return a = string.replace(" ", "%20") return a #(4.) returns a string in reverse def string_reverse(string): #returns error message if not a string if type(string) is not str: return "error: not a string" #initializes empty string ans #adds letters from string to ans letter by letter from back to front #then returns ans i = 0 ans = "" while i < len(string): ans = ans + string[len(string)-1-i] i += 1 return ans #(5.) checks if strings are the same, or 1 letter off def levenstein(first, second): if type(first) is not str or type(second) is not str: return "error: one or both aren't strings" i = 0 edit = 0 #returns False if lengths off by more than a letter if abs(len(first) - len(second)) > 1: return False #if same length if len(first) == len(second): #checks each letter in first to corresponding letter in second while i < len(first): #increments edit for every letter off if first[i] != second[i]: edit += 1 #returns False if edit > 1 since that means they're were more than one letter off if edit > 1: return False i += 1 #if one word is a letter longer than the other else: #sets length to that of the shorter word and initalizes i as 0 length = min(len(first), len(second)) i = 0 while i < length: #if letter at position i doesn't match for the two words it means that it is the off letter for either first or second if first[i] != second[i]: #if the non-discrepant letter in first matches that of second or vice versa, then return True else False if first[i:] == second[i+1:] or first[i+1:] == second[i:]: return True else: return False i += 1 #assumes first and second are off by no more than one letter unless proven otherwise return True #(6.) checks if a word or number is a palindrome def palindrome(word): #tries to convert word to a string if it isn't one if type(word) is not str: try: word = str(word) except: return "error: not a string and couldn't convert to one" #get rid of spaces, periods, and commas #then converts the letters to lowercase for ease of comparison word = word.replace(" ", "") word = word.replace(".", "") word = word.replace(",", "") word = word.lower() #checks first and last letter and each letter after and before respectively #stops halfway through the word i = 0 while i < 1+len(word)/2: if word[i] != word[len(word)-i-1]: return False i += 1 #assumes word is a plaindrome unless proven otherwise return True class Tester(unittest.TestCase): def test_isCharUnique(self): self.assertEqual(isCharUnique("asdfghjkl"), True) self.assertEqual(isCharUnique("asdfghjkla"), False) self.assertEqual(isCharUnique("1234567890"), True) self.assertEqual(isCharUnique(1234567890), True) def test_isPermut(self): self.assertEqual(isPermut("asdfgdxgfd", "asgfdfgdxd"), True) self.assertEqual(isPermut("asdfgdxgfd", "asdfgdxgfds"), False) self.assertEqual(isPermut("asdfgexgfd", "gfdfgasdxd"), False) def test_urlify(self): self.assertEqual(urlIfy("did it work?"), "did%20it%20work?") self.assertEqual(urlIfy("How about now?"), "How%20about%20%20now?") def test_string_reverse(self): self.assertEqual(string_reverse("asdfghjkl"), "lkjhgfdsa") def test_levenstein(self): self.assertEqual(levenstein("casino", "casinos"), True) self.assertEqual(levenstein("latino", "latina"), True) self.assertEqual(levenstein("Latino", "latina"), False) self.assertEqual(levenstein("cabino", "casinos"), False) def test_palindrome(self): self.assertEqual(palindrome("a man a plan a canal panama"), True) self.assertEqual(palindrome("A man a plan a canal. Panama"), True) self.assertEqual(palindrome("A man, a plan, a canal. Panama"), True) self.assertEqual(palindrome(123456654321), True) if __name__ == '__main__': unittest.main()
a33c1df622f5a939691226dd1a11f29f150e19a2
aselivan0v/home-work-beetroot
/lesson9/l9_tast2_Extend Phonebook app.py
4,686
3.859375
4
# Task 2 # Extend Phonebook application # # Functionality of Phonebook application: # # Add new entries # Search by first name # Search by last name # Search by full name # Search by telephone number # Search by city or state # Delete a record for a given telephone number # Update a record for a given telephone number # An option to exit the program # The first argument to the application should be the name of the phonebook. Application should load JSON data, # if it is present in the folder with application, else raise an error. After the user exits, all data should be saved # to loaded JSON. import json FILENAME = 'Phonebook.json' def add_new_entries(entries, first_name, last_name, telephone_number, city): new_entrie = {} new_entrie['first_name'] = first_name new_entrie['last_name'] = last_name new_entrie['telephone_number'] = telephone_number new_entrie['city'] = city new_entrie['id'] = int(max(entries)) + 1 entries[new_entrie['id']] = new_entrie write_file(entries) def search_by_first_name(entries, first_name): resalt = [] for a in entries: if (entries[a]['first_name'] == first_name): resalt.append([first_name, entries[a]['last_name'], entries[a]['telephone_number'], entries[a]['city']]) if not resalt: return 'Такого имени нет' return resalt def search_by_last_name(last_name): for x in entries: if (entries[x]['last_name'] == last_name): return 'Такая фамилия есть' return 'Такой фамилии нет' def search_by_full_name(first_name, last_name): for x in entries: for q in entries: if (entries[x]['first_name'] == first_name and entries[q]['last_name'] == last_name): return 'Такое ФИО есть' return 'Такого ФИО нет' def search_by_telephone_number(telephone_number): for x in entries: if (entries[x]['telephone_number'] == telephone_number): return 'Такой номер есть' return 'Такого номера нет' def search_by_city_or_state(city): for x in entries: if (entries[x]['city'] == city): return 'Такой город есть' return 'Такого города нет' def delete_a_record_for_a_given_telephone_number(): pass def update_a_record_for_a_given_telephone_number(entries, telephone_number): new_entries = {} for x in entries: print(x, type(x), entries[x]['telephone_number'], type( entries[x]['telephone_number'] )) new_number = {} if entries[str(x)]['telephone_number'] == telephone_number: new_number['telephone_number'] = input('Такой номер есть! \nВведите новый номер: ') new_entries.update(new_number) write_file(new_entries) else: new_entries[x] = entries[x] # return print('Поздравляем, ввели новый номер: ', new_number) return 'Такого номера нет' def an_option_to_exit_the_program(): pass def read_file(): with open(FILENAME) as file: x = json.load(file) return x def write_file(dict): with open(FILENAME, 'w') as file: json.dump(dict, file) def main(): entries = read_file() while True: print( '''1. Add new entries 2. Search by first name 3. Search by last name 4. Search by full name 5. Search by telephone number 6. Search by city or state 7. Delete a record for a given telephone number 8. Update a record for a given telephone number 9. An option to exit the program''') choice = input() if choice == '1': add_new_entries(entries, input('first name '), input('last name '), input('telephone_number '), input('city')) if choice == '2': print(search_by_first_name(entries, input('Введите имя '))) if choice == '8': print(update_a_record_for_a_given_telephone_number(entries, input('Введите номер: '))) # print(entries) #add_new_entries(24, 'Dima', 'Savchuk', '98745661', 'Kyiv') # print(entries) # # print(search_by_first_name('Sacha')) # print(search_by_last_name('Selivanov')) # print(search_by_telephone_number('98745661')) # print(search_by_city_or_state('Kyiv')) # print(search_by_full_name('Artem', 'Savchuk')) # print(update_a_record_for_a_given_telephone_number('98745661')) # print(entries) # write_file(entries) # print(read_file(), type(read_file())) main()
50d80a5a2e60d98d760fe151f6a7772e8446069e
imarkofu/PythonDemo
/Demo/day04.py
2,870
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 可变参数 # 但是调用的时候,需要先组装出一个list或tuple: def calc(numbers): sum = 0 for n in numbers: sum += n * n return sum print(calc([1, 2, 3])) print(calc((1, 3, 5, 7))) # 在参数前面加了一个*号 def calc(*numbers): sum = 0 for n in numbers: sum += n * n return sum; print(calc(1, 2, 3)) print(calc(1, 3, 5, 7)) print(calc()) nums = [1, 2, 3] print(calc(nums[0], nums[1], nums[2])) # *nums表示把nums这个list的所有元素作为可变参数传进去 calc(calc(*nums)) # 关键字参数 # 可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple # 关键字参数允许你传入0个或任意个含参数名的参数 # 关键字参数在函数内部自动组装为一个dict def person(name, age, **kw): print('name:', name, " age:", age, " other:", kw) person("Michael", 30) person('Bob', 35, city='Beijing') person('Adam', 45, gender='M', job='Engineer') # 关键字参数可以扩展函数的功能 extra = {'city': 'Beijing', 'job': 'Engineer'} person('Jack', 24, city=extra['city'], job=extra['job']) # **extra表示把extra这个dict的所有key-value用关键字参数传入到函数的**kw参数 person('Jack', 24, **extra) # 命名关键字参数 # 到底传入了哪些,就需要在函数内部通过kw检查 def person(name, age, **kw): if 'city' in kw: pass if 'job' in kw: pass print('name:', name, " age:", age, " other:", kw) # 调用者仍可以传入不受限制的关键字参数 person('Jack', 24, city='Beijing', addr='Chaoyang', zipcode=123456) # 如果要限制关键字参数的名字,就可以用命名关键字参数 def person(name, age, *, city, job): print('name:', name, " age:", age, " city:", city, " job:", job) person('Jack', 24, city='Beijing', job='Engineer') # 如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了 # def person(name, age, *args, city, job): # print(name, age, args, city, job) # person('Jack', 24, 'Beijing', 'Engineer') def person(name, age, *, city='Beijing', job): print(name, age, city, job) person('Jack', 24, job='Engineer') def f1(a, b, c=0, *args, **kw): print('a=', a, 'b=', b, 'c=', c, 'args=', args, 'kw=', kw) def f2(a, b, c=0, *, d, **kw): print('a=', a, 'b=', b, 'c=', c, 'd=', d, 'kw=', kw) f1(1, 2) f1(1, 2, c=3) f1(1, 2, 3, 'a', 'b') f1(1, 2, 3, 'a', 'b', x=99) f1(1, 2, d=99, ext=None) args = (1, 2, 3, 4) kw = {'d': 99, 'x': '#'} f1(*args, **kw) args = (1, 2, 3) kw = {'d': 88, 'x': '#'} f2(*args, **kw) # 递归函数 def fact(n): if n == 1: return 1 return n * fact(n - 1) print(fact(1)) print(fact(5)) print(fact(100))
a76cb437af6caef6bf987785493145ee3fd59159
vincentX3/Leetcode_practice
/easy/349IntersectionofTwoArrays.py
1,384
3.828125
4
from typing import List class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: return list(set(nums1).intersection(set(nums2))) def intersection2(self, nums1: List[int], nums2: List[int]) -> List[int]: hash={} intersection=[] for num in nums1: hash[num]=num for num in nums2: if num in hash: intersection.append(num) hash.pop(num) #去重 return intersection def intersection3(self, nums1: List[int], nums2: List[int]) -> List[int]: nums1.sort() nums2.sort() intersection = [] left, right = 0, 0 while left < len(nums1) and right < len(nums2): left_val = nums1[left] right_val = nums2[right] if right_val == left_val: intersection.append(nums2[right]) while right < len(nums2) and nums2[right] == right_val: right += 1 while left < len(nums1) and nums1[left] == left_val: left += 1 if right_val > left_val: while left < len(nums1) and left_val == nums1[left]: left += 1 else: while right < len(nums2) and right_val == nums2[right]: right += 1 return intersection
a49c7182083d8787939fbe8c2c5e2cba5a39d489
vasilako/Automation-with-Python
/unit test/letter_test.py
768
3.671875
4
from letters import LetterCompiler import unittest class TestLetters(unittest.TestCase): def test_two(self): testcase = "A b c d e f g h i j k l m n o q r s t u v w x y z" expected = ['b', 'c'] self.assertEqual(LetterCompiler(testcase), expected) # EDGE CASES HERE def test_empty(self): testcase = "" expected = "" self.assertEqual(LetterCompiler(testcase), expected) def test_word(self): testcase = "awesome" expected = ['a'] self.assertEqual(LetterCompiler(testcase), expected) def test_unmatch(self): testcase = "go" expected = [] self.assertEqual(LetterCompiler(testcase), expected) if __name__ == "__main__": unittest.main()
e6c61701ef597d31662d9d507b47f6449f5ed5d9
c108glass/MIT-IntroProgramming-Python
/Lecture3-Python-ProblemSolving.py
2,150
4.21875
4
##Lecture 3 ##Problem Solving ##Intro to Computer Science And Programming - MIT ##https://ocw.mit.edu ##Decrementing function: guaranteed to always terminate loop if: ##1.Map set of program variables to an integer. ##2.Starts with a non-negative value ##3.When <= 0, loop terminates. ##4.Decreased each iteration ##Find the cube root of a perfect cube #2. ##Exhaustive Enumeration (Brute Force) - exhaust the space of all possible answers. x = int(raw_input('Enter an integer: ')) for ans in range(0, abs(x)+1): if ans**3 == abs(x): break if ans**3 != abs(x): print x, 'is not a perfect cube' else: if x < 0: ans = -ans print 'Cube root of ' + str(x) + ' is ' + str(ans) ##Approximation(using an epsilon). Find square root using Exhaustive Enumerationx ##These two programs do not work for finding exact square, only an approximation. ##The purpose is to show how program execution time is based on ##size of input, level of accuracy(epsilon), and size of iteration increment. ##More specifically, it is based on the algorithm used. x = 12345 epsilon = 0.01 numGuesses = 0 ans = 0.0 while abs(ans**2 - x) >= epsilon and ans <= x: ans += 0.00001 numGuesses += 1 print 'numGuesses =', numGuesses if abs(ans**2 - x) >= epsilon: print 'Failed on square root of ', x else: print ans, 'is close to square root of', x ##Here's a faster way. Bisection Search. ##Cut search space in half each iteration. ##This method takes 26 guesses for x = 12345. Previous algorithm took more than 11 million guesses. x = 12345 epsilon = 0.01 numGuesses = 0 low = 0.0 high = x ans = (high + low)/2.0 while abs(ans**2 - x) >= epsilon and ans <= x: #print low, high, ans numGuesses += 1 if ans**2 < x: low = ans else: high = ans ans = (high + low)/2.0 print 'numGuesses =', numGuesses print ans, 'is close to square root of', x ##Can estimate the number of guesses by (x/epsilon)**2. ##Estimating number of guesses is useful for determining an appropriate algorithm, ##so that the program runs in a reasonable timeframe.
702593f973fd3ccdd28f934d9162752dc252e4d0
Aasthaengg/IBMdataset
/Python_codes/p03738/s328147917.py
168
4.09375
4
a = input() b = input() if len(a)<len(b): print("LESS") elif len(a)==len(b): print("LESS" if a<b else "EQUAL" if a==b else "GREATER") else: print("GREATER")
1b6faa058729a0316d36ff7041398a926473f331
dengl11/Leetcode
/problems/erect_the_fence/solution.py
804
3.625
4
class Solution: def outerTrees(self, points: List[List[int]]) -> List[List[int]]: points.sort() def cross(O, A, B): O, A, B = points[O], points[A], points[B] v1x, v1y = A[0]-O[0], A[1]-O[1] v2x, v2y = B[0]-O[0], B[1]-O[1] return v1x * v2y - v2x * v1y # lower part lower = [] for p in range(len(points)): while len(lower) > 1 and cross(lower[-2], p, lower[-1]) > 0: lower.pop() lower.append(p) # upper part upper = [] for p in range(len(points)-1, -1, -1): while len(upper) > 1 and cross(upper[-2], p, upper[-1]) > 0: upper.pop() upper.append(p) return [points[i] for i in set(lower + upper)]