blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
acb5ffaf7c1b3d0ff74419af235ff1ba3a4d5320
cavid-aliyev/HackerRank
/collection-counter.py
727
3.703125
4
# Collection-counter -> https://www.hackerrank.com/challenges/collections-counter/problem from collections import Counter # Ölçülərin sayını əlavə edirik mallarin_razmerlerinin_sayi= int(input("Ölçüləri sayını əlavə edin: ")) #Öıçüləri bir listə yığırıq myList = Counter(list(map(int, input().split()))) #Mallarin db sinden satilan mallari yaziriq satilan_mallarin_sayi = int(input("Satılan malları əlavə edin")) myTuple = [tuple(map(int, input().split())) for i in range(satilan_mallarin_sayi)] #Toplam satılan malların qiymətlərinin cəmi cem = 0 for i in myTuple: if i[0] in myList: if myList[i[0]] > 0: cem += i[1] myList[i[0]] -= 1 print(cem)
dcdaaceba0365796d4de0b9b6135d70969e7a2bf
VISHAL2981/python_basic-s
/shorthand_ifelse.py
155
4.0625
4
a=int(input("enter a\n")) b=int(input("enter b\n")) if a>b: print("a b sai bda hai sir ji ") print("b a sai bda hai") if b>a else print("a b sai bda hai")
c08b38aece4e85f90c9cf1a91e79ffb735fca56c
maxkagan/cs-21a
/assignment5/aggregator.py
5,048
3.671875
4
# ----------------------------------------------------------------------------- # Name: Max Kagan aggregator.py # Purpose: CS 21A - implement a simple general purpose aggregator # # Author: Max Kagan # ----------------------------------------------------------------------------- """ Implement a simple general purpose aggregator Usage: aggregator.py filename topic filename: input file that contains a list of the online sources (urls). topic: topic to be researched and reported on """ import urllib.request import urllib.error import re import sys def write_to_file(output_string, match_target): """ Writes a formatted string to an output file Parameters: valid_matches (string) - data received from the format_and_search_data function link_searched (string) - the link we searched through that contains desired data Return: True or False (Bool) - True if results were found and outputted to file False if results were not found and the output file only contains a empty string """ filename = match_target + 'summary.txt' if output_string == '': with open(filename, 'a', encoding='utf-8') as my_file: my_file.write("") my_file.close() return False else: with open(filename, 'a', encoding='utf-8') as my_file: my_file.write(output_string) my_file.close() return True def generate_output_strings(valid_matches, link_searched): """ Creates string to be used in file output generation Parameters: valid_matches (string) - data received from the format_and_search_data function link_searched (string) - the link we searched through that contains desired data Return: formatted_output (string) - a string that beautifies the output and is read directly on file output generation """ end_line = '----------------------------------------\n' if valid_matches == '': return valid_matches else: formatted_output = ("Source url:" + '\n' + link_searched + '\n' + (valid_matches + '\n') + end_line + '\n') return formatted_output def format_and_search_data(parsed_html, match_target): """ capture references to the given word found in the given html code Parameters: parsed_html (string) - the formatted string data from the html string match_target (string) - the word we are searching for Return: formatted_data (string) - Words found between '>' and '<' characters from the html source string input """ formatted_data = '' # extract text inside brackets containing the match target regex = r'>([^><]*\b{}\b.*?)<'.format(match_target) try: valid_match = re.findall(regex, parsed_html, re.IGNORECASE | re.DOTALL) except: valid_match = False if valid_match: formatted_data = '\n'.join(valid_match) return formatted_data def read_link(desired_link): """ Reads a url and returns html source code if able to connect to the web server and decode the received data Parameters: desired_link (string) - String representation of a URL that we will attempt to extract html source code from Return: read_data (string) - the decoded html file if the link was able to be read and decoded using UTF-8 """ url_file = str(desired_link) try: with urllib.request.urlopen(desired_link) as opened_file: read_file = opened_file.read().decode('UTF-8') return read_file except urllib.error.URLError as url_err: print('Error opening url: ', url_file, url_err) except UnicodeDecodeError as decode_err: print('Error decoding url: ', url_file + '\n', decode_err) def main(): """ Reads an input file as an argument and matches search targets as the second parameter return: True or False (Bool) An output file with the name determined by match_target + summary.txt """ # Check to see if correct number of arguments have been entered by the user if len(sys.argv) != 3: print("Error: Invalid number of arguments" + '\n') print('Usage: aggregator.py filename topic') return # Exceptions are caught and displayed by the functions called with open(sys.argv[1], 'r', encoding='utf-8') as my_file: match_target = sys.argv[2] desired_output = '' for line in my_file: page_data = read_link(line) search_results = format_and_search_data(page_data, match_target) desired_output = desired_output + generate_output_strings( search_results, line) return write_to_file(desired_output, match_target) if __name__ == '__main__': main()
e481b74acdbeda2da4f78662d84b29980c7ce556
pratikap41/Python-Program
/Employee Tracker.py
2,855
3.984375
4
class Employee: def __init__(self, name, designation, gender, doj, salary): self.name = name self.designation = designation self.gender = gender self.doj = doj self.salary = salary emp_list = [] def registration(): while(1): print('note :- to exit press 0 ') name = input('Enter name : ') if (name == '0'): break else: designation = input('Enter designation : ') gender = input('Enter your Gender :') doj = input('Enter Date Of Joining : ') salary = input('Enter salary : ') name = Employee(name, designation, gender, doj, salary) emp_list.append(name) print("Registration Done!") globals().update(locals()) def stat(): while(1): print("""******************************************* 1. Number of employee 2. Number of female employee 3. Number of male employee 4. Assistant manager 5. Number of employee having salary greater than 10 thosand 6. Back """) op2 = int(input('CHOOSE OPTION: ')) if (op2 == 1): print(len(emp_list)) elif(op2 == 2): fe = 0 for i in emp_list: if(i.gender.upper() == 'F' ): fe += 1 else: None print("Number of female employee : ", fe) elif(op2 == 3): me = 0 for i in emp_list: if (i.gender.upper() == 'M'): me += 1 else: None print("Number of male employee", me) elif(op2 == 4): for i in emp_list: if (i.designation.upper() == 'ASSISTANT MANAGER'): print(i.name, i.designation) else: None elif(op2 == 5): sl = 0 for i in emp_list: if (i.salary >= '10000'): sl += 1 else: None print('Number of employee having salary greater than 10 thousand : ', sl) elif(op2 == 6): break while(1): print("""**************MENU************** 1. Employee Registration 2. statistics 3. Employee information 4. Exit """) op1 = int(input("CHOOSE OPTION :")) if (op1 == 1): registration() if (op1 == 2): stat() if (op1 == 3): for i in emp_list: print(i.name, '\n') search = input('Enter name of an employee :') for i in emp_list: if(i.name.upper() == search.upper()): print(i.__dict__) if(op1 == 4): break
ccef15f2576a847142e21736d618ba263855c4ab
natj/tov
/label_line.py
1,820
3.703125
4
import numpy as np import math import matplotlib.pyplot as plt """ Simple script to label line similar to what contour function does credits: Thomas Albrecht https://stackoverflow.com/questions/19876882/print-string-over-plotted-line-mimic-contour-plot-labels """ def label_line(line, label_text, near_i=None, near_x=None, near_y=None, rotation_offset=0, offset=(0,0)): """call l, = plt.loglog(x, y) label_line(l, "text", near_x=0.32) """ def put_label(i): """put label at given index""" i = min(i, len(x)-2) dx = sx[i+1] - sx[i] dy = sy[i+1] - sy[i] rotation = np.rad2deg(math.atan2(dy, dx)) + rotation_offset pos = [(x[i] + x[i+1])/2. + offset[0], (y[i] + y[i+1])/2 + offset[1]] txt = plt.text(pos[0], pos[1], label_text, size=5, rotation=rotation, color = line.get_color(), ha="center", va="center", bbox = dict(ec='1',fc='1',pad=0)) return txt x = line.get_xdata() y = line.get_ydata() ax = line.get_axes() if ax.get_xscale() == 'log': sx = np.log10(x) # screen space else: sx = x if ax.get_yscale() == 'log': sy = np.log10(y) else: sy = y # find index if near_i is not None: i = near_i if i < 0: # sanitize negative i i = len(x) + i put_label(i) elif near_x is not None: for i in range(len(x)-2): if (x[i] < near_x and x[i+1] >= near_x) or (x[i+1] < near_x and x[i] >= near_x): put_label(i) elif near_y is not None: for i in range(len(y)-2): if (y[i] < near_y and y[i+1] >= near_y) or (y[i+1] < near_y and y[i] >= near_y): put_label(i) else: raise ValueError("Need one of near_i, near_x, near_y")
691c9ef8e4f37b88e68fb62286d4297d0909c65a
StephenElishaClarke/Code
/fibonacci.py
796
4.03125
4
def memoize(f): memo = {} def helper(x): if x not in memo: memo[x] = f(x) print(memo) return memo[x] return helper @memoize def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1)+fib(n-2) n = input("Enter the desired nth term of the fibonacci sequence: ") #n = int(n) print(fib(n)) @memoize def s(n): if n == 0: return 0 elif n == 1: return 1 elif n == 2: return 2 else: return s(n-1)+s(n-3) print(s(n)) ################################################################### import pickle fn = open("data.pkl", "w") pickle.dump(fib(n), fn) fn.close() with open('data.pkl', 'rb') as f: data = pickle.load(f) print(data)
362751f874de9393b7b41d2489390206fb061549
snehavaddi/DataStructures-Algorithms
/LL_reverse_list_in_set_of_k_set2.py
1,431
3.953125
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def reverse(self, head, k): curr = self.head prev = None next = None count = 0 new_stack = [] while(curr is not None): count = 0 while(curr is not None and count < k): new_stack.append(curr.data) curr = curr.next count = count + 1 while(new_stack): if prev == None: prev = Node(new_stack.pop()) self.head = prev else: prev.next = Node(new_stack.pop()) prev = prev.next prev.next = None return self.head def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node def printList(self): temp = self.head while (temp): print(temp.data,end=" ") temp = temp.next llist = LinkedList() llist.push(9) llist.push(8) llist.push(7) llist.push(6) llist.push(5) llist.push(4) llist.push(3) llist.push(2) llist.push(1) print("Given linked list") llist.printList() llist.head = llist.reverse(llist.head, 3) print("\nReversed Linked list") llist.printList()
79f2053847dcc22554d9d37b1fee4fabc7ac05d7
mwthe78/My-python-Code
/Week11/exo1.py
49
3.578125
4
b=float(input(" give a number")) c=b*2 print (c)
4a2bf9a5a0f87217505033d52bc6798b428c7015
andrewzhang1/Selenium-1
/Calculate-class.py
385
3.609375
4
''' Alex helped to create this class 03/10/2017 Add unit test: 1. Add ''' ## Test a python class class Calculate(object): # May or may not define "zeor": #zero = 90 def add(self, x, y): return x + y + self.zero if __name__ == '__main__': calc = Calculate() calc.zero = 9 result = calc.add(2, 2) print ("Result is: ", result)
48bca3b0721fe6f79a37e078fde2f404bd2ce1d5
claudianguyen/easy-lemon
/utils/FormatUtils.py
976
4.21875
4
""" Utils method for formatting text. """ def format_job_info(job_info): """ Checks each characteristic in the job_info object. If the charc is None, return "N/A", otherwise, return the stripped text. :param job_info: the job_info that needs to be formatted. :return: job_info: this job_info will contain the formatted changes. """ for charc in job_info.keys(): job_charc = job_info[charc] if job_charc and job_charc.strip(): job_info[charc] = job_charc.strip() else: job_info[charc] = "N/A" return job_info def currency_string_to_basic_string(currency_string): """ Given a string like $120,000 --> 120000 :param currency_string: The currency string to convert :return: String that represents the "basic" version of the string. """ currency_excludes = str.maketrans('$', ' ', ',') return currency_string.translate(currency_excludes)
623093fa7e86b289940e00b923e8e314447094d5
dalaAM/month-01
/day06_all/day06/demo01.py
644
4.15625
4
""" 深拷贝 exercise:exercise01 """ # 准备拷贝工具 import copy list01 = [ [10, 20, 30], [40, 50, 60], ] list02 = list01[:] # 浅拷贝 list03 = copy.deepcopy(list01) # 深拷贝 # 验证: # 浅拷贝修改深层,互相影响 # list02[0][0] = "十" # print(list01) # [[10, 20, 30], [40, 50, 60]] # 浅拷贝修改第一层,互不影响 # list02[0] = "列表" # print(list01)# [[10, 20, 30], [40, 50, 60]] # print(list02)# ['列表', [40, 50, 60]] # 深拷贝修改,互不影响 list03[0] = "列表" list03[1][0] = "四十" print(list01)# [[10, 20, 30], [40, 50, 60]] print(list03)# ['列表', ['四十', 50, 60]]
e10ab7dddeb39d64c80cc0c4e8796cfb8e671c76
kateflorence/motion_parallax
/motion_parallax.py
4,703
4.21875
4
### ### Author: Kate Martin ### Course: CSc 110 ### Description: This program is designed to display a nature scene ### using graphics. It utilizes if-statements, while loops, ### indexing, the random module, parameters and arguments ### within functions, and incorporates motion parallax on the ### user's interface. ### from graphics import graphics import random def main(gui): # Assign random colors to the mountains in three color strings red = random.randint(0, 255) green = random.randint(0, 255) blue = random.randint(0, 255) color_string_one = gui.get_color_string(red, green, blue) red = random.randint(0, 255) green = random.randint(0, 255) blue = random.randint(0, 255) color_string_two = gui.get_color_string(red, green, blue) red = random.randint(0, 255) green = random.randint(0, 255) blue = random.randint(0, 255) color_string_three = gui.get_color_string(red, green, blue) # Display the scene using a loop while True: gui.clear() sky(gui) mountain(gui, color_string_one) mountains(gui, color_string_two, color_string_three) foreground(gui) flowers(gui) birds(gui) gui.update_frame(30) def flowers(gui): ''' This function displays a flashing carnival of flowers using a while loop ''' flowers = 0 while flowers <= 15: flower_x = random.randint(0, 500) flower_y = random.randint((gui.mouse_y // 4) + 300, 500) gui.ellipse(flower_x, flower_y, 10, 10, 'hot pink') gui.ellipse(flower_x + 7, flower_y + 5, 10, 10, 'hot pink') gui.ellipse(flower_x + 14, flower_y , 10, 10, 'hot pink') gui.ellipse(flower_x + 7, flower_y - 5, 10, 10, 'hot pink') gui.ellipse(flower_x + 7, flower_y, 5, 5, 'yellow') flowers += 1 def sky(gui): ''' This function displays the sky and a yellow sun with a black border The sun moves in respect to the mouse of the user. ''' x = (gui.mouse_x // 30) y = (gui.mouse_y // 30) gui.rectangle(0, 0, 500, 500, 'light sky blue') gui.ellipse(x+365, y+65, 76, 76, 'black') gui.ellipse(x+365, y+65, 75, 75, 'yellow') def foreground(gui): ''' This function displays the foreground of the scene, including grass and a tree. The tree uses a while loop to create a carnival of leaves of different colors. The foreground moves in respect to the mouse of the user. ''' x = (gui.mouse_x) y = (gui.mouse_y // 4) gui.rectangle(0, y + 300, 500, 400, 'spring green') x_grass = 0 while x_grass <= 500: gui.line(x_grass, y + 300, x_grass, y + 280, 'spring green') x_grass += 5 leaves = 0 x = (gui.mouse_x // 10) while leaves <= 100: red = random.randint(0, 50) green = random.randint(30, 200) blue = random.randint(0, 50) color_string = gui.get_color_string(red, green, blue) x_leaves = random.randint(405, 480) y_leaves = random.randint(315, 380) gui.ellipse(x + x_leaves - 50, y + y_leaves - 75, 7, 4, color_string) leaves += 1 gui.rectangle(x+385, y+300, 9, 62, 'brown') def mountain(gui, color): ''' This function displays the middle mountain in a random color. The mountain moves in respect to the mouse of the user. ''' x = (gui.mouse_x // 18) y = (gui.mouse_y // 18) gui.triangle(x + 250, y + 130, x + 125, y + 400, x + 375, x + 400, color) def mountains(gui, color_one, color_two): ''' This function displays the middle mountains in random colors. The mountains move in respect to the mouse of the user, slightly more than the middle mountain does, in order to achieve motion parallax. ''' x = (gui.mouse_x // 15) y = (gui.mouse_y // 15) gui.triangle(x+100, y+165, x-100, y+400, x+300, y+400, color_one) gui.triangle(x+400, y+165, x+200, y+400, x+600, y+400, color_two) def birds(gui): ''' This function displays 5 birds in the sky traveling downwards. Uses a while loop and lines to achieve this. ''' bird = 0 start_left_x = 30 start_left_y = 50 end_left_x = 50 end_left_y = 60 while bird < 5: gui.line(start_left_x, start_left_y, end_left_x, end_left_y, 'black') gui.line(end_left_x, end_left_y, start_left_x + 40, start_left_y, 'black') start_left_x += 60 start_left_y += 15 end_left_x = start_left_x + 20 end_left_y = start_left_y + 10 bird += 1 # call to main - argument passed in is the creation of the canvas for the program main(gui=graphics(500, 500, 'motion parallax'))
0b2728a7b809f2ee3ed76d36905555a0dfe2193d
saycmily/vtk-and-python
/leecode/1-500/1-100/95-不同的二叉搜索树Ⅱ.py
787
3.8125
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def generateTrees(self, n: int): def func(start, end): if start > end: return [None] ans = [] for i in range(start, end+1): left_trees = func(start, i-1) right_trees = func(i+1, end) for l in left_trees: for r in right_trees: tree = TreeNode(i) tree.left = l tree.right = r print(tree) ans.append(tree) return ans return func(1, n) if n else []
fcd325367dcbef7d1db51809003889a4ce97cf5f
karel1980/advent-of-code-2015
/day11/day11b.py
1,629
3.703125
4
import re def make_alphas(start, end): return "".join([chr(c) for c in range(ord(start),ord(end)+1)]) alphabet = make_alphas('a','z') class Validator: def __init__(self): sequences = [ alphabet[n:n+3] for n in range(len(alphabet)-2) ] self.seq_regex = re.compile("(%s)"%("|".join(sequences))) self.iol_regex = re.compile("[iol]") self.double_pair_regex = re.compile('([a-z])\\1.*([a-z])\\2') def _contains_sequence_of_three(self, password): return self.seq_regex.search(password) is not None def _contains_iol(self, password): return self.iol_regex.search(password) is not None def _contains_two_different_pairs(self, password): match = self.double_pair_regex.search(password) return match is not None and match.group(1) != match.group(2) def is_valid_password(self, password): return self._contains_sequence_of_three(password) and\ not self._contains_iol(password) and\ self._contains_two_different_pairs(password) class PasswordTool: def __init__(self): self.validator = Validator() def get_next_password(self, password): chars = [ c for c in password ] n = len(password)-1 while n >= 0: if ord(chars[n]) < ord('z'): chars[n] = chr(ord(chars[n])+1) break else: chars[n] = "a" n -= 1 if n < 0: return "a"*(len(password)+1) return "".join(chars) def get_next_valid_password(self, password): valid = False while not valid: password = self.get_next_password(password) valid = self.validator.is_valid_password(password) return password if __name__ == '__main__': tool = PasswordTool() print tool.get_next_valid_password("vzbxxyzz")
aadf0dce54d1eaa1d6d4d9d1ab4f8cbd9660e308
fpgodoy/Exercicios-Python
/ex028.py
340
3.765625
4
from random import randint num = randint(0,9) chute = int(input ('O computador escolheu um número entre 0 e 9. Tente adivinhar qual foi: ')) print('Você escolheu {}.'.format(chute)) if chute == num: print('Parabéns, você acertou, o número era {}.'.fomart(num)) else: print('Você errou, o número era {}.'.format(num))
0e95c78c70cac67447b357690689122dc27a96d9
greatwallgoogle/Learnings
/other/learn_python_the_hard_way/ex32.py
1,639
4.1875
4
# 循环和列表 # list初始化:将数据放入[ ]之间,用逗号分隔 # ele = []; --声明一个空列表 # ele.append(x); 向列表尾部添加一个元素x # for i in list : 遍历列表list # 列表中可以存放不同类型的元素 # range(start,end) :表示生成一个列表,其元素为从start开始,最后一个元素为(end - 1),即区间为[start,end)。 # 可以使用[index]访问元素 hairs = ["brown","blond","red"] eyes = ["brown","blue","green"] weights = [1,2,3,4] print("hairs:" , hairs) print("eyes:" ,eyes) print("weights: ",weights) the_count = [1,2,3,4,5] #pear : 梨 # apricot: 杏 fruits = ['apples','oranges','pears','apricots'] change = [1,'pennies',2,'dimes',3,'quaters'] for number in the_count: print("This is count %d" % number) for fruit in fruits: print("A fruit of type:%s" % fruit) for x in change: print("I got %r" % x) elements = [] for x in range(0,6): print("Adding %d to the list." % x) elements.append(x) for x in elements: print("Element was : %d" % x) elements2 = range(1,10) print("elements2 :" ,elements2) # 定义一个两层列表 list1 = [[1,2,3],['a','b'],["hello","world"],["Monday",10]] print("list1 :" ,list1) # 可以使用[]访问元素 print("list index1 :" , list1[0]) print("list index2 :" , list1[1]) # 遍历每个元素值 for x in list1: print("x : " , x) for y in x: print("y : ",y) print("================") # 通过索引循环 for index in range(len(list1)): print("current ele:", list1[index]) for index2 in range(len(list1[index])): print("current ele 2:" , list1[index][index2]) print("**********************")
870bc02197b7fd046aa1b19cec33a3b7b5dce55d
josulaguna/Python
/calculo-areas.py
811
3.859375
4
#Josué Laguna Alonso #01/03/18 #coding: utf8 import os os.system ("clear") from math import pi print """ ******************** Calculadora de áreas ******************** a) Triángulo b) Círculo """ figura = raw_input ("¿Qué figura quiere calcular (Escriba T o C)? ") if (figura == "T"): base = input ("Escriba la base: ") altura = input ("Escriba la altura: ") if (base >0 and altura >0): print "Un triangulo de base",base, "y de altura",altura, "tiene un área de ",base*altura/2 else: print "No se puede calcular, ya que hay números negativos" if (figura == "C"): radio = input ("Escriba el radio: ") if (radio >0): print "El radio es",radio, "y tiene un área de " ,2*pi*radio else: print "No se puede calcular, ya que hay números negativos"
917b3f1faba9e31cb433a7ac1852fce12c051e29
UWPCE-PythonCert-ClassRepos/SP_Online_PY210
/students/zhen_yang/lesson02/series.py
1,634
4.09375
4
# define function fibonacci() def fibonacci(num): if num == 0 : return 0 elif num == 1: return 1 else: return fibonacci(num-1) + fibonacci(num-2) # define function lucas() def lucas(num): if num == 0 : return 2 elif num == 1: return 1 else: return lucas(num-1) + lucas(num-2) # define the sum_series() def sum_series(num,*argv): if argv: # using optional parameters if num == 0 : return argv[0] elif num == 1: return argv[1] else: return sum_series(num-1,argv[0],argv[1]) + sum_series(num-2,argv[0],argv[1]) else:# no optional paramter then producing fibonnaci number if num == 0 : return 0 elif num == 1: return 1 else: return sum_series(num-1,0,1) + sum_series(num-2,0,1) # run some tests assert fibonacci(0) == 0 assert fibonacci(1) == 1 assert fibonacci(2) == 1 assert fibonacci(3) == 2 assert fibonacci(4) == 3 assert fibonacci(5) == 5 assert fibonacci(6) == 8 assert fibonacci(7) == 13 assert lucas(0) == 2 assert lucas(1) == 1 assert lucas(4) == 7 # test that sum_series matches fibonacci assert sum_series(5) == fibonacci(5) assert sum_series(7, 0, 1) == fibonacci(7) # test if sum_series matched lucas assert sum_series(5, 2, 1) == lucas(5) # test if sum_series works for arbitrary initial values assert sum_series(0, 3, 2) == 3 assert sum_series(1, 3, 2) == 2 assert sum_series(2, 3, 2) == 5 assert sum_series(3, 3, 2) == 7 assert sum_series(4, 3, 2) == 12 assert sum_series(5, 3, 2) == 19 print("tests passed")
2322d67df1990dd9b19ee2e18940b906866325ca
gmontoya2483/curso_python
/Section_09_Advance_buit_in_Functions/generator_classes_and_iterators.py
965
3.8125
4
class FirstFiveGenerator: def __init__(self): self.number = 0 def __next__(self): if self.number < 5: current = self.number self.number += 1 return current else: raise StopIteration() class FirstFiveIterator: def __init__(self): self.numbers = [1, 2, 3, 4, 5] self.i = 0 def __next__(self): if self.i < len(self.numbers): current = self.numbers[self.i] self.i += 1 return current else: raise StopIteration() if __name__ == '__main__': my_gen = FirstFiveGenerator() print(next(my_gen)) print(next(my_gen)) print(next(my_gen)) print(next(my_gen)) print(next(my_gen)) print ('\n') my_iterator = FirstFiveIterator() print(next(my_iterator)) print(next(my_iterator)) print(next(my_iterator)) print(next(my_iterator)) print(next(my_iterator))
96c7640e8d4cc31482a9e0ea99a6a0ededa43024
surajmapa/CodeBreakthrough
/OOP/oop.py
2,927
3.734375
4
from enum import Enum from abc import ABC, abstractmethod class SecurityDevice(ABC): def __init__(self, active): self.active = active @abstractmethod def reset(self): pass class Sensor(SecurityDevice): def __init__(self, silent, distance): self.silent = silent self.distance = distance @property def distance(self): print("getting distance") return self._distance @distance.setter def distance(self, val): print("setting distance") self._distance = val @distance.deleter def distance(self): del self._distance def reset(self): print("Resetting ... Sensor version") self.silent = False self.distance = 20 class Position: def __init__(self, pan, tilt, zoom): self.pan = pan self.tilt = tilt self.zoom = zoom def __str__(self): return f"Pan: {str(self.pan)}. Tilt: {str(self.tilt)}. Zoom: {str(self.zoom)}." def __eq__(self, other): return self.pan == other.pan and self.tilt == other.tilt and self.zoom == other.zoom __hash__ = None class Camera(SecurityDevice): def parse_camera(): with open("cameras.txt") as f: d = f.read().strip().split(" ") serial_number = d[0] position = Position(int(d[1]), int(d[2]), int(d[3])) camera_type = Camera.CameraType[d[4]] return Camera(serial_number, position, camera_type) def __init__(self, serial_number, position, camera_type): self.serial_number = serial_number self.position = position self.camera_type = camera_type def __str__(self): return f"Serial number: {self.serial_number}. Camera type: {self.camera_type}. " + self.position.__str__() def __eq__(self, other): return self.serial_number == other.serial_number and self.position == other.position and self.camera_type == other.camera_type __hash__ = None class CameraType(Enum): ptz = 0 eptz = 1 stationary = 2 def reset(self): print("Resetting camera...") self.position = Position(0, 0, 0) @property # we used a property to show that we can hide the internals # serial number will be in format abc-123 or something similar # internally stored as two variables def serial_number(self): return str.upper(self._serial_number_code) + '-' + self._serial_number_id @serial_number.setter def serial_number(self, val): data = val.split('-') self._serial_number_code = data[0] self._serial_number_id = data[1] @serial_number.deleter def serial_number(self): del self._serial_number_code del self._serial_number_id camera = Camera('abc-123', Position(1, 2, 3), Camera.CameraType.ptz) print(camera.serial_number) camera = Camera.parse_camera() print(camera)
5edc0b5105d59936db89d249a16aa156ed5ac0e6
iamrustamov/Telegram-Lesson-Bot
/db_helper.py
7,877
3.578125
4
import sqlite3 def prepare_db(db_name): conn = sqlite3.connect(db_name) cur = conn.cursor() cur.execute('''CREATE TABLE IF NOT EXISTS students( number TEXT PRIMARY KEY NOT NULL, last_name TEXT NOT NULL, first_name TEXT NOT NULL, middle_name TEXT NOT NULL);''') cur.execute('''CREATE TABLE IF NOT EXISTS homeworks( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , name TEXT NOT NULL, description TEXT NOT NULL );''') cur.execute('''CREATE TABLE IF NOT EXISTS ratings( number TEXT PRIMARY KEY NOT NULL, CONSTRAINT ratings_students_number_fk FOREIGN KEY (number) REFERENCES students (number) ON DELETE CASCADE ON UPDATE CASCADE );''') cur.execute('''CREATE TABLE IF NOT EXISTS absents( number TEXT PRIMARY KEY NOT NULL, CONSTRAINT absents_students_number_fk FOREIGN KEY (number) REFERENCES students (number) ON DELETE CASCADE ON UPDATE CASCADE );''') cur.execute('''CREATE TABLE IF NOT EXISTS asks( text TEXT NOT NULL, date TEXT NOT NULL, first_name TEXT NOT NULL, username TEXT, last_name TEXT );''') cur.execute('SELECT * FROM homeworks;') hws_count = len(cur.fetchall()) cur.execute('UPDATE sqlite_sequence SET seq=? WHERE name=\'homeworks\';', (hws_count,)) cur.execute('SELECT * FROM absents;') days_count = len(list(map(lambda x: x[0], cur.description))) - 1 cur.execute('SELECT * FROM sqlite_sequence WHERE name=\'absents\'') if len(cur.fetchall()) == 0: cur.execute('INSERT INTO sqlite_sequence(name, seq) VALUES (\'absents\', ?);', (days_count,)) else: cur.execute('UPDATE sqlite_sequence SET seq=? WHERE name=\'absents\';', (days_count,)) conn.commit() conn.close() def execute_select(db_name, sql): conn = sqlite3.connect(db_name) cur = conn.cursor() result = cur.execute(sql).fetchall() conn.close() return result def add_student(db_name, args): conn = sqlite3.connect(db_name) cur = conn.cursor() cur.execute('SELECT * FROM students WHERE number=?', (args[0],)) if len(cur.fetchall()) == 0: cur.execute( 'INSERT INTO students(number, last_name, first_name, middle_name) VALUES (?,?,?,?);', (args[0], args[1], args[2], args[3])) cur.execute('INSERT INTO ratings(number) VALUES (?)', (args[0],)) cur.execute('INSERT INTO absents(number) VALUES (?)', (args[0],)) conn.commit() conn.close() def delete_student(db_name, arg): conn = sqlite3.connect(db_name) cur = conn.cursor() cur.execute('SELECT * FROM students WHERE number=?', (arg,)) if len(cur.fetchall()) > 0: cur.execute('DELETE FROM students WHERE number=?', (arg,)) cur.execute('DELETE FROM ratings WHERE number=?', (arg,)) cur.execute('DELETE FROM absents WHERE number=?', (arg,)) conn.commit() conn.close() def add_hw(db_name, args): conn = sqlite3.connect(db_name) cur = conn.cursor() cur.execute('INSERT INTO homeworks(name, description) VALUES (?,?);', (args[0], args[1])) cur.execute('SELECT seq FROM sqlite_sequence WHERE name=\'homeworks\';') count = cur.fetchall() cur.execute('ALTER TABLE ratings ADD hw_{} TEXT DEFAULT \'-\' NOT NULL;'.format(count[0][0])) conn.commit() conn.close() def delete_hw(db_name, id): conn = sqlite3.connect(db_name) cur = conn.cursor() cur.execute('SELECT * FROM homeworks WHERE id=?', (id,)) if len(cur.fetchall()) > 0: cur.execute('DELETE FROM homeworks WHERE id=?;', (id,)) cur.execute('SELECT id FROM homeworks') hw_ids = cur.fetchall() cur.execute('''CREATE TABLE ratings_tmp(number TEXT PRIMARY KEY NOT NULL, CONSTRAINT ratings_students_number_fk FOREIGN KEY (number) REFERENCES students(number) ON DELETE CASCADE ON UPDATE CASCADE);''') for i in range(len(hw_ids)): cur.execute('ALTER TABLE ratings_tmp ADD hw_{} TEXT DEFAULT \'-\' NOT NULL;'.format(str(i + 1))) query = 'INSERT INTO ratings_tmp SELECT number' for hw_id in hw_ids: query += ', hw_' + str(hw_id[0]) query += ' FROM ratings;' cur.execute(query) cur.execute('DROP TABLE ratings;') cur.execute('ALTER TABLE ratings_tmp RENAME TO ratings;') for i in range(len(hw_ids)): cur.execute('UPDATE homeworks SET id={} WHERE id=?'.format(str(i + 1)), (str(hw_ids[i][0]),)) cur.execute('UPDATE sqlite_sequence SET seq={} WHERE name=\'homeworks\''.format(len(hw_ids))) conn.commit() conn.close() def delete_hws(db_name): conn = sqlite3.connect(db_name) cur = conn.cursor() cur.execute('DELETE FROM homeworks;') cur.execute( 'CREATE TABLE ratings_tmp(number TEXT PRIMARY KEY NOT NULL, CONSTRAINT ratings_students_number_fk FOREIGN KEY (number) REFERENCES students(number) ON DELETE CASCADE ON UPDATE CASCADE);') cur.execute('INSERT INTO ratings_tmp SELECT number FROM ratings;') query = 'DROP TABLE ratings;' cur.execute(query) query = 'ALTER TABLE ratings_tmp RENAME TO ratings;' cur.execute(query) cur.execute('UPDATE sqlite_sequence SET seq = 0 WHERE name = \'homeworks\'') conn.commit() conn.close() def add_absents_column(db_name): conn = sqlite3.connect(db_name) cur = conn.cursor() cur.execute('SELECT seq FROM sqlite_sequence WHERE name=\'absents\';') count = cur.fetchall()[0][0] + 1 cur.execute('ALTER TABLE absents ADD day_{} TEXT DEFAULT \'-\' NOT NULL;'.format(count, )) cur.execute('UPDATE sqlite_sequence SET seq = ? WHERE name = \'absents\';', (count,)) conn.commit() conn.close() def delete_students(db_name): conn = sqlite3.connect(db_name) cur = conn.cursor() cur.execute('DELETE FROM students;') cur.execute('DELETE FROM ratings;') cur.execute('DELETE FROM absents') conn.commit() conn.close() def recreate_absents(db_name): conn = sqlite3.connect(db_name) cur = conn.cursor() cur.execute('DROP TABLE absents') cur.execute('UPDATE sqlite_sequence SET seq = 0 WHERE name=\'absents\'') cur.execute( '''CREATE TABLE absents( number TEXT PRIMARY KEY NOT NULL, CONSTRAINT absents_students_number_fk FOREIGN KEY (number) REFERENCES students (number) ON DELETE CASCADE ON UPDATE CASCADE)''') conn.commit() conn.close() def recreate_ratings(db_name): conn = sqlite3.connect(db_name) cur = conn.cursor() cur.execute('DROP TABLE ratings') cur.execute( '''CREATE TABLE ratings( number TEXT PRIMARY KEY NOT NULL, CONSTRAINT ratings_students_number_fk FOREIGN KEY (number) REFERENCES students (number) ON DELETE CASCADE ON UPDATE CASCADE);''') cur.execute('SELECT seq FROM sqlite_sequence WHERE name=\'homeworks\';') count = cur.fetchall()[0][0] for i in range(count): cur.execute('ALTER TABLE ratings ADD hw_{} TEXT DEFAULT \'-\' NOT NULL;'.format(i + 1)) conn.commit() conn.close() def add_absent(db_name, val): conn = sqlite3.connect(db_name) cur = conn.cursor() cur.execute('INSERT INTO absents VALUES (' + ','.join(val) + ');') conn.commit() conn.close() def update_rating(db_name, val): conn = sqlite3.connect(db_name) cur = conn.cursor() cur.execute('DELETE FROM ratings WHERE number=?;',(val[0],)) cur.execute('INSERT INTO ratings VALUES (' + ','.join(val) + ');') conn.commit() conn.close()
218eaf7901a402ec0c14289bb615c4e596871f2f
tomtang110/comp9021
/quzzi/quiz-4/Week 5 - quiz_4.py
1,319
4.375
4
# Uses National Data on the relative frequency of given names in the population of U.S. births, # stored in a directory "names", in files named "yobxxxx.txt with xxxx being the year of birth. # # Prompts the user for a first name, and finds out the first year # when this name was most popular in terms of frequency of names being given, # as a female name and as a male name. # # Written by *** and Eric Martin for COMP9021 import os first_name = input('Enter a first name: ') directory = 'names' min_male_frequency = 0 male_first_year = None min_female_frequency = 0 female_first_year = None # Replace this comment with your code if not female_first_year: print(f'In all years, {first_name} was never given as a female name.') else: print(f'In terms of frequency, {first_name} was the most popular ' f'as a female name first in the year {female_first_year}.\n' f' It then accounted for {min_female_frequency:.2f}% of all female names.' ) if not male_first_year: print(f'In all years, {first_name} was never given as a male name.') else: print(f'In terms of frequency, {first_name} was the most popular ' f'as a male name first in the year {male_first_year}.\n' f' It then accounted for {min_male_frequency:.2f}% of all male names.' )
05d455120fb3d27e256e0e3321a92b2f42906dab
Shaheel23/Application1
/DICTIONARY/Dictionary_App.py
898
3.53125
4
import json from difflib import get_close_matches data=json.load(open("076 data.json")) def translate(word): word=word.lower() if word in data: return data[word] elif word.title() in data: return data[word.title()] elif word.upper() in data: return data[word.upper()] elif len(get_close_matches(word,data.keys()))>0: yn = input("Did you mean %s instead? Enter Y if yes or N if no!!" % get_close_matches(word,data.keys())[0]) if yn=="Y": return data[get_close_matches(word,data.keys())[0]] elif yn=="N": print("The word doesnt exist!") else: print("We didnt understad your query") else: print("The word doesnt exist!!!..Please recheck") word=input("Enter Word:") output=translate(word) if type(output)==list: for i in output: print(i) else: print(output)
399d7c12e5820d46f68e75f4d30627504cfea920
RuomeiYan/CCC-My-solutions
/2001/01-J3.py
1,284
3.796875
4
hand = input() def output(suit): string = "" for i in suit: string = string + i + " " return string def points(suit): point = 0 for i in suit: if i == "A": point += 4 elif i == "K": point += 3 elif i == "Q": point += 2 elif i == "J": point += 1 if len(suit) == 0: point += 3 elif len(suit) == 1: point += 2 elif len(suit) == 2: point += 1 return str(point) clubs = hand[hand.index("C")+1:hand.index("D")] diamonds = hand[hand.index("D")+1:hand.index("H")] hearts = hand[hand.index("H")+1:hand.index("S")] spades = hand[hand.index("S")+1:len(hand)] print("%11s%29s" % ("Cards Dealt", "Points")) t = "Clubs "+output(clubs) print(t+" "*(40-len(t)-len(points(clubs)))+points(clubs)) t = "Diamonds "+output(diamonds) print(t+" "*(40-len(t)-len(points(diamonds)))+points(diamonds)) t = "Hearts "+output(hearts) print(t+" "*(40-len(t)-len(points(hearts)))+points(hearts)) t = "Spades "+output(spades) print(t+" "*(40-len(t)-len(points(spades)))+points(spades)) total = int(points(clubs)) + int(points(diamonds)) + int(points(hearts)) + int(points(spades)) print("%40s" % ("Total "+str(total)))
87fe03ef3e8bb3654997545884f5771ad94a53bf
naveenakallagunta/python
/large.py
108
3.625
4
a=int(raw_input()) b=int(raw_input()) c=int(raw_input()) if a>b: print a elif b>c: print b else: print c
f883f29a891a7dea272836f5461aa9d6a928286b
Vaishnav2103/Coffee_Machine_Software
/main.py
2,364
4.28125
4
MENU = { "espresso": { "ingredients": { "water": 50, "coffee": 18, }, "cost": 1.5, }, "latte": { "ingredients": { "water": 200, "milk": 150, "coffee": 24, }, "cost": 2.5, }, "cappuccino": { "ingredients": { "water": 250, "milk": 100, "coffee": 24, }, "cost": 3.0, } } profit = 0 resources = { "water": 300, "milk": 200, "coffee": 100 } def is_resources_sufficient(order): for items in order: if order[items] >= resources[items]: print(f"Sorry there is not enough {items}") return False return True def coin_check(): print("Please Insert Coins") total = int(input("How many quarters? ")) * 0.25 total += int(input("How many dimes? ")) * 0.1 total += int(input("How many nickel? ")) * 0.05 total += int(input("How many pennies? ")) * 0.01 return round(total, 2) def sufficient_coin(amount_inserted, cost_order): if amount_inserted >= cost_order: change = amount_inserted - cost_order print(f"Here is ${change} in change") global profit profit += cost_order return True elif cost_order > amount_inserted: print("Sorry that's not enough money. Money refunded") return False def make_coffee(drink_name, order_ingredients): for key in order_ingredients: resources[key] -= order_ingredients[key] print(f"Here is your {drink_name}☕. Enjoy!") #TODO:2 Turn off the coffee Machine by entering "Off to the Prompt" switch = True while switch is not False: #TODO:1 Print Prompt the user choice = input("What would you like? (espreso/latte/cappuccino): ").lower() if choice == "off": switch = False print("Machine Turned off") elif choice == "report": print(f"Water: {resources['water']}ml") print(f"Milk: {resources['milk']}ml") print(f"Coffee: {resources['coffee']}g") print(f"Money: ${profit}") else: drink = MENU[choice] if is_resources_sufficient(drink["ingredients"]): payment = coin_check() if sufficient_coin(payment, drink["cost"]): make_coffee(choice, drink["ingredients"])
7644233fdec2ca3e1c1735a2ac1d7cfe2eae3dd9
danielamendozach/introprogramacion
/práctico_2/ejercicio3.py
164
3.6875
4
def contador(palabra): contador=0 for i in palabra: contador= contador+1 return contador plb=input("Ingrese la palabra: ") print(contador(plb))
e4e8b06d97f1c41482109877cf3b8157e8ab52c7
sreece52/remoteroomalerts
/remoteRoomAlertsServer/modules/motionSensorModule.py
971
3.703125
4
import RPi.GPIO as GPIO from gpiozero import MotionSensor import datetime import time from time import sleep import piCameraModule from piCameraModule import Camera class motionSensor: pir = MotionSensor(25) # setup pin 25 as input for the motion sensor def __init__(self): # configure the GPIO pin mode self.camera = Camera() self.camera.__init__() def detectMotion(self): while(1): #loop that keeps polling the pins if motionSensor.pir.motion_detected: # if the pins status changes we enter this if localTime = '{:%H:%M:%S}'.format(datetime.datetime.now()) print("Motion detected at " + localTime) # prints notification self.camera.takePicture() time.sleep(10) # wait for ten secs else: # if state unchanged we enteclar this condition print("No Motion detected") # simple print time.sleep(1) # sleep for one sec
17165c12fc59bbc416ca26f77b3935baf19d2bb4
ibrahimgurhandev/mycode
/collectedLap/calculator.py
1,151
4.28125
4
#!/usr/bin/env python3 import operator def calculator(): print("Calculator App") def get_operand(): while True: op = input("what will you like to do,\n " "'+' to add, '/' to divide, '-' to subtract, '*' to multiply ").lower() if op in ["+", "/", "-", "*"]: return op def get_nums(count): while True: try: num = float(input(f"Enter {count} number - it can be a float or integer: ")) break except ValueError: print("That's not an a number!") return num def calculate(): op = get_operand() operators = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv} try: print(operators[op](get_nums("first"), get_nums("second"))) except ZeroDivisionError: print("HEYYY! you can't divide by ZERO. DON'T YOU DARE DO THAT AGAIN") calculate() calculate() def main(): calculator() if __name__ == "__main__": main()
14385d5d7aefaf0d324fb617890f4d9139a511aa
jiarmy1125/Kata
/Counting_Duplicates.py
508
3.828125
4
# "aabBcde" -> 2 # 'a' occurs twice and 'b' twice (`b` and `B`) # "indivisibility" -> 1 # 'i' occurs six times # duplicate_count("abcde"), 0 # duplicate_count("abcdea"), 1 # duplicate_count("indivisibility"), 1 def duplicate_count(text): text=text.lower() x=[] for t1 in text: if (text.count(t1)) != 1: x.append(t1) # print(x) x=set(x) print(len(x)) return len(x) duplicate_count("abcde"), 0 duplicate_count("abcdea"), 1 duplicate_count("indivisibility"), 1
9fc36269df64c9f0f11161280e85299b979100a5
NicVic81/PythonbookProjects
/Chapter7.py
8,101
4.40625
4
# message = input("Tell me something, and I will repeat it back to you: ") # print(message) # # name = input("Please enter your name: ") # print("Hello, "+name.title()+"!") #user_promt = 'If you tell us your name we can personalize the message for you.' #user_promt += '\nWhat is your name?' #name = input(user_promt) #print("Hello, "+name.title()+"!") ##using int() to convert strings to intergers #age = input("How old are you? ") #age=int(age) #height = input("How tall are you in inches? ") #height=int(height) #if height >= 36: # print("\nYou're tall enough to ride DIS DICK!") #else: # print("\nYou'll be able to ride DIS DICK when you are "+str((36-height))+" inches taller!") # using % to divide and show the remainder and use to tell if it is odd or even # number = input("Enter a number and I will tell you if it is even or odd: ") # number = int(number) # # if number % 2 == 0: # print("\nThe number "+str(number)+" is even.") # else: # print("\nThe number "+str(number)+" is odd") # ## while loop to count up to 5 # current_number =1 # while current_number <= 5: # print(current_number) ## #The += operator is shorthand for current_number =current_number + 1 # current_number +=1 # prompt = "\nTell me something, and I will repeat it back to you. " # prompt += "\nEnter 'quit' to end the program. : " # # message="" # while message.lower() != 'quit': # message = input(prompt) # print(message) ##trying to refine the code above on my own # first_message = "\nTell me something, and I will repeat it back to you. " # first_message += "\nEnter 'quit' to end the program.\n" # print(first_message) # prompt="Your call holy man: " # message="" # while message.lower() != 'quit': # message = input(prompt) # # Adding an if satement to not print if the word is quit # if message.lower() != 'quit': # print(message+"\n") # # now using a variable to see if the program should keep running # first_message = "\nTell me something, and I will repeat it back to you. " # first_message += "\nEnter 'quit' to end the program.\n" # print(first_message) # prompt="Your call holy man: " # message="" # active = True # while active: # message = input(prompt) # # Adding an if satement to not print if the word is quit # if message.lower() == 'quit': # active = False # else: # print(message+"\n") # #now using a while true statement because it just runs until a break condition is met # direction_prompt = "Please tell me all the cities you have been and I will " # direction_prompt += "make you a list" # direction_prompt += "\nEnter 'quit' any time you want to stop.\n" # print(direction_prompt) # prompt = "City" # city_number = 1 # city_list = [] # while True: # city = input(prompt + ' '+str(city_number)+':') # city_list.append(city) # city_number += 1 # # if city.lower() == 'quit': # break # else: # print('Next city please.\n') # del city_list [-1] # print('You have been to '+str(len(city_list))+' cities.') # print('The cities are:') # # sort this list # for city_print in sorted(city_list): # print(city_print.title()) # # using a continue in a while loop # current_number = 0 # while current_number < 10: # current_number += 1 # # this says if the number is an even number than continue the while loop and if # # not then go to the print function and then continue the while loop # if current_number % 2 ==0: # continue # print(current_number) # exercise 7-4 # directions_prompt = "Tell me the toppings you want on your pizza.\n" # directions_prompt += "Enter quit to stop entering toppings" # topping_prompt = "Enter your pizza topping: " # # print(directions_prompt) # # while True: # topping = input(topping_prompt) # # if topping.lower() == 'quit': # break # else: # print("I will add "+topping.lower()+" to your pizza\n") # exercise 7-5 # age_prompt = "Please tell me your age and I will tell you the price of the ticket" # age_prompt += "\nEnter quit at any time to exit the program\n" # age_enter = "Age: " # print(age_prompt) # while True: # user_age = input(age_enter) # # if user_age.lower() == 'quit': # break # elif int(user_age) < 3: # print("Your ticket is free.\n") # elif int(user_age) < 12: # print("Your ticket is 10 dollars.\n") # else: # print("Your ticket is 12 dollars\n") # exercise 7-6.1 # This exits on a conditional statement # age_prompt = "Please tell me your age and I will tell you the price of the ticket" # age_prompt += "\nEnter quit at any time to exit the program\n" # age_enter = "Age: " # print(age_prompt) # user_age = "" # while str(user_age.lower()) != "quit": # user_age = input(age_enter) # # Would not work without this first if statement because while it is in the loop it first checks it the interger is # # less than three and would error since it is a string # if str(user_age.lower()) == "quit": # print(user_age) # elif int(user_age) < 3: # print("Your ticket is free.\n") # elif int(user_age) < 12: # print("Your ticket is 10 dollars.\n") # else : # print("Your ticket is 12 dollars\n") # Exercise 7-6.2 # This exits using an active variable # age_prompt = "Please tell me your age and I will tell you the price of the ticket" # age_prompt += "\nEnter quit at any time to exit the program\n" # print(age_prompt) # age_enter = "Age: " # keep_running = "True" # while keep_running: # user_age = input(age_enter) # if str(user_age.lower()) == "quit": # print(user_age) # keep_running = False # elif int(user_age) < 3: # print("Your ticket is free.\n") # elif int(user_age) < 12: # print("Your ticket is 10 dollars.\n") # else : # print("Your ticket is 12 dollars\n") # Exercise 7-6.3 # This uses a break to exit # age_prompt = "Please tell me your age and I will tell you the price of the ticket" # age_prompt += "\nEnter quit at any time to exit the program\n" # age_enter = "Age: " # print(age_prompt) # while True: # user_age = input(age_enter) # # if user_age.lower() == 'quit': # break # elif int(user_age) < 3: # print("Your ticket is free.\n") # elif int(user_age) < 12: # print("Your ticket is 10 dollars.\n") # else: # print("Your ticket is 12 dollars\n") # Start with users that need to be verified # and an empty list to hold confirmed users # unconfirmed_users = ['alice', 'brian', 'candace'] # confirmed_users = [] # # # verify each user until there are no more unconfirmed users # # move each verified user into the list of confirmed users # while unconfirmed_users: # current_user = unconfirmed_users.pop() # # print("Verifying user: " + current_user.title()) # confirmed_users.append(current_user) # # #Display all confirmed users # print("\nThe following users have been confirmed:") # for confirmed_user in confirmed_users: # print(confirmed_user.title()) ##Showing how to remove all instance of a value in a list # pets = ['dog','cat','dog','godlfish','cat','rabbit','cat'] # print(pets) # # while 'cat' in pets: # pets.remove('cat') # # print(pets) ##Filling a dictionary with user input responses = {} #Set a flag to indicate that polling is active polling_active = True while polling_active: #Prompt for the person's name and response. name = input("\nWhat is your name? ") response = input("Which mountain would you like to climb someday? ") #Store the response in the dictionary #This means the the dictionary entry for that name gets that response responses[name] = response #Find out if anyone else is going to take the poll. repeat = input("Would you like to let another person respond? (yes/ no) ") if repeat.lower() == 'no': polling_active = False #Polling is complete. Show the results. print("\n--- Poll Results ---") for name, response in sorted(responses.items()): print(name.title() + " would like to climb " + response.title() + ".")
b79cc598d2b49e60e2524fc04f098a3bac6b9f5c
paulojuanifpb/IFTERACT
/ifteractWEB/ifteractApi/Model/Grupo.py
2,050
3.5
4
import sqlite3 def criarTabelaGrupo(conn): cursor = conn.cursor() cursor.execute(""" CREATE TABLE tb_Grupo( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, nome VARCHAR(70) not null, data date, administrador int not null, foreign key (administrador) references tb_Usuario('id') ); """) class Grupo(): def __init__(self, nome, dataCriacao, administrador, participantes = []): self.nome = nome self.dataCriacao = dataCriacao self.administrador = administrador self.participantes = participantes self.participantes.append(administrador) self.moderadors = [] def inserir(self, grupo, conn): cursor = conn.cursor() cursor.execute(""" Select id from tb_Grupo where email = ? and senha = ? ; """, grupo.administrador.email, grupo.administrador.senha) idAdmin = cursor.fetchone() cursor.execute(""" insert into tb_Grupo(nome, data, administrador) values(?,?,?) """,(grupo.nome,grupo.dataCriacao,idAdmin)) conn.commit() def listar(self, conn): cursor = conn.cursor() grupos = [] cursor.execute(""" Select * From tb_Grupo; """) for linha in cursor.fetchall(): nome = linha[1] dataCriacao = linha[2] admin = linha[3] return grupos def atualizar(self,grupo,conn): cursor = conn.cursor() id = int(input("digite o id:\n")) cursor.execute(""" update tb_Grupo set nome = ?,dataCriacao = ?, adiministrador where id = ? """, (grupo.nome,grupo.dataCriacao, grupo.adiministrdor, id)) conn.commit() def deletar(self, conn): cursor = conn.cursor() id = int(input('Digite o id:\n')) cursor.execute(""" delete from tb_Grupo where id = ? """,(id,))
e55aaecfea24242abdaf5a2e164d56688e05a280
PdxCodeGuild/class_mouse
/1 Python/solutions/lab7_rock_paper_scissors_no_if.py
1,525
4.125
4
### Modules ### import random ### Variables ### choices = ['rock', 'paper', 'scissors'] # dictionary to assign inputs to values choice_dict = { 'rock': 0, 'paper': 1, 'scissors': 2 } # Calculate result message using a list of lists. -1 is lose, 0 is tie, 1 is win, 2 is invalid input results = [ #rock paper scissors [0, -1, 1], # rock [1, 0, -1], # paper [-1, 1, 0], # scissors [2, 2, 2] # invalid ] # dictionary to assign message to result result_messages = { -1 : "Sorry you lose", 0 : "It is a tie", 1 : "Congrats, you win!", 2 : "Invalid input" } # dictionary to keep with the theme of "no if" statements play_again = { "yes": True, "no": False } ### Logic ### # Welcome message print('Welcome to Rock, Paper, Scissors!') # Loop for replayability running = play_again["yes"] while running: # Get the users choice and convert to value for result player_choice = choice_dict.get(input(f'Please select one: \n{choices}: '), 3) # Get the computers choice computer_choice = random.choice(choices) # Output computers choice to the screen print(f'Computer chose {computer_choice.capitalize()}') # Overwrite computer_choice with the value needed to determine winner computer_choice = choice_dict.get(computer_choice) # Get the result message and print to screen print(result_messages[results[player_choice][computer_choice]]) # Ifless conditional to keep with "no if" theme running = play_again.get(input('Would you like to play again?'), False)
0208c0d636d4458763ea24a61605d7278c1ca382
busa2004/snippet2
/크루스칼.py
671
3.71875
4
def find_parent(parent, x): if parent[x] != x: parent[x] = find_parent(parent,parent[x]) return parent[x] def union_parent(parent,a,b): a = find_parent(parent,a) b = find_parent(parent,b) if a < b: parent[b] = a else: parent[a] = b def solution(n, costs): v = n edges = [[cost,a,b] for a,b,cost in costs] parent = [0] * (v+1) result = 0 for i in range(1,v+1): parent[i] = i edges.sort() for edge in edges: cost, a, b = edge if find_parent(parent,a) != find_parent(parent,b) : union_parent(parent,a,b) result += cost return result
379d2317c380061f1ff6295c5e34def03a9c88c9
daniel-reich/ubiquitous-fiesta
/jQGT8CNFcMXr55jeb_12.py
69
3.65625
4
def numbers_sum(lst): return sum(x for x in lst if type(x)==int)
e7ba37425cea9e74b248a827a6e2837fc51d7957
nvyacheslav/python-project-lvl1-2
/brain_games/core.py
1,214
3.890625
4
"""Brain-games print-out function module.""" import prompt def welcome_user(): """Prompt User name and print welcome message. Returns: User name """ print('Welcome to the Brain Games!') user = prompt.string('May I have your name? ') print('Hello, {0}!'.format(user)) return user def base_play(*, start_msg, tries_limit, get_question_answer): """Return Base play function. Args: start_msg: start game message tries_limit: tries limit get_question_answer: question-answer generator """ user = welcome_user() print(start_msg) for _ in range(tries_limit): question, answer = get_question_answer() print('Question: {0}'.format(question)) user_answer = prompt.string('Your answer: ', empty=True) if user_answer == answer: print('Correct!') continue wrong_answer_msg = "'{0}' is wrong answer ;(. Correct answer was '{1}'." print(wrong_answer_msg.format(user_answer, answer)) print("Let's try again, {0}!".format(user)) break else: # for - else. Run if no break occurs in cycle for. print('Congratulations, {0}!'.format(user))
0c1cff71aa6d3c9da65408cd5e0a457d19a4906e
p-v-o-s/infrapix
/src/infrapix/core.py
1,318
3.625
4
import numpy, Image def fig_to_data(fig): """ @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it @param fig a matplotlib figure @return a numpy 3D array of RGBA values note: this code was orginally taken from http://www.icare.univ-lille1.fr/wiki/index.php/How_to_convert_a_matplotlib_figure_to_a_numpy_array_or_a_PIL_image """ # draw the renderer fig.canvas.draw() # Get the RGBA buffer from the figure w,h = fig.canvas.get_width_height() buf = numpy.fromstring(fig.canvas.tostring_argb(), dtype=numpy.uint8) buf.shape = (w,h,4) # canvas.tostring_argb gives pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode buf = numpy.roll(buf, 3, axis = 2) return buf def fig_to_img(fig): """ @brief Convert a Matplotlib figure to a PIL Image in RGBA format and return it @param fig a matplotlib figure @return a Python Imaging Library ( PIL ) image note: this code was orginally taken from http://www.icare.univ-lille1.fr/wiki/index.php/How_to_convert_a_matplotlib_figure_to_a_numpy_array_or_a_PIL_image """ # put the figure pixmap into a numpy array buf = fig_to_data(fig) w, h, d = buf.shape return Image.fromstring("RGBA", ( w ,h ), buf.tostring())
da1047ca994c5464c621bf7efd3c420fbffcb9ab
tian0zhi/BaseAlgorithm
/insertsort.py
520
3.625
4
def insertsort(li): '''插入排序''' Length = len(li)# 列表长度 for i in range(1,Length):# 只需排序1 - len(li) for j in range(0,i):# 比较待排序数与已经排好序(有序区)各元素大小 if li[j] > li[i]:# 升序排序,如果待排序数li[i]<有序区li[j],交换他们 temp = li[j] li[j] = li[i] li[i] = temp else:# 如果待排序数li[i]!<有序区li[j],结束这次 待排序数li[i] 排序 break a = [10,9,8,7,6,5,4,3,2,1] insertsort(a) print(a)
80306d26a3c47bcf371238cbe4f6d6ffffe54506
shortdistance/algorithms
/chapter-3/BinarySearchST.py
2,562
3.921875
4
#! usr/bin/python # -*- coding: utf-8 -*- class BinarySearchST(object): def __init__(self): self.__Keys = [] self.__Vals = [] def get(self, key): N = len(self.__Keys) i = self.rank(key) if len(self.__Keys) == 0: return None if i < N and self.__Keys[i] == key: return self.__Vals[i] else: return None def put(self, key, val): N = len(self.__Keys) i = self.rank(key) # If hit, update the value if i < N and self.__Keys[i] == key: self.__Vals[i] = val return # Simlar to insertion sort, put the bigger items to the right and insert # to the right position if hit faild. else: j = N self.__Keys.append(key) self.__Vals.append(val) while i < j: self.__Keys[j] = self.__Keys[j-1] self.__Vals[j] = self.__Vals[j-1] j -= 1 self.__Keys[i] = key self.__Vals[i] = val def rank(self, key): """BinarySearch. Args: key: Search the key in the array. Returns: mid: The position that already exist the key. lo: The position that key can insert. """ lo = 0 hi = len(self.__Keys) - 1 while lo <= hi: mid = lo + (hi - lo) // 2 if self.__Keys[mid] > key: hi = mid - 1 elif self.__Keys[mid] < key: lo = mid + 1 else: return mid return lo def contains(self, key): N = len(self.__Keys) i = self.rank(key) if len(self.__Keys) == 0: return False if i < N and self.__Keys[i] == key: return True else: return False def keys(self): return self.__Keys if __name__ == "__main__": st = BinarySearchST() minlen = int(input('> min length of the word: ')) print('> searching tale.txt...') with open('../test-data/tale.txt') as f: for dataIn in f.readlines(): for word in dataIn.strip().split(): if len(word) < minlen: continue if not st.contains(word): st.put(word, 1) else: st.put(word, st.get(word)+1) max = '' st.put(max, 0) for word in st.keys(): if st.get(word) > st.get(max): max = word print('> most frequent word: %s %s' % (max, st.get(max)))
b7d62ec23aea421f10e333cc1026cb18694f7329
jkbockstael/leetcode
/2020-06-month-long-challenge/day06.py
1,185
4.21875
4
#!/usr/bin/env python3 # Day 6: Queue Reconstruction by Height # # Suppose you have a random list of people standing in a queue. Each person is # described by a pair of integers (h, k), where h is the height of the person # and k is the number of people in front of this person who have a height # greater than or equal to h. Write an algorithm to reconstruct the queue. # # Note: # - The number of people is less than 1,100. class Solution: def reconstructQueue(self, people: [[int]]) -> [[int]]: # Convenience functions for clarity height = lambda person: person[0] taller_in_front = lambda person: person[1] # Sort the input by height descending and number of taller persons in # front ascending sorted_people = sorted(people, key = lambda person: (-height(person), taller_in_front(person))) # Insert into the queue at the correct position queue = [] for person in sorted_people: queue.insert(taller_in_front(person), person) return queue # Test assert Solution().reconstructQueue([[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]) == [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
e02d644668cd8f11b963088c7769ed88ef830c69
kinseyreeves/Interview-Questions
/binary_tree.py
2,149
4.125
4
""" Binary-tree implementation with different functionality. for reference. Kinsey Reeves """ class Node: def __init__(self, data): self.left = None self.right = None self.data = data def insert_node(element, tree): # print(tree.data) if (element <= tree.data): # print("less") if (tree.left): insert_node(element, tree.left) else: tree.left = Node(element) else: # print("right") if (tree.right): insert_node(element, tree.right) else: tree.right = Node(element) def in_order_print_tree(tree): if (tree): in_order_print_tree(tree.left) print(tree.data, end='') in_order_print_tree(tree.right) def create_tree(lst): root = Node(lst[0]) for i in lst[1:]: # print("inserted") insert_node(i, root) return root def print_depth(tree): print("tree depth: ") print(_depth(tree)) def _depth(tree): if (not tree): return 0 if (_depth(tree.left) > _depth(tree.right)): return _depth(tree.left) + 1 return _depth(tree.right) + 1 def size(tree): if not tree: return 0 else: return size(tree.left) + size(tree.right) + 2 def is_balanced(tree): if not tree: return True if abs(_depth(tree.left) - _depth(tree.right)) <= 1: return is_balanced(tree.left) and is_balanced(tree.right) return False def print_levels(tree): print('', end='') open_set = set() open_set.add(tree) while len(open_set) > 0: t = open_set.pop() print(t.data, end=' ') if (t.left): open_set.add(t.left) if (t.right): open_set.add(t.right) print('\n') def print_structure(tree): if (tree): return f'[ {tree.data} ' + f'{print_structure(tree.left)} ' + f' {print_structure(tree.right)}]' else: return 'Nil' t = create_tree([1, 2, 1, 4, 5, 2]) in_order_print_tree(t) print('\n') print_levels(t) print_depth(t) print(is_balanced(t)) print_levels(t) # in_order_print_tree(t) print(print_structure(t))
bf4425eae629200c466ae9a5d012dadc2fdec988
tuneman7/property_scraper
/tester.py
1,376
4.03125
4
#!/usr/bin/python my_input = "bozo" next_string = '' m_len=len(my_input) print(m_len) while m_len > 0: print(m_len) next_string = next_string + my_input[m_len-1] m_len-=1 print(next_string) s1 = '' for c in my_input: s1 = c + s1 # appending chars in reverse order print(s1) s2='' new_string = [s2 + c for c in my_input] print(new_string) input_good = True try: input_word = input("Enter a word:") if not isinstance(input_word, str): print("You have entered zero letters so a vowel density cannot be computed.") input_good=False # if len(input_word.strip()==0): # print("You have entered zero letters so a vowel density cannot be computed.") # input_good=False input_vowel = input("Enter a vowel:") if not isinstance(input_vowel, str): print("You have not entered a vowel letters so a vowel density cannot be computed.") input_good = False if len(input_vowel.strip() == 0): print("You have entered zero letters so a vowel density cannot be computed.") input_good = False if (input_good): print("fido") # number_of_letters = vowel_density(input_word, input_vowel) # print("{} of the letters in {} are \"{}\".".format(number_of_letters, input_word, input_vowel)) except: print("There was an error in the input provided.") ")
3f7967c78dce1cbeb78533ae8285f7083169e4f8
krisograbek/nba_recaps_nlp
/scraper.py
4,158
3.515625
4
import requests import datetime as dt from datetime import timedelta from bs4 import BeautifulSoup def get_games_info(date, days): """ Parameters ---------- date : str (format YYYYMMDD) The most recent day (default is yesterday) days: int, optional The number of days back (default is 7) Returns ------- a list of tuples with a score, a url for each game, and game's date """ # convert to datetime games_date = dt.datetime.strptime(date, "%Y%m%d") games_info = [] if games_date > dt.datetime.now(): print("Date must be in the past. Ending...") return games_info # create a list of last x days dates = [games_date - dt.timedelta(days=x) for x in range(days)] date_strs = [date.strftime("%Y%m%d") for date in dates] print(date_strs) for game_dt in dates: # convert date to format like Wednesday, March 3 games_date_str = game_dt.strftime("%A, %B %#d") print(games_date_str) # find container schedule_url = "https://www.espn.com/nba/schedule/_/date/" games_urls = [] # url to scrape url = schedule_url + game_dt.strftime("%Y%m%d") # get content req = requests.get(url) soup = BeautifulSoup(req.text, "html.parser") container = soup.find("div", id="sched-container") first_header = container.find("h2") first_header_txt = first_header.get_text() table_container = first_header.next_sibling if table_container.next_sibling.name == 'div': table_container = table_container.next_sibling print("Went for the next container") # print(table_container.next_sibling.name) if first_header_txt != games_date_str: print("Something went wrong") return if table_container.get_text() == "No games scheduled": print("No games scheduled on this day") return games_info # first one is a header, we don't want it rows = table_container.find_all("tr")[1:] # each row contains a cell with the score for row in rows: # get the cell with the score score_cell = row.find_all("td")[2] game_score = score_cell.get_text() # score cell contains also the link to the game # we need game's recap, this is why replace() is here game_url = score_cell.a['href'].replace("game", "recap", 1) print(game_url) games_info.append((game_score, game_url, game_dt)) return games_info def get_site_text(date, days): """ Scrapes NBA recap articles from ESPN Parameters ---------- date : str (format YYYYMMDD) The most recent day (default is yesterday) days: int, optional The number of days back (default is 7) Returns ------- list a list of tuples with a game score and article's text Raises ------ AttributeError If the most recent day is in the future """ if (not days) or (days < 1): days = 1 if not date: yesterday = dt.date.today() - timedelta(days=1) date = yesterday.strftime("%Y%m%d") if days > 7: print("Too many days... Reducing to 7") days = 7 url_base = "https://www.espn.com" articles = [] games_info = get_games_info(date, days) for info in games_info: print("Scraping; ", info[1]) req = requests.get(url_base + info[1]) soup = BeautifulSoup(req.text, "html.parser") try: # Finding the main title tag. art_div = soup.find("div", class_ = "article-body") paras = art_div.find_all("p") # get article text from paragraphs articles.append((info[0], " ".join([p.get_text() for p in paras]), info[2])) # sometimes a game recap is not provided. # In that case atr_div is a NoneType and has no find_all() attribute except AttributeError as e: print("No game recap") print("Articles len: ", len(articles)) return articles
c51396de72a07374f96a1d59389e10782335a5c8
beststrelok/pareto
/criteria.py
6,597
3.546875
4
# -*- coding: utf-8 -*- # python3 # import sys # os.getcwd() # print(sys.version) # sys.exit() # gradient-animator.com # http://thecodeplayer.com/walkthrough/animating-css3-gradients # /*----------------------------------------------*/ # !!!! IMPORTANT # import cmd # import platform # from pprint import pprint import pylab from colorama import init from colorama import Fore, Back, Style init() # run init to enable asci console to start coloring def get_input(): a = {} count = int(input("Type in the number of options: ")) print('Type F1(x) and F2(x), for example "2,3":') for i in range(1, count+1): data = input('x'+str(i)+': ') a[i] = [int(x) for x in data.split(',')] a[i].extend(('+', '+', '+', '+')) return a def pareto(a): # F1->max and F2->max for i in a: for j in a: if ((a[i][0] < a[j][0] and a[i][1] < a[j][1]) or (a[i][0] <= a[j][0] and a[i][1] < a[j][1]) or (a[i][0] < a[j][0] and a[i][1] <= a[j][1])): a[i][2] = Fore.RED+'-'.center(8)+Fore.RESET # F1->min and F2->min for i in a: for j in a: if ((a[i][0] > a[j][0] and a[i][1] > a[j][1]) or (a[i][0] >= a[j][0] and a[i][1] > a[j][1]) or (a[i][0] > a[j][0] and a[i][1] >= a[j][1])): a[i][3] = Fore.RED+'-'.center(8)+Fore.RESET # F1->max and F2->min for i in a: for j in a: if ((a[i][0] < a[j][0] and a[i][1] > a[j][1]) or (a[i][0] <= a[j][0] and a[i][1] > a[j][1]) or (a[i][0] < a[j][0] and a[i][1] >= a[j][1])): a[i][4] = Fore.RED+'-'.center(8)+Fore.RESET # F1->min and F2->max for i in a: for j in a: if ((a[i][0] > a[j][0] and a[i][1] < a[j][1]) or (a[i][0] >= a[j][0] and a[i][1] < a[j][1]) or (a[i][0] > a[j][0] and a[i][1] <= a[j][1])): a[i][5] = Fore.RED+'-'.center(8)+Fore.RESET return a def render(a): print(Style.BRIGHT) print(Fore.CYAN) print('/--------------------------------------------------------------\\') print('| | F1(x) | F2(x) | F1 max | F1 min | F1 max | F1 min |') print('| | | | F2 max | F2 min | F2 min | F2 max |') print('|--------------------------------------------------------------|') for item in a: if (item > 1): print(Fore.CYAN+'|--------|--------|--------|--------|--------|--------|--------|'+Fore.RESET) print(Fore.CYAN+'|'+Fore.CYAN+('x'+str(item)).center(8)\ +Fore.CYAN+'|'+Fore.YELLOW+str(a[item][0]).center(8)+Fore.RESET\ +Fore.CYAN+'|'+Fore.YELLOW+str(a[item][1]).center(8)+Fore.RESET\ +Fore.CYAN+'|'+Fore.GREEN+str(a[item][2]).center(8)+Fore.RESET\ +Fore.CYAN+'|'+Fore.GREEN+str(a[item][3]).center(8)+Fore.RESET\ +Fore.CYAN+'|'+Fore.GREEN+str(a[item][4]).center(8)+Fore.RESET\ +Fore.CYAN+'|'+Fore.GREEN+str(a[item][5]).center(8)+Fore.RESET\ +Fore.CYAN+'|') print('\--------------------------------------------------------------/') def _remove_non_dominant(a): for i in range(1, len(a)+1): # {1: [2, 3, '+', '\x1b[31m - \x1b[39m', '+', '+'], 2: [1, 2, '\x1b[31m - \x1b[39m', '+', '+', '+']} if (a[i][2] != '+' and a[i][3] != '+' and a[i][4] != '+' and a[i][5] != '+'): del a[i]; return a def _remove_not_unique(a): b = list(a.values()) unique = [] [unique.append(item) for item in b if item not in unique] return unique def ___distance(x1, y1, x2, y2): return ((x2-x1)**2 + (y2-y1)**2)**.5 def __draw_quantile(graph): to_draw = [] print('graph---') print(graph) closest = [999999999, graph[0][0], graph[0][1]] for i in range(0, len(graph)): if (len(graph) > 1): # 3 x = [i[0] for i in graph] # [2,3,0] y = [i[1] for i in graph] # [3,1,2] for i in range(0, len(graph)-1): dist = ___distance(closest[1], closest[2], x[i+1], y[i+1]) # 5**.5 print(dist) if (dist < closest[0]): closest[0] = dist # 5**.5 closest[1] = x[i+1] # 3 closest[2] = y[i+1] # 1 to_draw.append(closest) del graph[0]; y = [i[2] for i in to_draw] x = [i[1] for i in to_draw] print('----====') print(to_draw) print('====----') pylab.plot(x, y, '-') print('end quantile') def _add_points_and_annotate(unique): x_all = [i[0] for i in unique] y_all = [i[1] for i in unique] pylab.plot(x_all, y_all, 'bs') for i in range(0,len(unique)): pylab.annotate('F(x{0})'.format(i+1), xy=(x_all[i], y_all[i]), xytext=(x_all[i]+.2, y_all[i]+.2)) def _add_lines(unique): for j in range(2, 6): graph = [] for i in range(0, len(unique)): if (unique[i][j] == '+'): graph.append([unique[i][0], unique[i][1]]) __draw_quantile(graph) def _add_ticks(unique): x_all = [i[0] for i in unique] y_all = [i[1] for i in unique] pylab.xticks(range(min(x_all)-1, max(x_all)+2)) pylab.yticks(range(min(y_all)-1, max(y_all)+2)) def plot(a): a = _remove_non_dominant(a) unique = _remove_not_unique(a) _add_points_and_annotate(unique) _add_lines(unique) _add_ticks(unique) pylab.show() # /*------------------------------------------------ # | RUN # ------------------------------------------------*/ if __name__ == "__main__": a = get_input() a = pareto(a) render(a) plot(a) input('Press ENTER to exit...') print() # a = { # 1 : [11, 7, '+', '+', '+', '+'], # 2 : [8, 5, '+', '+', '+', '+'], # 3 : [7, 12, '+', '+', '+', '+'], # 4 : [5, 6, '+', '+', '+', '+'], # 5 : [3, 18, '+', '+', '+', '+'], # 6 : [2, 11, '+', '+', '+', '+'], # 7 : [9, 3, '+', '+', '+', '+'], # 8 : [19, 4, '+', '+', '+', '+'], # 9 : [5, 19, '+', '+', '+', '+'], # } # a = { # 1 : [1, 6, '-', '-', '-', '-'], # 2 : [2, 3, '-', '-', '-', '-'], # 3 : [1, 3, '-', '+', '-', '-'], # 4 : [5, 2, '+', '-', '-', '-'], # 5 : [0, 6, '-', '+', '-', '+'], # 6 : [5, 1, '-', '+', '+', '-'], # 7 : [4, 2, '-', '+', '-', '-'], # 8 : [2, 5, '-', '-', '-', '-'], # 9 : [2, 6, '+', '-', '-', '-'], # 10 : [1, 4, '-', '-', '-', '-'], # }
66a7ba991a006787a23f4b70d5871227847a4d42
leafeon00000/AtCorder
/ABC162/A.py
131
3.734375
4
# coding: utf-8 # 標準入力<str> N = input() ans = "No" for n in range(3): if N[n - 1] == "7": ans = "Yes" print(ans)
26fd02dcafb96baa3b62e9aba360fce5190b16d8
tedgey/while_loop_exercises
/print_a_box.py
582
4.125
4
# Print a box with a given height and width box_width_input = input("What should the width of the box be? ") box_width = int(box_width_input) box_height_input = input("What should the height of the box be? ") box_height = int(box_height_input) width_count = box_width * ("*") inner_width_count = box_width - 2 inner_width_set = inner_width_count * (" ") inner_width = ("*" + str(inner_width_set) + "*") counter = 0 print(width_count) while counter < box_height: counter = counter + 1 if counter < box_height - 1: print(inner_width) print(width_count)
ed5e12a431e0b6f0ace14804a5b4df4c8f037928
mateusrmoreira/Curso-EM-Video
/desafios/desafio13.py
255
3.71875
4
''' 13/03/2020 by jan Mesu Faça um algoritimo que peça o salário de um funcionário e mostre o novo valor com 15% de aumento. ''' salario = float(input('Escreva o salário do funcionário R$ ')) nousalario = salario * (15/100) print(f'O salário do funcionário de R$ {salario}. após o aumento de 15% passa a ser R$ {salario+nousalario:.2f}')
34f161c98eadf74df8bd1696d9776532fea9d1db
niufuren/bigdatr_test
/src/movement.py
293
3.640625
4
class Movement: def __init__(self): self.x = 0 self.y = 0 def move_down(self): self.y = self.y - 1 def move_up(self): self.y = self.y + 1 def move_right(self): self.x = self.x + 1 def move_left(self): self.x = self.x - 1
686c71766a75cc84ce9a1dc389acc6a24ddef2ec
MiniPa/python_demo
/advanced/01 dataStructureAlgorithm 数据结构和算法/1.3 集合 查找符合规则的若干元素.py
1,717
3.78125
4
# 1.3 保留最后N个元素 "collections.deque" ========== deque 队列 from collections import deque def search(lines, pattern, history=5): previous_line = deque(maxlen=history) for line in lines: if pattern in line: previous_line.append(line) yield line, previous_line ## Example use on a file if __name__ == '__main__': with open(r'./somefile.txt') as f: print("start search() ==>") for line, prevlines in search(f, 'welcome', 2): for pline in prevlines: print(pline, end='') print(line, end='') print('-' * 20) ## 队列两端插入元素,时间复杂度是o(1); 列表开头插入或删除时间复杂度是 # 1.4 查找最大或最小的N个元素 ========== heap 堆 import heapq nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] print(heapq.nlargest(3, nums)) print(heapq.nsmallest(3, nums)) portfolio = [ {'name': 'IBM', 'shares': 100, 'price': 91.1}, {'name': 'AAPL', 'shares': 50, 'price': 543.22}, {'name': 'FB', 'shares': 200, 'price': 21.09}, {'name': 'HPQ', 'shares': 35, 'price': 31.75}, {'name': 'YHOO', 'shares': 45, 'price': 16.35}, {'name': 'ACME', 'shares': 75, 'price': 115.65} ] cheap = heapq.nsmallest(3, portfolio, key=lambda s:s['price']) expensive = heapq.nlargest(3, portfolio, key=lambda s:s['price']) nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2] heap = list(nums) heapq.heapify(heap) print(heap) ## 堆特征: heap[0]为最小元素,heapq.heappop()获取元素--时间复杂度O(logN),N为堆大小 ## 根据堆与要取得的集合大小不同,依次采用min()/max(), nlargest()/nsmallest(), sorted(items)[:N] 不同的方式
499511c4243ac71e9e5d0714fe1e70ad1b9eb59b
wilbertgeng/LeetCode_exercise
/934.py
1,501
3.71875
4
"""934. Shortest Bridge""" class Solution(object): def shortestBridge(self, A): """ :type A: List[List[int]] :rtype: int """ m = len(A) n = len(A[0]) res = float('inf') def dfs(i, j): if i < 0 or j < 0 or i >= m or j >= n or A[i][j] == "#" or A[i][j] == 0: return A[i][j] = '#' dfs(i+1, j) dfs(i-1, j) dfs(i, j+1) dfs(i, j-1) def bfs(node, depth, res): directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] q = deque() q.append((node, depth)) visited = set() while q: node, depth = q.popleft() i, j = node if A[i][j] == "#": res = min(res, depth) return visited.add(node) for dir in directions: newX, newY = i + dir[0], j + dir[1] if newX >= 0 and newX < m and newY >= 0 and newY < n and A[newX][newY] != "#" and A[newX][newY] not in visited: q.append(((newX, newY), depth + 1)) for i in range(m): for j in range(n): if A[i][j] == 1: dfs(i, j) break break for i in range(m): for j in range(n): if A[i][j] == 1: bfs((i, j), 0, res) return res
aa8c1b08de127ffd932d4006b8c052ca6ac98a32
AprajitaSingh/numpy
/matrixpro.py
136
3.984375
4
#program to generate a matrix product of two arrays import numpy as np x = [[1, 0], [1, 1]] y = [[3, 1], [2, 2]] print(np.matmul(x, y))
3830da5d26a3e5972b71105d4e8cb2cf1f0dc12b
tomasabril/caesar_cipher
/tutorial.py
2,340
4.03125
4
sample = [1, ["another", "list"], ("a", "tuple")] mylist = ["List item 1", 2, 3.14] mylist[0] = "List item 1 again" # We're changing the item. mylist[-1] = 3.21 # Here, we refer to the last item. mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14} mydict["pi"] = 3.15 # This is how you change dictionary values. mytuple = (1, 2, 3) myfunction = len print(myfunction(mylist)) ##### myfile = open(r"C:\\text.txt", "w") myfile.write("This is a sample string") myfile.close() myfile = open(r"C:\\text.txt") print(myfile.read()) 'This is a sample string' myfile.close() ##### lst1 = [1, 2, 3] lst2 = [3, 4, 5] print([x * y for x in lst1 for y in lst2]) #[3, 4, 5, 6, 8, 10, 9, 12, 15] print([x for x in lst1 if 4 > x > 1]) #[2, 3] # Check if a condition is true for any items. # "any" returns true if any item in the list is true. any([i % 3 for i in [3, 3, 4, 4, 3]]) #True # This is because 4 % 3 = 1, and 1 is true, so any() # returns True. # Check for how many items a condition is true. sum(1 for i in [3, 3, 4, 4, 3] if i == 4) #2 del lst1[0] print(lst1) #[2, 3] del lst1 ##### number = 5 def myfunc(): # This will print 5. print(number) def anotherfunc(): # This raises an exception because the variable has not # been bound before printing. Python knows that it an # object will be bound to it later and creates a new, local # object instead of accessing the global one. print(number) number = 3 def yetanotherfunc(): global number # This will correctly change the global. number = 3 ##### class MyClass(object): common = 10 def __init__(self): self.myvariable = 3 def myfunction(self, arg1, arg2): return self.myvariable # This is the class instantiation classinstance = MyClass() classinstance.myfunction(1, 2) # This class inherits from MyClass. The example # class above inherits from "object", which makes # it what's called a "new-style class". # Multiple inheritance is declared as: # class OtherClass(MyClass1, MyClass2, MyClassN) class OtherClass(MyClass): # The "self" argument is passed automatically # and refers to the class instance, so you can set # instance variables as above, but from inside the class. def __init__(self, arg1): self.myvariable = 3 print(arg1) classinstance = OtherClass("hello") #hello
3b21ae0a2c2ee5357c1ab1742728c6da5158e50f
Zh0nek/web
/lab7/8/Logic-2/4.py
558
3.6875
4
def no_teen_sum(a, b, c): def fix_teen(n): return n if n not in [13,14,17,18,19] else 0 return fix_teen(a)+fix_teen(b)+fix_teen(c) """ Given 3 int values, a b c, return their sum. However, if any of the values is a teen -- in the range 13..19 inclusive -- then that value counts as 0, except 15 and 16 do not count as a teens. Write a separate helper "def fix_teen(n):" that takes in an int value and returns that value fixed for the teen rule. In this way, you avoid repeating the teen code 3 times (i.e. "decomposition"). """
32c6e42d3329373d945241f902653c1bda311f0b
adastraperasper/coding-with-bro
/name.py
120
4
4
name = input("Enter your name please:") age = input("Enter your age please:") print("Olla"+ name+ "You are " +age)
060cd5bef861d2892d8465e2f383079a67685ec4
Samrat0009/Python_REPO1
/#10 Recursion_1/Printing_using_recursion.py
417
3.71875
4
# printing numbers from 1 to n : # base case : 1 to n def print1ton(n): if n==0: return smalloutput = print1ton(n-1) print(n,end=" ") return n = int(input()) print1ton(n) print() #__________________ for reverse : def revprint1ton(n): if n==0: return print(n,end=" ") smalloutput = revprint1ton(n-1) return n = int(input()) revprint1ton(n)
6df3193c7a9d95eb79c0f529b04651926adb0718
ChristianLiinHansen/workspace_python
/Tutorials from Udacity/rename_files.py
812
3.921875
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 9 14:24:42 2014 @author: christian """ #Imports import os #Introduction note print("This program renames the files") def rename_files(): #Get the file names file_list = os.listdir("/home/christian/Dropbox/E14/MasterThesis/PythonTutorials/prank") #Be sure that the computer looks in the right folder saved_path = os.getcwd(); print(saved_path) #Well it did not.. So we change the directory. os.chdir("/home/christian/Dropbox/E14/MasterThesis/PythonTutorials/prank") #Check again... saved_path = os.getcwd() print(saved_path) #Print this print(file_list) for file_name in file_list: os.rename(file_name, file_name.translate(None,"0123456789")) rename_files()
7be4ca18ecb9d35853ba0c5f3a50ac51ace2bbd6
sasha-n17/python_homeworks
/homework_2/task_4.py
290
3.78125
4
text = input('Введите строку из нескольких слов, разделённых пробелами: ') print(f'Количество слов в введённой строке: {len(text.split())}') for i, el in enumerate(text.split()): print(f'{i+1}. {el[:10]}')
fa30adb4bdbd452c2a6494fc0a5a77de4ac86f39
hhoangphuoc/data-structures-and-algorithms
/cracking_the_coding_interview/moderate_problems/intersection.py
912
3.921875
4
# Given two straight line segments, find intersection point of two line segments def slope(p): x1 = p[0][0] x2 = p[1][0] y1 = p[0][1] y2 = p[1][1] return (y2-y1)/float(x2-x1) def intercept(p, m): return p[0][1] - (m * p[0][0]) def is_between(p, intersect_x, intersect_y): if intersect_x > p[0][0] and intersect_x < p[1][0] and intersect_y > p[0][1] and intersect_y < p[1][1]: return True return False def point_of_intersection(a, b): m1 = slope(a) m2 = slope(b) if m1 == m2: return None else: c1 = intercept(a, m1) c2 = intercept(b, m2) intersect_x = (c1 - c2) / (m2 - m1) intersect_y = m1 * intersect_x + c1 # Check if intersection point is witin the line segment range if is_between(a, intersect_x, intersect_y) and is_between(b, intersect_x, intersect_y): return intersect_x, intersect_y return None print point_of_intersection([(1, 2), (3, 4)], [(5, 6), (8, 10)])
a433feba1b669702485fb98c61f1dc8ce5fa536c
sohag2018/Python_G5_6
/group.py
161
4.34375
4
list =[1,5,6,8] # print(list) # print(list[0]) # # for x in list: # print(x) # print("-------------------------") for x in range(3,0,-1): print(list[x])
3511ffe8d56683feaa459c02ef673ed3486ad5b6
LoGOuT92/ZadaniaPython
/main.py
2,842
3.6875
4
def task_5(): import random tablica = [] tablica2 = ['abecadlo', 'z', 'pieca', 'spadlo', 'musztarda', 'pilot', 'telefon'] for i in range(0, 10): tablica.append(random.randint(1, 100)) def sort(tablica): for i in range(len(tablica) - 1, 0, -1): for j in range(i): if tablica[j] > tablica[j + 1]: tablica[j], tablica[j + 1] = tablica[j + 1], tablica[j] sort(tablica) print(tablica) sort(tablica2) print(tablica2) def task_6(): zdanie = input("podaj zdanie: ") tablica = [] tablica = zdanie.split(' ') def sort(tablica): for i in range(len(tablica) - 1, 0, -1): for j in range(i): if tablica[j] > tablica[j + 1]: tablica[j], tablica[j + 1] = tablica[j + 1], tablica[j] def sort2(tablica): for i in range(len(tablica) - 1, 0, -1): for j in range(i): if len(tablica[j]) > len(tablica[j + 1]): tablica[j], tablica[j + 1] = tablica[j + 1], tablica[j] sort(tablica) print(tablica) sort2(tablica) print(tablica) def task_7(): import random def sort(tablica): for i in range(len(tablica) - 1, 0, -1): for j in range(i): if tablica[j] > tablica[j + 1]: tablica[j], tablica[j + 1] = tablica[j + 1], tablica[j] tablica2 = [] for j in range(100): string = "" tablica1 = [] for i in range(random.randrange(3, 9)): tablica1.append(random.randrange(97, 123)) string += (chr(tablica1[i])) tablica2.append(string) sort(tablica2) print(tablica2) def task_71(): import random tablica2 = [] litery = [97, 101, 105, 111, 117, 121] def sort(tablica): for i in range(len(tablica) - 1, 0, -1): for j in range(i): if tablica[j] > tablica[j + 1]: tablica[j], tablica[j + 1] = tablica[j + 1], tablica[j] for j in range(100): string = "" tablica1 = [] for i in range(random.randrange(3, 9)): tablica1.append(random.randrange(97, 123)) if (i + 1) % 3 == 0 and i != 0: if tablica1[i] not in litery: tablica1[i] = random.choice(litery) if i > 0: if tablica1[i] == tablica1[i - 1]: while tablica1[i] == tablica1[i - 1]: tablica1[i] = random.randrange(97, 123) string += (chr(tablica1[i])) tablica2.append(string) sort(tablica2) print(tablica2) def main(): task_5() task_6() task_7() task_71() if __name__ == '__main__': main()
7a16e045fab947c71dc5fbd5edd9bcfde5041cd4
fernandooliveirapimenta/python
/lista/src/ex35.py
122
3.703125
4
r1 = 2 r2 = 2 r3 = 2 if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2: print('triangulo') else: print('náo')
3fb22a1bca5f17f04d6a99ba4a62104b76f316b3
dhnanj2/TS-Codes
/qwewd.py
522
3.703125
4
def rle (input_string) : length_of_input = len(input_string) result = "" i = 0 while i < length_of_input : count = 1 if (i+1 <length_of_input and input_string[i] == input_string[i+1] ) : while (input_string[i] == input_string[i+1]) : count += 1 i += 1 if count>2 : result = result + str(count) + input_string[i] else : result = result + input_string[i] return result print(rle("qqqprqcccaa"))
e69ce1e7885db7b95cce5726361fa154df7705a0
Isthares/Small-Python-Projects
/Special-Pythagorean-Triplet/specialPythagoreanTriplet.py
830
4.375
4
# File Name: specialPythagoreanTriplet.py # Author: Esther Heralta Espinosa # Date: 04/06/19 # Description of the program: A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 # For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. SUM = 1000 def main(): # (a ** 2) + (b ** 2) = (c ** 2) # a + b + c = SUM # because a < b < c then: # c = SUM - a - b and c => 1 ... 1000 # b < c and b > a ==> b => 1 ... 999 # a < b and a < c ==> a => 1 ... 998 for a in range(1, SUM - 1): for b in range (1, SUM): c = SUM - a - b if (a ** 2) + (b ** 2) == (c ** 2) and (a < b < c): print("a: {0}, b: {1}, and c: {2}".format(a, b, c)) if __name__ == "__main__": main()
863ae42e7a48ae3b5b4a361a85c3cef771527f6d
iCodeIN/Data-Structures-and-Algoritms
/Array & Pointers/reverseString.py
424
3.625
4
def reverseWords(self, s: str) -> str: l,r=0, len(s)-1 while l<=r and s[l] == " ": l+=1 while l<=r and s[r] == " ": r-=1 d= collections.deque() word=[] while l<=r: if s[l] == ' ' and word: d.appendleft("".join(word)) word=[] elif s[l] != " ": word.append(s[l]) l+=1 d.appendleft(''.join(word)) return " ".join(d)
a25f81fb8edc28e0b87e2aaf186ef0f3cdb8f5be
lingdantiancai/face-FD-FR
/makerHello/OpenCV-Face-detection/database/insert.py
737
3.671875
4
import sqlite3, sys def insert(a, b, c, d, e ): conn = sqlite3.connect('sayHello.db') c = conn.cursor() c.execute("INSERT INTO COMPANY (DATA1,DATA2,DATA3,DATA4,DATA5) \ VALUES ('%s', '%s', '%s', '%s', '%s' )" % (a, b, c, d, e)); conn.commit() c = conn.cursor() cursor = c.execute("SELECT DATA1,DATA2,DATA3,DATA4,DATA5 from COMPANY") for row in cursor: print "DATA1 = ", row[0] print "DATA2= ", row[1] print "DATA3= ", row[2] print "DATA4= ", row[3] print "DATA5 = ", row[4], "\n"; return "Operation done successfully"; if '__main__' == __name__: if 6 == len(sys.argv): args = sys.argv insert(args[1], args[2], args[3], args[4], args[5]) insert('gaoyuyu','male','2014113605','material','12')
6a26e1cb0fd4d2ddc94b287c0b7be2ff41695762
romanbog/adventOfCode2020
/day7/part2/main.py
1,870
3.65625
4
from collections import defaultdict def search(searchTerm, ruleDict, bagResult): #if(searchTerm not in ruleDict): #return 0 #print(searchTerm) #bagResult.add(searchTerm) summation = 0 setInside = ruleDict[searchTerm] #print(setInside) for element in setInside: print(element) elementArray = element.split() #print(elementArray) #print(elementArray[2]) #bagResult.add(element) #summation += int(elementArray[2]) summation += int(elementArray[2]) #print(''.join(elementArray[1:])) summation *= int(elementArray[2]) * search(''.join(elementArray[1:]), ruleDict, bagResult) return summation with open("example.txt", "r") as f: array = f.read().split('\n') #sets every value to an empty set ruleDict = defaultdict(set) #for every group array.pop() #print(array) for rule in array: #replace newlines print(rule) string = rule.split() #bagName = " " #string[:2] = [bagName] bagName = string[0] bagName += " " bagName += string[1] #bagName = string[:1] #bagName = ' '.join(string[1]) #print(bagName) counter = 5 toAdd = "" #print(string) #print(rule) for i in range(4, len(string), 4): ruleDict[string[i+1] + ' ' + string[i+2]].add(bagName + ' ' + string[i]) #print(ruleDict) ''' while(counter + 1 <= len(string)): toAdd += string[counter] toAdd += " " toAdd += string[counter + 1] counter += 2 #toAdd += " " #print(toAdd) #toAdd += string[counter + 1] #print(toAdd) #ruleDict.update({bagName : toAdd}) #ruleDict.update({toAdd : bagName}) ruleDict[toAdd].add(bagName) toAdd = "" counter += 2 ''' #print(ruleDict) searchTerm = 'shiny gold' #print(ruleDict[searchTerm]) bagResult = set() print(search(searchTerm, ruleDict, bagResult)) print(ruleDict) print(len(bagResult)) #if searchTerm in ruleDict: #print("hi") #print(search(searchTerm, ruleDict)) #print(search(searchTerm, ruleDict)
2a9f25ca132a6007f73737c25b669d92548ee317
SOURABHDHEKALE/introduction-py
/decorator.py
1,307
3.90625
4
# ## GENERATOR ## # # def disp(a,b): # yield a # yield b # result = disp(20,30) # # lst = list(result) # # print(lst) # print(result) # print(type(result)) # print(next(result)) # # # # def show(a,b): # while a<=b: # yield a # a+=1 # result = show(1,5) # print(result) # print(type(result)) # print(next(result)) # print(next(result)) # # # for i in result: # print(i) file = open("sourabh_dhekale.txt","a") #file.write("python is a very easy to understand\n") a = file.write("python is a very easy to understand\n") print(a) # a is represent as a how many carrecter are avalable file.close() raws = 5 for i in range(0,raws): for j in range(1,i+1): print("*",end="") print("\r") raws = 6 for i in range(raws+1,0,-1): for j in range(0,i-1): print("*", end="") print("\r") file = open("sourabh_dhekale.txt") # print(file.tell()) # .tell is represent the file pointer kute ahe te sangato print(file.readline()) # print(file.tell()) #file.seek(0) print(file.readline()) # next line read karayachi asel tar use kela jato # print(file.tell()) file.close() with open("sourabh_dhekale.txt") as file: a = file.read(6) print(a) # ya made close() use karawa lagat nahi
585c2111eee77a105dc8d7e6dce5e2d18b3b13e3
Richard-Joe/python_advanced_programming
/generator/generator_4.py
532
3.5
4
# -*- coding: UTF-8 -*- import time def squares_1(): cursor = 1 while True: yield cursor ** 2 cursor += 1 def squares_2(cursor=1): while True: response = yield cursor ** 2 if response: cursor = int(response) else: cursor += 1 if __name__ == '__main__': # for i in squares_1(): # print (i) # time.sleep(0.5) sq = squares_2() print (next(sq)) print (next(sq)) sq.send(10) print (next(sq)) print (next(sq))
6560684c886e255d88149bc6b6adfdbc0a450e1b
lschnellmann/LPTHW
/ex15.py
1,803
4.59375
5
# Exercise 15: Reading Files # You know how to get input from a user with raw_input or argv, Now you will learn about # reading from a file. You may have to play with this exercise the most to understand what's # going on, so do the exercise carefully and remember your checks. Working with # files is an easy way to erase your work if you are not careful. # This exercise involves writing two files. One is usual usual ex15.py file that you will run, # but the other is named ex15.sample.txt. This second file isn't a script but a plain text # file we'll be reading in our script. Here are teh contents of that file: #____________________________________ #this line imports the module 'argv' which stores arguements for unpacking # at a later time from sys import argv # this line 'unpacks' arguements from argv (or does it assign arguments?) script, filename = argv # this line opens the file that was specified in the command line (it is # 'hardcoded". -- which is bad practice in most cases depending on what # you want to do. txt = open(filename) # this line tells you the filename that is to be read by usign the formatter # %r .. (could it be %s?) print "Here's your file %s :" % filename # txt.read instructs TXT to 'READ' the text in the file, and then print it. print txt.read() #prompts the user to type the file name again, could be changed to # file_again = raw_input("type the file name again >") print "Type the filename again:" file_again = raw_input("> ") #opens the file again from the user prompt, instead of being hardcoded txt_again = open(file_again) #prints out the file print txt_again.read() answer = raw_input("do you want to close \%r ") if answer == "yes": txt_again.close() print "file is closed" quit() print "file is NOT closed"
801997006d2d834cbe60473fa2f96885c3bda5ee
ashNOLOGY/pytek
/Chapter_4/ash_ch4_WordJumbleGame.py
1,514
4.125
4
''' NCC Chapter 4 The Word Jumble Game Project: PyTek Code by: ashNOLOGY ''' #------ The Imports import math import random import os #Greeting the player print("\n\t\t\tWelcome to the Word Jumble Game" "\n\t\t\t-------------------------------") ''' SECTION 1 -We create a list of words -We have python randomly choose a word from that list ''' #Creating the sequence of the words words = ("python", "easy", "ash") #Pick a word at random from "words" random_word = random.choice(words) #Setting up the "correct" // the randomly choosen word to be tested against correct = random_word #checking to make sure CORRECT is picking up a word print("The correct word is: [ ", correct, " ]") ''' SECTION 2 -We take the Random Word and Jumble it ''' #Jumble will store the newly jumbled word jumble = "" new_random_word = "" #setting up the WHILE loop while random_word: #finding the length of the randwom_word, and randomly choosing a position position = random.randrange(len(random_word)) print("The position is: ", position) #adding to the jumble jumble += random_word[position] print("\nThe Jumble word is: ", jumble) #random_word = random_word[:position] + random_word[(position + 1)] #print("\n New Random Word is: ", new_random_word) #creating the new jumbled word #print("\nThe New Random Word is: ", new_random_word) #ENTER to Exit input("\n\n\t\t\tEnter to Exit")
88b87d666101c9874f43a09b594bdbdd6c606216
shank1608/walkman_project
/walkman.py
1,522
3.640625
4
class Walkman(): def __init__(self, songs): self.songs = self.convert_lower(songs) self.status = False # shows walkman status def play(self, song): song_lower = song.lower() if song_lower in self.songs: print("playing song ", song) self.current_song = song_lower self.status = True else: print("song is not in the list") def next(self): newplaylist = self.songs current_index = newplaylist.index(self.current_song) try: next_index = current_index + 1 next_song = newplaylist[next_index] print("playing next song ..", next_song) self.current_song = next_song except IndexError: next_index = 0 next_song = newplaylist[next_index] print("playing next song ..", next_song) self.current_song = next_song def pause(self): if self.status: print("pausing current song", self.current_song) self.status = False else: print("Walkman is already paused") def add_song(self, *new_songs): for song in new_songs: self.songs.append(song.lower()) def remove_song(self, *songs): try: for song in songs: self.songs.remove(song.lower()) except ValueError: print("song is not in the list") def convert_lower(self, songs): return [x.lower() for x in songs]
cfd5cbf4c889dfdce607b5a09c34d97ebbb1f9dd
wuqx/BesTVQoS
/BesTVQoS/BesTVQoS/common/date_time_tool.py
4,630
3.828125
4
# -*- coding: utf-8 -*- '''获取当前日期前后N天或N月的日期''' from time import strftime, localtime, time from datetime import timedelta, date, datetime import calendar year = strftime("%Y",localtime()) mon = strftime("%m",localtime()) day = strftime("%d",localtime()) hour = strftime("%H",localtime()) min = strftime("%M",localtime()) sec = strftime("%S",localtime()) def current_time(): return time() def today(): ''''' get today,date format="YYYY-MM-DD" ''''' return date.today() def todaystr(): ''' get date string, date format="YYYYMMDD" ''' return year+mon+day #def datetime(): # ''''' # get datetime,format="YYYY-MM-DD HH:MM:SS" # ''' # return strftime("%Y-%m-%d %H:%M:%S",localtime()) def datetimestr(): ''''' get datetime string date format="YYYYMMDDHHMMSS" ''' return year+mon+day+hour+min+sec def get_day_of_day(n=0): ''''' if n>=0,date is larger than today if n<0,date is less than today date format = "YYYY-MM-DD" ''' if(n<0): n = abs(n) return date.today()-timedelta(days=n) else: return date.today()+timedelta(days=n) def get_days_region(begin_date, end_date): tmp_begin_date=datetime.strptime(begin_date, '%Y-%m-%d') tmp_end_date=datetime.strptime(end_date, '%Y-%m-%d') days_str_list=[] for i in range((tmp_end_date - tmp_begin_date).days + 1): day=tmp_begin_date+timedelta(days=i) days_str_list.append("%s"%day.strftime('%Y-%m-%d')) return days_str_list def get_days_of_month(year,mon): ''''' get days of month ''' return calendar.monthrange(year, mon)[1] def get_firstday_of_month(year,mon): ''''' get the first day of month date format = "YYYY-MM-DD" ''' days="01" if(int(mon)<10): mon = "0"+str(int(mon)) arr = (year,mon,days) return "-".join("%s" %i for i in arr) def get_lastday_of_month(year,mon): ''''' get the last day of month date format = "YYYY-MM-DD" ''' days=calendar.monthrange(year, mon)[1] mon = addzero(mon) arr = (year,mon,days) return "-".join("%s" %i for i in arr) def get_firstday_month(n=0): ''''' get the first day of month from today n is how many months ''' (y,m,d) = getyearandmonth(n) d = "01" arr = (y,m,d) return "-".join("%s" %i for i in arr) def get_lastday_month(n=0): ''''' get the last day of month from today n is how many months ''' return "-".join("%s" %i for i in getyearandmonth(n)) def getyearandmonth(n=0): ''''' get the year,month,days from today befor or after n months ''' thisyear = int(year) thismon = int(mon) totalmon = thismon+n if(n>=0): if(totalmon<=12): days = str(get_days_of_month(thisyear,totalmon)) totalmon = addzero(totalmon) return (year,totalmon,days) else: i = totalmon/12 j = totalmon%12 if(j==0): i-=1 j=12 thisyear += i days = str(get_days_of_month(thisyear,j)) j = addzero(j) return (str(thisyear),str(j),days) else: if((totalmon>0) and (totalmon<12)): days = str(get_days_of_month(thisyear,totalmon)) totalmon = addzero(totalmon) return (year,totalmon,days) else: i = totalmon/12 j = totalmon%12 if(j==0): i-=1 j=12 thisyear +=i days = str(get_days_of_month(thisyear,j)) j = addzero(j) return (str(thisyear),str(j),days) def addzero(n): ''''' add 0 before 0-9 return 01-09 ''' nabs = abs(int(n)) if(nabs<10): return "0"+str(nabs) else: return nabs def get_today_month(n=0): ''''' 获取当前日期前后N月的日期 if n>0, 获取当前日期前N月的日期 if n<0, 获取当前日期后N月的日期 date format = "YYYY-MM-DD" ''' (y,m,d) = getyearandmonth(n) arr=(y,m,d) if(int(day)<int(d)): arr = (y,m,day) return "-".join("%s" %i for i in arr) if __name__=="__main__": print today() print todaystr() #print datetime() print datetimestr() print get_day_of_day(20) print get_day_of_day(-3) print get_today_month(-3) print get_today_month(3) print get_days_xalis_list("2015-03-21", "2015-03-24")
fa48b6178e3261a403a597e8f487a9027a9e0116
Luciano0000/Pyhon-
/object/私有化/QianFeng024object3.py
522
3.90625
4
#父类的私有属性子类中无法访问与修改 #但是可以通过在子类中重写父类私有属性,访问自己私有属性即可 class Person(object): def __init__(self): self.__money = 200 self.name = 'da' def show1(self): print(self.name,self.__money) class Student(Person): def __init__(self): super().__init__() self.__money = 500 def show(self): print('monney:{},name:{}'.format(self.__money,self.name)) s = Student() s.show() s.show1()
3cf2d780654b54776241949f65fbd9af129ff176
ruanhq/Leetcode
/Algorithm/116.py
2,943
3.765625
4
#116. populating next right pointers in each node: from collections import deque class Solution: def connect(self, root: 'Node') -> 'Node': if not root: return None currentList = deque([root]) while currentList: numberNodeThisLevel = len(currentList) for i in range(numberNodeThisLevel): currentNode = currentList.popleft() if i < numberNodeThisLevel - 1: currentNode.next = currentList[0] if currentNode.left: currentList.append(currentNode.left) if currentNode.right: currentList.append(currentNode.right) return root #Making the right pointers -> similar to that levelwise traversal here. #The storage space required would be O(log-n) #This GBDT model classifies accoutns based only on the direct behavior features #of each account. #a deep feature is a feature that is a function of the #direct features of entities linked to the entity in question. #aggregation function of #flatten binary tree to linked lists -> here class Solution: def connect(self, root: 'None') -> 'Node': if not root: return None currentList = deque([root]) while currentList: numberNodeThisLevel = len(currentList) for i in range(numberNodeThisLevel): currentNode = currentList.popleft() if i < numberNodeThisLevel - 1: currentNode.next = currentList[0] if currentNode.left: currentList.append(currentNode.left) if currentNode.right: currentList.append(currentNode.right) return root #Minimum path sum would be the minimal of local minimum simulating some pseudo-labels, pseudolabels.. We leverage a technique from transfer learning and extract the last hidden layer s output from the first stage model as the input of the second stage.. Then the hidden layers will be related to the ones. 2 5 6 11 10 13 15 11 18 16 #result would be 11. -1 2 1 -1 2 -1 -1 2 1 -1 1 0 -1 2 1 -1 3 -1 tr = [[-1],[3,2],[-3,1,-1]] def minimumTotal(self, triangle: List[List[int]]) -> int: if len(triangle) == 1: return triangle[0][0] for i in range(1, len(triangle)): for j in range(len(triangle[i])): if j > 0: leftAppend = triangle[i - 1][j - 1] else: leftAppend = float("inf") if j < len(triangle[i]) - 1: rightAppend = triangle[i - 1][j] else: rightAppend = float("inf") triangle[i][j] = min(leftAppend, rightAppend) + triangle[i][j] result = min(triangle[len(triangle) - 1]) return result
aff3519643c6a39c5ab8cf318ec43c6e53ed778b
kopwei/euler
/030_digits_fifth_powers/solve.py
312
3.578125
4
def is_wanted_number(num): nums = [int(c) for c in str(num)] return num == sum(map(lambda x: x **5 , nums)) def main(): sum_val = 0 for i in range(10, 295245): if is_wanted_number(i): print(i) sum_val += i print(sum_val) if __name__ == '__main__': main()
c3a7b6bfd8aa3708119a8c990ed7da205a9af175
mateus-ocabral/exercicios-prog
/exercicios/ex006.py
164
3.890625
4
nota1=float(input("Primeira Nota: ")) nota2=float(input("Segunda Nota: ")) print("A media entre {:.2f} e {:.2f} e igual {:.2f}".format(nota1,nota2,(nota1+nota2)/2))
150eefbbc1d77de7a53d386b169653353c4ca735
SantiagoYoung/eVeryDay
/liaoxuefeng/Inheritence_EX.py
1,881
4.46875
4
# coding: utf-8 # 在OOP程序设计中,当我们定义一个class的时候, # 可以从某个现有的class继承,新的class称为子类(Subclass), # 而被继承的class称为基类、父类或超类(Base class、Super class)。 class Animal(object): def run(self): print 'Animal is running...' class Dog(Animal): # pass def run(self): print 'Dog is running...' def eat(self): print 'Eating meat....' class Cat(Animal): # pass def run(self): print 'Cat is running....' # 继承有什么好处?最大的好处是子类获得了父类的全部功能。 dog = Dog() dog.run() cat = Cat() cat.run() # 当子类和父类都存在相同的run()方法时,我们说,子类的run()覆盖了父类的run(), # 在代码运行的时候,总是会调用子类的run()。 # 这样,我们就获得了继承的另一个 好处:多态。 ''' 什么是多态? 当我们定义一个class的时候, 我们实际上就定义的一种数据类型。 我们定义的数据类型和Python自带的数据类型,如str、list、dict一样。 ''' a = list() # a是list类型 b = Animal() # b是Animal类型 c = Dog() # c是Dog类型 def run_twice(animal): animal.run() animal.run() run_twice(Animal()) run_twice(Dog()) run_twice(Cat()) class Tortoise(Animal): def run(self): print 'Tortoise is running slowly....' run_twice(Tortoise()) # 多态的好处就是,当我们需要传入Dog、Cat、Tortoise……时,我们只需要接收Animal类型就可以了,因 # 因为Dog、Cat、Tortoise……都是Animal类型,然后,按照Animal类型进行操作即可。 # 由于Animal类型有run()方法,因此,传入的任意类型, # 只要是Animal类或者子类,就会自动调用实际类型的run()方法,这就是多态的意思:
55de2e60cefade69cad7c1261d3a0cd3e6eaa9e2
qiwsir/LearningWithLaoqi
/PythonAdvance/0801pyad.py
911
3.640625
4
#coding:utf-8 import datetime, calendar def last_friday_1(today): last_Friday = today one_day = datetime.timedelta(days=1) while last_Friday.weekday() != calendar.FRIDAY: last_Friday -= one_day return last_Friday.strftime("%A, %Y-%b-%d") #Friday, year-month-date def last_friday_2(today): last_Friday = today while last_Friday.weekday() != calendar.FRIDAY: last_Friday -= datetime.date.resolution #datetime.date.resolution == 1 day return last_Friday.strftime("%A, %Y-%b-%d") def last_friday_3(today): target_day = calendar.FRIDAY this_day = today.weekday() delta_to_target = (this_day - target_day) % 7 last_Friday = today - datetime.timedelta(days=delta_to_target) return last_Friday.strftime("%A, %Y-%b-%d") if __name__ == "__main__": today = datetime.date.today() lastFriday = last_friday_3(today) print(lastFriday)
22a6aac0c75d09020fb83cdd15b195581c4974c8
urosisakovic/imagelib
/imagelib/utility.py
1,772
3.5
4
import numpy as np from PIL import Image #TODO: form exception in case of an error. def imopen(img_path): """ Given filepath to an image, this function loads it as an numpy.ndarray of type float32. Args: img_path(string): Filepath to an image. Ret: Image as an numpy.ndarray. """ img = Image.open(img_path) img = np.array(img, dtype=np.float32) if len(img.shape) == 3 and img.shape[-1] == 4: img = img[:, :, :-1] return img def imwrite(img_path, img): """ Given filepath and an image in numpy.ndarray format, this functions stores it. Args: img_path(string): Filepath to a desired location. img(numpy.ndarray): RGB or grayscale image. """ img = ((img - img.min()) / (img.max() - img.min())) * 255. img = Image.fromarray(img.astype(np.uint8)) img.save(img_path) # TODO: Extend this to cover RGBA. def rgb2gray(rgb, conv_ratio=None): """ Converts rgb image to grayscale. Args: rgb(numpy.ndarray): RGB image with shape [<height>, <width>, 3]. conv_ration(numpy.ndarray): Denotes how much green, red or blue affect intensity grayscale image. Shape [1, 3]. Form [red_contrib, green_contrib, blue_contrib]. Ret: Grayscale image as an numpy.ndarray of shape [<height>, <width>]. """ if len(rgb.shape) == 2: return rgb if conv_ratio is None: conv_ratio = np.array([0.2989, 0.5870, 0.1140]) return np.dot(rgb, conv_ratio) def scale(a, mn=0, mx=255): min_a = a.min() max_a = a.max() range_a = max_a - min_a goal_range = mx - mn a = ((a - min_a) / range_a) * goal_range + mn return a #TODO def rgb2hsv(): pass #TODO def hsv2rgb(): pass
4f54d2696e3f9a40f18fb4b4f00dfd818a3c7c7f
Vith-MCB/Phyton---Curso-em-Video
/Cursoemvideo/Exercícios/exer24 - SANTO.py
91
3.8125
4
nome = input('Insira o nome da cidade: ') pn = nome.upper().split() print('SANTO' in pn[0])
f1d1f1cef0839f993a59e86f3940f6278c8eb1ee
yeodongbin/PythonLecture
/01.PythonLecture/07.list.py
7,771
3.796875
4
# 리스트, 튜플, 딕셔너리, 셋 l = [10, 20,30, 40] s = {10,20,30,40, 50} d = {'one' : 1, 'two':2} for i in d: print(i) for i in range(10): print(i) #리스트 : 변경이 가능한 자료형, 순서가 있는 자료형 l = [100,200,300,400] print(l) print(type(l)) len(l) del(l) print(l[1]) l[1] = 1000 print(l) print(dir(l)) # 매서드 확인 l.append(300) #l.clear() #l.copy() l.count(300) l.extend([100,200,300]) l.index(400) l.insert(3, 1000) # l[3] 위치에 1000 삽입 l.pop() l.remove(100) l.reverse() l.sort() #sorted() #reversed() #range(Start, stop, step) print(type(range(10))) print(list(range(10))) print(1, list(range(10))) print(2, list(range(5,10))) print(3, list(range(2,10,2))) print(4, list(range(10,5, -1))) print(5, list(range(-10))) for i in 'hello world': print(i) for i in range(10): print(i) else: print('good job') #압축형 list, 지능형 list l = list(range(101)) print(l) ll = [] print(ll) for i in range(10): ll.append(i) print(ll) ll = [i for i in range(10)] print(ll) for i in range(2, 10): for j in range(1,10): print('{} x {} = {}'.format(i, j, i*j)) lll = ['{} x {} = {}'.format(i, j, i*j) for i in range(2, 10) for j in range(1,10)] print(lll) # 배열 array # 리스트 list a = [10, 20, 30] #a[0] = 10, a[1] = 20, a[2] = 30 print(type(a)) for temp in a: print(temp, end=" ") print() a[1] = 2000 for i in range(0,3,1): print(a[i], end=" ") ''' List comprehensions 루프를 한줄로 줄이는 방법 ''' squares = [n**2 for n in range(10)] squares = [] for n in range(10): squares.append(n**2) # 문제 - 4개 값을 가지는 list < 임의값 4개 입력 전체 합을 출력하시오. list = [0, 0, 0, 0] sum = 0 for i in range(0,4): list[i] = int(input("Insert value : ")) sum += list[i] print("전체 합 : {}".format(sum)) list = [] sum = 0 for i in range(0,4): list.append(int(input("Insert value : "))) sum += list[i] print("전체 합 : {}".format(sum)) #초기화(Dynamic array) a = [] #list명은 정했지만 저장 갯수 X a = [0,0,0] #list명은 정하고 저장 갯수 3 a = [0, "yeo", True] #슬라이싱(Slicing) print(a[0]) # 0 print(a[0:2]) # 0 yeo print(a[-1]) # True print(a[:]) # 0 yeo True #추가 append(185), insert expend a.append(185) print(a) a.insert(0,"first") # 0 index "first" 값 print(a) a.insert(1,"second") # 1 index "second" 값 print(a) #변경 list[index] = 값 a[3] = 184 print(a) #삭제 del list[index], remove, pop del a[0] print(a[:]) #병합 + b = ["dongbin", False, 100] c = a + b print(c,len(c),end="\n") # ['yeo', True, 184, "dongbin", False, 100] d = a print(d) d.append(b) print(d,len(d),end="\n") # ['yeo', True, 184, ["dongbin", False, 100]] #반복 d = a * 2 print(d) #검색 string = "my name is yeo dongbin".split() index = string.index("yeo") #11 count = string.count("m") #2 print(index, count) # 얇은 복사, 깊은 복사 alist = [1,2,3,4] blist = alist #얇은 복사 print(id(alist)) print(id(blist)) print(blist) alist[3] = 10 print(blist) #Stack / append() pop() stack = [] stack.append("A") stack.append("B") stack.append("C") print(stack) print(stack.pop()) print(stack) #Queue / append() pop(0) queue = [] queue.append("A") queue.append("B") queue.append("C") print(queue) print(queue.pop(0)) print(queue) # list comprehension : 코드를 짧게 쓰자 list = [] for i in range(6): if (i%2 == 1): list.append(i) print(list) list2 = [i for i in range(6) if i%2 == 1] print(list2) # x 1 ~ 5 , y 1 ~ 5 => x * y => 25가지 # 1*1 1*2 1*3 .... list3 = [x*y for x in range(1,6,1) for y in range(1,6,1)] print(list3) rl = list(range(100,500,100)) print(rl) rl2 = [i for i in range(100,500,100)] print(rl2) rl3 = ['{}*{}={}'.format(i,j,j*j) for i in range(2,10) for j in range(1,10)] print(rl3) rl4 = [ 10 if True else 20] rl5 = [ i for i in range(10) if (i % 2 ==0) ] print(rl5) ### list list = 1D => 2D list2D = [[1,2,3], [4,5,6], [7,8,9]] print(list2D) for i in range(3): for j in range(3): print(list2D[i][j], end=" ") print() # 다양한 리스트 저장 방법 l = [(1,10),(2,20),(3,30),(4,40)] print(l[2][1]) for i in l: print(i) for i, j in l: print(i, j) for i, j in enumerate(range(100,1000,100),1): print(i,j) for i in range(10): pass print('hello world') for i in range(10): continue print('hello world') ############################################################## #문제 - 피보나츠 수열 #1 2 3 5 8 13 21 34 55... 100개 그리고 합 pibo_list = [] pibo_list.append(1) pibo_list.append(2) for i in range(0,8,1): #98 count pibo_list.append(pibo_list[i]+pibo_list[i+1]) print(pibo_list) sum = 0 for element in pibo_list:# 1 2 3 5 8 13 21 34 55 89 print(element) sum += element print("Total : %d" %sum) #문제- 10개 짜리 피보나츠 수열을 list로 구현, 반전 시키지오 pibo = [] pibo.append(0) pibo.append(1) print(pibo) for i in range(2,10,1): temp = pibo[i-2] + pibo[i-1] pibo.append(temp) print(pibo) for i in range(0,5,1) : pibo[i], pibo[len(pibo)-1-i] = pibo[len(pibo)-1-i], pibo[i] pibo2 = [] for i in range(0,10,1) : temp = pibo[9-i] pibo2.append(temp) print(pibo2) #문제 lotto 6자리가 안 겹치도록 만드시오.(10/18 과제) #해답1 from random import * lotto = [0, 0, 0, 0, 0, 0] # list 초기화, 6자리 설정. for i in range(0, 6, 1): # 6회 반복 lotto[i] = randint(1,45) # 1 ~ 45 사이 랜덤값 추출하여 lotto[i]에 설정 count = lotto.count(lotto[i]) # 추출된 lotto[i]값이 lotto 리스트에 있는지 검색. if count == 0: # count값이 0인 경우, 중복값 없으므로 리스트에 추가. lotto.append(lotto[i]) lotto.sort(reverse=True) #lotto.reverse() # index 기분 역전 print(lotto) #해답2 from random import * lotto=[] while(len(lotto)<6): rand_num = randint(1,45) # 1~45 까지 랜덤값을 만들어줌 if (rand_num not in lotto): lotto.append(rand_num) lotto.sort() #순차 정렬 print(lotto) #해답3 from random import * lotto = [] lotto_size = 6 while lotto_size: number = randint(1, 45) count = lotto.count(number) if count == 0: lotto.append(number) lotto_size-=1 print(lotto) ############################################################## #list list = 1D => 2D # 1 2 3 4 5 # 10 9 8 7 6 # 11 12 13 14 15 # 20 19 18 17 16 # 21 22 23 24 25 #1 matrix = [] for i in range(5): row = [] for j in range(5): row.append(0) #[0,0,0,0,0] matrix.append(row) print(matrix) #2 matrix = [[0 for i in range(5)] for j in range(5)] print(matrix) #3 얇은 복사 발생 문제 # matrix = [[0]*5]*5 # print(matrix) num = 1 for i in range(5): if i%2 == 0: for j in range(5): matrix[i][j] = num num += 1 else : for j in range(4,-1,-1): matrix[i][j] = num num += 1 # 출력부 for i in range(5): for j in range(5): print("{0:>2}".format(matrix[i][j]), end=" ") print() print() for arr in matrix: for num in arr: print("{0:>2}".format(num), end=" ") print() print(matrix) #문제 - 2D list(matrix) 90' rotate def rotate_a_matrix_by_90_degred(a): row_length = len(a) column_length = len(a[0]) res =[[0]*row_length for _ in range(column_length)] for r in range(row_length): for c in range(column_length): res[c][row_length-1-r] = a[r][c] return res a = [ [1,2,3,4], [5,6,7,8], [9,10,11,12] ] print(rotate_a_matrix_by_90_degred(a))
766f03aa9656c9e5fdef5140243bb264fb2d3439
marquesarthur/programming_problems
/leetcode/amazon/2020/pythagorean_triplet.py
631
3.8125
4
import math class Solution(object): def __sums_up_to(self, nums, value): for i in nums: target = value - i**2 if target > 0 and math.sqrt(target) in nums: return True return False def triplet(self, nums): # 1st sort numbers nums = sorted(nums) # O (n log n) for i, value in enumerate(nums): aux = nums[:i] + nums[i+1:] if self.__sums_up_to(set(aux), value**2): return True return False a = [3, 1, 4, 6, 5] print(Solution().triplet(a)) b = [10, 4, 6, 12, 5] print(Solution().triplet(b))
0c5e592278d88d440caaa06b5603cb9217557d0e
umair3/pytorial
/basics/strings.py
481
3.84375
4
name = "umaiR anwar" age = 31 print("Hello %s, age = %d" % (name, age)) print('Hello %s, age = %d' % (name, age)) data = ("Umair", 31) print("Name = %s, Age = %d" % data) print(len(name)) print(name.index('a')) print(name.count('t')) # find occurrences print(name.capitalize()) # capitalize fist letter, and other are small print(name.casefold()) # case-less comparison print(name.zfill(15)) # fills with zeros print(name.upper()) print(name.lower()) print(name.split(' '))
de19b6ffadb89f5a9f8fb8c6e4ca996c92413c3c
marinov98/Python_Learning
/MergeSort.py
574
3.859375
4
def isEmpty(arr): if (len(arr) == 0): return True else: return False def mergSort(array): leftIndex = 0 righIndex = 0 leftArray = array[:len(array) // 2] rightArray = array[len(array) // 2:] for i in leftArray: for j in rightArray: if ( i >= j): array[righIndex] = rightArray[righIndex] righIndex+=1 else: array[leftIndex] = leftArray[leftIndex] leftIndex+=1 return array arr = [1, 4, 5, 6, 7, 8, 9, 22, 11] mergSort(arr)
cdc903529640c39cc5ea36367cfd82b065310b87
podgeh1/CloudComputingRepo
/Lab3/palindrome.py
270
4.4375
4
# check if entered is a palindrome # Ask user to enter a word entered_word = raw_input("Enter a word: ") # Reverse the entered word rev_word = reversed(entered_word) # Compare the strings if list(entered_word) == list(rev_word): print("True") else: print("False")
445014959f91bf3e3617c0780556e5eddc85917c
Slawak1/pands-problem-set
/collatz.py
1,640
4.15625
4
# Problem No. 4 # Write a program that asks the user to input any positive integer and outputs the # successive values of the following calculation. At each step calculate the next value # by taking the current value and, if it is even, divide it by two, but if it is odd, multiply # it by three and add one. Have the program end if the current value is one. import sys # import system module # Validation of user data inserted # Try Except statement allow me to replace 'bad looking' error to defined text try: number = int (input ("Enter a positive integer, Please: ")) except: print ('Provided is not a positive Integer. Start program and try again') sys.exit(0) # stops program after error if number < 0: # check if number is negative # if negative number provided, statement is printend. print ("Sorry, but %d is a negative number." %(number)) print ("Start program, and try again." ) sys.exit(0) # will stop the program after negative number provided else: print ("Your number is %d Thank You" %(number)) # while loop is repeated until number = 1 while number != 1: if number%2 == 0: # IF statement checks is division remainder of number divided by 2 is equal 0 number = int (number/2) # if TRUE number is divided by 2 and printed print (number, end=" ") # argument end=" " allow me to print in the same line else: number = int ((number * 3) + 1) #if not TRUE - number is multiplied by 3 and added 1 and printed print (number, end=" ") else: # if number equal 1 while loop ends, and statement is printed print ('\n \n Thank You for calculations')
7583910c5e421980ae02c26498a49d989c7d8aab
acc-cosc-1336/cosc-1336-spring-2018-jjmareck
/src/assignments/assignment9/main.py
892
4.09375
4
#Write import statements for classes invoice and invoice_item from src.assignments.assignment9.invoice import Invoice from src.assignments.assignment9.invoice_item import InvoiceItem ''' LOOK AT THE TEST CASES FOR HINTS Create an invoice object In the loop: Create a new InvoiceItem Create a user controlled loop to continue until y is not typed, in loop... Prompt user for description, quantity, and cost. Add values to the InvoiceItem. Add the InvoiceItem to the invoice object. Once user types a letter other than y display the Invoice to screen ''' invoice=Invoice('ACME Bricks','04202018') keep = 'y' while keep == 'y': description = input('Description: ') quantity = int(input('Quantity: ')) cost = int(input('Cost: ')) invoice.add_invoice_item(InvoiceItem(description,quantity,cost)) keep = input('Keep going? y or n: ') invoice.print_invoice()
b03a201f18f4ea2be4248c6ae808e7058eb9bafe
reetzjl/python-challenge
/PyBank/main.py
1,875
4.09375
4
import csv # Files to Load input = "budget-data.csv" # Variables to Track TotalMonths = 0 TotalRevenue = 0 PrevRevenue = 0 Date = 0 RevenueChange = 0 MaxIncr = {"Date":"", "RevenueChange":0} MaxDecr = {"Date":"", "RevenueChange":0} # Read Files with open(input, newline='') as input: # CSV reader specifies delimiter and variable that holds contents csvreader = csv.reader(input, delimiter=',') # Read the header row first csv_header = next(csvreader) # Read each row of data after the header for row in csvreader: ##The total number of months included in the dataset ##The total net amount of "Profit/Losses" over the entire period TotalMonths = TotalMonths + 1 TotalRevenue = TotalRevenue + int(row[1]) #second part of for loop Date = row[0] if Date == "Jan-10": PrevRevenue = int(row[1]) else: Revenue = int(row[1]) RevenueChange = Revenue - PrevRevenue PrevRevenue = Revenue if RevenueChange > MaxIncr["RevenueChange"]: MaxIncr["Date"] = Date MaxIncr["RevenueChange"] = RevenueChange if RevenueChange < MaxDecr["RevenueChange"]: MaxDecr["Date"] = Date MaxDecr["RevenueChange"] = RevenueChange ##The average change in "Profit/Losses" between months over the entire period average = TotalRevenue / TotalMonths print("Financial Analysis") print("--------------------------") print(f"Total Months: {TotalMonths}") print(f"Total Revenue: {TotalRevenue}") print({0}: {1}".format("Average Change",average)) print(f"Greatest Increase in Profits: {MaxIncr}"") print(f"Greatest Decrease in Profits: {MaxDecr}")
0147f59b076abc8259b16013f605dcfa6c4ac95f
FerhatSaritas/PythonMorselExcersises
/AddMatrices/add.py
1,064
3.6875
4
def add(*argv): sum = list() for j in range(len(argv)): if len(argv[j]) != len(argv[j-1]): raise ValueError("Given matrices are not the same size.") for i in range(len(argv[j])): if len(argv[j][i]) != len(argv[j][i-1]): raise ValueError("Given matrices are not the same size.") for i, li in enumerate(argv[0]): sum.append(list()) for j in li: sum[i].append(0) for arg in argv: for i, li in enumerate(arg): for j, num in enumerate(li): sum[i][j] += num return sum def add_suggested_solution(): def add(*matrices): """Add corresponding numbers in given 2-D matrices.""" combined = [] for rows in zip(*matrices): row = [] for values in zip(*rows): total = 0 for n in values: total += n row.append(total) combined.append(row) return combined
eb3c38b1d66fbde9ef435085876b3dd5851d7c4b
mariabelenceron/Python
/RoadtoCode/07_reloj.py
411
3.703125
4
def calcular_hora_a_segundos(hora): una_hora = 3600 return una_hora * hora def calcular_minuto_a_segundos(minuto): un_minuto = 60 return un_minuto * minuto if __name__ == "__main__": hora = int(input('Ingrese una hora: ')) minuto = int(input('Ingrese los minutos: ')) print(f'{hora}:{minuto} son {calcular_hora_a_segundos(hora) + calcular_minuto_a_segundos(minuto)} segundos')
ccfe63ede5977b2f915a05dbeb7610d7afe8fbc8
qingdaodahui/PSI_KOMI_PYTHON
/BruteForce.py
991
3.625
4
import math import itertools class BruteForceMethod(object): def __init__(self, listOfPoint, strategy): self.listOfPoint = listOfPoint self.strategy = strategy def resolveProblem(self): self.permutations = list(itertools.permutations(self.listOfPoint, len(self.listOfPoint))) result = float("Inf") path = -1 #print(list(self.permutations)) listLen = len(self.permutations) print(listLen) for i in range(0, listLen): sumByStrategy = 0 subListLen = len(self.permutations[i]) for j in range(0, subListLen-1): sumByStrategy += self.strategy.calculate(self.permutations[i][j], self.permutations[i][j+1]) print(sumByStrategy) if sumByStrategy < result: result = sumByStrategy path = i print("BR: " + str(result) + " " + str(path)) print("Path:" + str(self.permutations[path]))
e014aaf1c8ce92771a0ab9395cd7fa5d66a5b65c
deeplhub/python-demo
/src/com/xh/demo/python/demo14_set_05_判断.py
706
3.671875
4
''' Title: 无序列表判断 Description: @author H.Yang @email xhaimail@163.com @date 2020/03/05 ''' print("== 无序列表判断 ==") set1 = {'a', 'b', 'c'} set2 = {'a', 'b' } set3 = {'z', 'v' } # 判断指定集合是否为该方法参数集合的子集。 print("set2.issubset(set1) :", set2.issubset(set1)) # 判断该方法的参数集合是否为指定集合的子集 print("set1.issuperset(set2):", set1.issuperset(set2)) # 判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。 print("set1.isdisjoint(set2):", set1.isdisjoint(set2)) print("set1.isdisjoint(set3):", set1.isdisjoint(set3)) print("a in set1:", 'a' in set1) print("x in set1:", 'x' in set1)
502d1a43415fea94a5eb4b00234c481ae1cc75b0
hevalenc/Analise_com_Pandas_Python
/2_estrutura_dados.py
1,593
4.1875
4
print("\nListas\n") #Criando uma lista chamada animais animais = [1,2,3] print(animais) animais = ["cachorro", "gato", 12345, 6.5] print(animais) #Imprimindo o primeiro elemento da lista print(animais[0]) #Imprimindo o 4 elemento da lista print(animais[3]) #Substituindo o primeiro elemento da lista animais[0] = "papagaio" print(animais) #Removendo gato da lista animais.remove("gato") print(animais) print(len(animais)) print("gato" in animais) print("") lista = [500, 30, 300, 80, 10] print(max(lista)) print(min(lista)) animais.append(["leão", "Cachorro"]) print("") print(animais) animais.extend(["cobra", 6]) print(animais) print(animais.count("leão")) lista.sort() print("") print(lista) print("\nTuplas\n") #As tuplas usam parênteses como sintaxe tp = ("Banana", "Maçã", 10, 50) print(tp[0]) #Diferente das listas as tuplas são imutáveis, o que quer dizer que não podemos alterar os seus elementos #tp[0] = "Laranja" - este tipo de alteração gera erro print(tp.count("Maçã")) print(tp[0:2]) print("\nDicionários\n") #Para criar um dicionário utilizamos as {} dc = {"Maçã":20, "Banana":10, "Laranja":15, "Uva":5} #Dicionários trabalham com o condeito chave e valor print(dc) #Acessando o valor de um dicionário através da chave print(dc["Maçã"]) #Atualizando o valor da Maçã dc["Maçã"] = 25 print(dc) #Retornando todas as chaves do dicionário print(dc.keys()) #Retornando os valores do dicionário print(dc.values()) #Verificando se já existe uma chave no dicionário e caso não exista inserir print(dc.setdefault("Limão", 22)) print(dc)
756ea7144f3c9058fa701633502618609f3fc486
scotontheedge/john
/quiz.py
4,698
4
4
""" Main quiz management logic. Creates the classes and manages the flow through the application. """ # Import classes to be used from classes import Quiz, HighScores # Import methods to be used from login import get_list, check_list, save_list, load_highscores, save_highscores # Import list and dictionary data from questions import questions, categories, difficulty def update_user(user): """ Description: Save the user object Parameters: user: The user object """ # Get the list of users users = get_list() # Check if the user exists in the list of user objects user_exist = check_list(users, user.user_name) if user_exist: # If the user exists replace the old object in the list with the new one and save to file users.remove(user_exist) users.append(user) save_list(users) def create_questions(category, difficulty): """ Description: Retrieves the questions and answers for the chosen category/difficulty Parameters: category: The questions category difficulty: The questions difficulty Returns: A tuple containing the list of questions and the list of answers with dictionaries of choices and correct answers """ return questions[category][difficulty]['questions'], questions[category][difficulty]['answers'] # noinspection PyShadowingNames def create_quiz(user): """ Description: Create, play the quiz and save user and high score info Parameters: user: The user playing the quiz """ # Ask the user to choose a category cat = choose_category() # Ask the user to choose the question difficulty diff = choose_difficulty() # Create the questions and answers based on user requested category/difficulty questions, answers = create_questions(cat, diff) # Tell the user their previous scores and number of attempts at this category/difficulty print("\nYou've had {} attempts at this category/difficulty and your current high score is {}\n" \ .format(user.get_plays(cat, diff), user.get_high_score(cat, diff))) # Create a Quiz object by passing in the questions and answers to play quiz = Quiz(questions, answers) # Play the quiz quiz.play() # Increment the number of play counts for the user for the category/difficulty level user.add_play(cat, diff) # Check and add any user high score updates for the category/difficulty level user.add_high_score(cat, diff, quiz.score) # Load the all time high score table scores = load_highscores() if not scores: # No all time high scores yet created, so create one scores = HighScores() # Check and add the score if a new record scores.add_high_score(cat, diff, quiz.score, user) # Save the high score table save_highscores(scores) # Update user plays and high score info update_user(user) def choose_category(): """ Description: Ask the user to choose a question category Returns: The category name from the categories list """ # Set a 1-indexed counter c_count = 1 # Display the categories using the counter and category name for c in categories: print("{}. {}".format(c_count, c)) # Increment the counter c_count += 1 # Ask the user to choose the category cat = int(input("Choose Category: ")) # Ensure the choice is one of the category number # The range()/len() methods are used to check the number of values in the category if cat not in range(1, len(categories) + 1): # Force the user to choose again if an invalid category choose_category() print("\n") # Return the category and need to take 1 away from the user selection as 0-Based index return categories[cat - 1] def choose_difficulty(): """ Description: Ask the user to choose a question difficulty Returns: The difficulty name from the difficulty list """ # Set a 1-indexed counter d_count = 1 # Display the difficulties using the counter and difficulty name for d in difficulty: print("{}. {}".format(d_count, d)) # Increment the counter d_count += 1 # Ask the user to choose the difficulty diff = int(input("Choose Difficulty: ")) # Ensure the choice is one of the difficulty numbers # The range()/len() methods are used to check the number of values in the difficulties if diff not in range(1, len(difficulty) + 1): choose_difficulty() print("\n") # Return the difficulty and need to take 1 away from the user selection as 0-Based index return difficulty[diff - 1]
a7d944053ec84df6bd786b4ad9d8bb3a80bda715
aminsol/FTP_Server_Client
/Client/client.py
4,309
3.78125
4
#!/usr/bin/python3 # This is client.py file import socket import os import sys import re # For file transfer ftp = 3333 # For communicating to server serverPort = 2222 # For communicating to Client clientPort = 1111 host = socket.gethostname() def send(data): # create a socket object client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # get local machine name # connection to hostname on the port. client_socket.connect((host, serverPort)) # Sending the message client_socket.send(data.encode('ascii')) # Receiving the response respond = client_socket.recv(128) client_socket.close() return respond.decode('ascii') def getSize(filename): if os.path.isfile(filename): filesize = os.stat(filename).st_size else: filesize = False return filesize def download(filename, filesize): filesize = int(filesize) # create TCP transfer socket on client to use for connecting to remote # server. Indicate the server's remote listening port clientSocket_transf = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # get local machine name host = socket.gethostname() # open the TCP transfer connection clientSocket_transf.bind(('', ftp)) # Start listening for incoming connections clientSocket_transf.listen(ftp) connectionSocket,addr = clientSocket_transf.accept() # get the data back from the server filedata = connectionSocket.recv(1024) # creat a file named "filename" and ready to write binary data to the file filehandler = open(filename, 'wb') # store amount of data being recieved totalRecv = len(filedata) # write the data to the file filehandler.write(filedata) print("file size: %d " % filesize) print("Total Recieved: %d " % totalRecv) # loop to read in entire file while totalRecv < filesize: filedata = connectionSocket.recv(1024) totalRecv = totalRecv + len(filedata) filehandler.write(filedata) print("Total Recieved: %d " % totalRecv) # close the file filehandler.close() # close the TCP transfer connection return clientSocket_transf.close() def upload(uInput): # pass communication socket hostname and file name try: fObj = open(uInput, "rb") fileSize = getSize(uInput) clientCtrSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clientCtrSocket.connect((host, ftp)) print("FTP connection established commncing upload") bytesSent = 0 while bytesSent < int(fileSize): fileData = fObj.read() if fileData: bytesSent += clientCtrSocket.send(fileData) print("Sent: " + str(bytesSent) + " / " + str(fileSize)) print("File upload done...\n") fObj.close() except FileNotFoundError: print("File not found...") return "err" except ConnectionError: print("Error connecting to FTP port \n") return "err" uploadFile = re.compile('upload ([\w\.]+)') downloadFile = re.compile('download ([\w\.]+)') lscommand = re.compile('ls ?([\w\.\\\/]*)') command = "" while command != "exit": command = input("Enter your command: ") result = "" if lscommand.match(command): print(send(command)) elif downloadFile.match(command): fileName = downloadFile.match(command)[1] # Asking server to send us a file # if the file exist then server response with file size size = send("download " + fileName) if size != "err": print("Start downloading..") result = download(fileName, size) print("Download is finished!") else: # cannot find the file on the server print("No such file found on the server!") elif uploadFile.match(command): fileName = uploadFile.match(command)[1] fileSize = getSize(fileName) if fileSize: if send("upload " + fileName + " " + str(fileSize)) == "ok": result = upload(fileName) else: print("Please use one of the following command:") print("upload <File Name>") print("download <File Name>") print("ls") print("exit") print("Client connection Closed!")
0f4b7d2976e7a7f7a2f222986cd9bc60cb3bac8c
SRIDEVI98/Python-Programming
/Beginner_level/addlist.py
560
3.65625
4
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: student # # Created: 04/02/2018 # Copyright: (c) student 2018 # Licence: <your licence> #------------------------------------------------------------------------------- def main(): pass if __name__ == '__main__': main() vehicle=[' Bycycle',' Bike',' Car'] vehicle.append(' Bus') vehicle.append(' Train') vehicle.append(' Aeroplan') print"vehicles:" for v in vehicle: print(v)
50c59464d0c6ee2799358bd08ac0e5daeea51f21
giselemanuel/programa-Ifood-backend
/qualified/sem7_qualified_6.py
2,623
3.671875
4
""" Descrição Utilizando as mesmas 8 funções das atividades Pilha- Funções Básicas e Fila - Funções Básicas: cria_fila() tamanho(fila) adiciona(fila, valor) remove(fila): Implemente a função fila_prioridade(lista) que recebe uma lista com números inteiros que representam idades de pessoas. A lista representa a ordem de chegada de cada pessoa. A função deve retornar uma fila que dê prioridade aos idosos. Pessoas com 65 anos ou mais devem ser colocadas no início da fila, mas respeitando o funcionamento normal da fila (primeiro a entrar, primeiro a sair). DICA: VOCÊ PODE UTILIZAR MAIS DE UMA FILA PARA RESOLVER O PROBLEMA ! Lembre-se: A fila funciona seguindo a sequência FIFO(First In First Out) - Primeiro a entrar, primeiro a sair. IMPORTANTE É OBRIGATÓRIO utilizar pelo menos as funções cria_fila, adiciona e remove da atividade anterior para implementar a função fila_prioridade. Seu código não passará nos testes se elas não forem utilizadas. Exemplos Chamada da função fila_prioridade(lista) Entrada: [18, 20, 23, 18] Saída: [18, 20, 23, 18] Entrada: [18, 23, 65, 89] Saída: [65, 89, 18, 23] Entrada: [30, 70] Saída: [70, 30] Entrada: [] Saída: [] Entrada: [65, 30, 70, 18, 66] Saída: [65, 70, 66, 30, 18] """ # função cria_fila -------------------------------- def cria_fila(): nova_fila = [] return nova_fila # função tamanho ---------------------------------- def tamanho(fila): return len(fila) # função adiciona --------------------------------- def adiciona(fila, elemento): fila.append(elemento) return fila # função remove ---------------------------------- def remove(fila): if len(fila) != 0: removido = fila.pop(0) return removido else: fila = None return fila # função fila_prioridade ------------------------- def fila_prioridade(lista): nova_fila = [] lista_preferencial = [] lista_normal = [] cria_fila() # chama função cria_fila() # se lista não estiver vazia if len(lista) != 0: for num in lista: if num < 65: # cria lista normal lista_normal.append(num) elif num >= 65: # cria lista preferêncial lista_preferencial.append(num) lista_preferencial.extend(lista_normal) # unifica as duas lista adiciona(nova_fila, lista_preferencial) else: return lista # declara variáveis ----------------------------- nova_lista = [18, 20, 23, 18] nova_fila = cria_fila() # chama função ---------------------------------- fila_prioridade(nova_lista)
be7cece8a8099fa99e53f287402a9ea0629859b5
giuzis/Oficinas-2
/sensores_plus_motores.py
1,714
3.671875
4
# CamJam EduKit 3 - Robotics # Worksheet 8 - Line Following Robot from time import sleep import time # Import the Time library from gpiozero import Robot, LineSensor, Button # Import the GPIO Zero Library # Set variables for the line detector GPIO pin pinLineFollowerLeft = 11 pinLineFollowerRight = 12 pinLineFollowerCenter = 26 # Easier to think the line sensor as a button linesensorcenter = Button(pinLineFollowerCenter) linesensorleft = Button(pinLineFollowerLeft) linesensorright = Button(pinLineFollowerRight) robot = Robot(left=(23,22), right=(18,17)) # Set the relative speeds of the two motors, between 0.0 and 1.0 leftmotorspeed = 0.3 rightmotorspeed = 0.3 motorforward = (leftmotorspeed, rightmotorspeed) motorbackward = (-leftmotorspeed, -rightmotorspeed) motorright = (-leftmotorspeed, rightmotorspeed) motorleft = (leftmotorspeed, -rightmotorspeed) def iscenteroverblack(): # It is 'pressed' if is over white, otherwise is black return not linesensorcenter.is_pressed def isrightoverblack(): # It is 'pressed' if is over white, otherwise is black return not linesensorright.is_pressed def isleftoverblack(): # It is 'pressed' if is over white, otherwise is black return not linesensorleft.is_pressed tempo = 0.05 try: # repeat the next indented block forever robot.value = motorforward while True: if iscenteroverblack(): robot.value= motorforward # sleep(tempo) if isrightoverblack(): robot.value= motorright # sleep(tempo) if isleftoverblack(): robot.value= motorleft # sleep(tempo) # If you press CTRL+C, cleanup and stop except KeyboardInterrupt: exit()
5adc93ab4c024fab74c528d8b0cb879fe16e567b
vannesspeng/Algorithm
/sort/selectsort.py
537
3.890625
4
# 最优时间复杂度:O(n2) # 最坏时间复杂度:O(n2) # 稳定性:不稳定(考虑升序每次选择最大的情况 def select_sort(alist): n = len(alist) for i in range(0, n): min_index = i for j in range(i+1, n): if alist[j] < alist[min_index]: min_index = j if min_index != i: alist[i], alist[min_index] = alist[min_index], alist[i] return alist alist = [54,226,93,17,77,31,44,55,20] if "__main__" == __name__: print(select_sort(alist))
b66324071df49d068505c48fcac4537905296551
steve-cw-chung/codewars_Python
/3.Take a Ten Minute Walk.py
2,506
4.09375
4
""" You live in the city of Cartesia where all roads are laid out in a perfect grid. You arrived ten minutes too early to an appointment, so you decided to take the opportunity to go for a short walk. The city provides its citizens with a Walk Generating App on their phones -- everytime you press the button it sends you an array of one-letter strings representing directions to walk (eg. ['n', 's', 'w', 'e']). You always walk only a single block in a direction and you know it takes you one minute to traverse one city block, so create a function that will return true if the walk the app gives you will take you exactly ten minutes (you don't want to be early or late!) and will, of course, return you to your starting point. Return false otherwise. Note: you will always receive a valid array containing a random assortment of direction letters ('n', 's', 'e', or 'w' only). It will never give you an empty array (that's not a walk, that's standing still!). """ # My Solution def is_valid_walk(walk): #determine if walk is valid if len(walk) != 10 : return False else: x = 0 y = 0 for i in walk: if(i=='n'): y+=1 elif(i=='s'): y-=1 elif(i=='w'): x-=1 elif(i=='e'): x+=1 else: print("invalid directrion. use n,s,w,e only") return False if(x==0 and y==0): return True else: return False # Solution 1 function isValidWalk(walk) { var dx = 0 var dy = 0 var dt = walk.length for (var i = 0; i < walk.length; i++) { switch (walk[i]) { case 'n': dy--; break case 's': dy++; break case 'w': dx--; break case 'e': dx++; break } } return dt === 10 && dx === 0 && dy === 0 } # Solution 2 function isValidWalk(walk) { function count(val) { return walk.filter(function(a){return a==val;}).length; } return walk.length==10 && count('n')==count('s') && count('w')==count('e'); } # Solution 3 function isValidWalk(walk) { const north = walk.filter(item => { return item === "n" }).length; const south = walk.filter(item => { return item === "s" }).length; const east = walk.filter(item => { return item === "e" }).length; const west = walk.filter(item => { return item === "w" }).length; return walk.length === 10 && north === south && east === west; } # Solution 4 function isValidWalk(walk) { return walk.length == 10 && !walk.reduce(function(w,step){ return w + {"n":-1,"s":1,"e":99,"w":-99}[step]},0) }