blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
5e204a443e3b9f351b676d9f41a2358f2590ac21
ThanitsornMsr/Programming-for-Everybody
/Chapter/Chapter_6.py
2,132
3.796875
4
str1 = 'Hello' str2 = "there" bob = str1 + str2 print(bob) str3 = '123' x = int(str3) + 1 print(x) name = input('Enter: ') print(name) apple = input('Enter: ') x = int(apple) - 10 print(x) fruit = 'banana' letter = fruit[1] print(letter) x = 3 w = fruit[x - 1] print(w) x = len(fruit) print(x) index = 0 while index < len(fruit): letter = fruit[index] print(index, letter) index = index + 1 for letter in fruit: print(letter) word = 'banana' count = 0 for letter in word: if letter == 'a': count = count + 1 print(count) # slicing string s = 'Monty Python' print(s[0:4]) print(s[6:7]) print(s[6:20]) print(s[:2]) print(s[8:]) print(s[:]) # sring concatenation a = 'Hello' b = a + 'There' print(b) c = a + ' ' + 'There' print(c) # using in as a logical operator fruit = 'banana' print('n' in fruit) print('m' in fruit) print('nan' in fruit) if 'a' in fruit: print('Found it!') # string comparison if word == 'banana': print('All right, bananas.') if word < 'banana': print('Your word, ' + word + ', comes before banana.') elif word > 'banana': print('Your word,' + word + ', comes after banana.') else: print('All right, bananas.') # string library print('A' < 'z') greet = 'Hello Bob' zap = greet.lower() print(zap) print(greet) print('Hi There'.lower()) print(dir(str)) # searching string fruit = 'banana' pos = fruit.find('na') print(pos) print(fruit.find('an')) aa = fruit.find('z') print(aa) # search and replace greet = 'Hello Bob' nstr = greet.replace('Bob', 'Jane') print(nstr) nstr = greet.replace('o', 'X') print(nstr) # stripping whitespace greet = ' Hello Bob ' print(greet.lstrip(),'!') print(greet.rstrip()) print(greet.strip()) # prefixes line = 'Please have a nice day' print(line.startswith('Please')) print(line.startswith('please')) # parsing and extracting data = 'From [email protected] Sat Jan 5 09:14:16 2008' atpos = data.find('@') print(atpos) sppos = data.find(' ',atpos) print(sppos) host = data[atpos+1:sppos] print(host)
85175fd2beadd66c25e275671d701c13b2961b0b
ThanitsornMsr/Programming-for-Everybody
/Chapter/Chapter_5.py
1,972
3.84375
4
# Chapter 5 n = 5 while n > 0: print(n) n = n - 1 print('Blastoff!') print(n) while True: line = input('> ') if line == 'done': break print(line) print('Done!') while True: line = input('> ') if line[0] == '#': continue if line == 'done': break print(line) print('Done!') for i in range(5,0,-1): print(i) print('Blastoff!') friends = ['Joseph', 'Glenn', 'Sally'] for friend in friends: print('Happy New Year',friend) print('Done!') largest_to_far = -1 print('Before', largest_to_far) for the_num in [9, 41, 12, 3, 74, 15]: if the_num > largest_to_far: largest_to_far = the_num print(largest_to_far, the_num) print('After', largest_to_far) # counting loop zork = 0 print('Before', zork) for thing in [9, 41, 12, 3, 74, 15]: zork = zork + 1 print(zork, thing) print('After', zork) # summing loop zork = 0 print('Before', zork) for thing in [9, 41, 12, 3, 74, 15]: zork = zork + thing print(zork, thing) print('After', zork) # finding tje average in loop count = 0 sum = 0 print('Before', count, sum) for i in [9, 41, 12, 3, 74, 15]: count = count + 1 sum = sum + i print(count, sum, i) avg = sum / count print('After',count, sum, avg) # filtering in a loop print('Before') for i in [9, 41, 12, 3, 74, 15]: if i > 20: print('Large number', i) print('After') # search using a boolean variable found = False print('Before', found) for i in [9, 41, 12, 3, 74, 15]: if i == 3: found = True print(found, i) break print(found, i) print('After', found) # how to find the smallest value smallest_so_far = None for i in [9, 41, 12, 3, 74, 15]: if smallest_so_far is None: smallest_so_far = i elif i < smallest_so_far: smallest_so_far = i print(smallest_so_far, i) print('After', smallest_so_far)
abccf9b34b1f331b6714bbf84491691eef4e6b12
ThanitsornMsr/Programming-for-Everybody
/Exercise/Exercise_7.py
989
3.8125
4
fname = input('Enter a file name: ') ofname = open(r"C:/Users/User/PycharmProjects/Python_for_EveryOne/"+fname) for line in ofname: line = line.rstrip().upper() print(line) fname = input('Enter a file name: ') ofname = open(r"C:/Users/User/PycharmProjects/Python_for_EveryOne/"+fname) count = 0 sum = 0 for line in ofname: line = line.rstrip() if line.startswith('X-DSPAM-Confidence:'): count = count + 1 a = float(line[20:]) sum = sum + a print('Average spam confidence:', sum/count) fname = input('Enter a file name: ') try: ofname = open(r"C:/Users/User/PycharmProjects/Python_for_EveryOne/"+fname) count = 0 for line in ofname: if line.startswith('Subject:'): count = count + 1 print('There were', count, 'subject lines in',fname) except: if '.' in fname: print('File cannot be opened:', fname) else: print(fname.upper(),"TO YOU - You have been punk'd")
113535781dd630c4dd4ed35d73e7506969d8c6f1
hiepbkhn/itce2011
/StandardLib/parallel/sum_primes_no_parallel.py
1,213
3.859375
4
''' Created on Dec 27, 2012 @author: Nguyen Huu Hiep ''' #!/usr/bin/python # File: sum_primes.py # Author: VItalii Vanovschi # Desc: This program demonstrates parallel computations with pp module # It calculates the sum of prime numbers below a given integer in parallel # Parallel Python Software: http://www.parallelpython.com import math, sys, time def isprime(n): """Returns True if n is prime and False otherwise""" if not isinstance(n, int): raise TypeError("argument passed to is_prime is not of 'int' type") if n < 2: return False if n == 2: return True max = int(math.ceil(math.sqrt(n))) i = 2 while i <= max: if n % i == 0: return False i += 1 return True def sum_primes(n): """Calculates sum of all primes below given integer n""" return sum([x for x in xrange(2, n) if isprime(x)]) ######## start_time = time.time() result = sum_primes(100) print "Sum of primes below 100 is", result inputs = (100000, 100100, 100200, 100300, 100400, 100500, 100600, 100700) for input in inputs: result = sum_primes(input) print "Sum of primes below", input, "is", result print "Time elapsed: ", time.time() - start_time, "s"
2c20b1594b4e36e383abd525c33c382b4ad83fce
hShivaram/pythonPractise
/ProblemStatements/CountTheChocolates.py
692
3.734375
4
# Description : Sanjay loves chocolates. He goes to a shop to buy his favourite chocolate. There he notices there is an # offer going on, upon bringing 3 wrappers of the same chocolate, you will get new chocolate for free. If Sanjay has # m Rupees. How many chocolates will he be able to eat if each chocolate costs c Rupees? # take input here inp = input() m_list = inp.split(",") m = int(m_list[0]) c = int(m_list[1]) no_choc = m // c no_wrapper = m // c while no_wrapper // 3 != 0: no_choc = no_choc + no_wrapper // 3 no_wrapper = no_wrapper // 3 + no_wrapper % 3 print(no_choc) # start writing your code here # dont forget to print the number of chocolates Sanjay can eat
0824e7d93385a87358503bc289e984dfeae38f8c
hShivaram/pythonPractise
/ProblemStatements/EvenorOdd.py
208
4.4375
4
# Description # Given an integer, print whether it is Even or Odd. # Take input on your own num = input() # start writing your code from here if int(num) % 2 == 0: print("Even") else: print("Odd")
7f77696fcdae9a7cef174f92cb12830cde16b3cb
hShivaram/pythonPractise
/ProblemStatements/AboveAverage.py
1,090
4.34375
4
# Description: Finding the average of the data and comparing it with other values is often encountered while analysing # the data. Here you will do the same thing. The data will be provided to you in a list. You will also be given a # number check. You will return whether the number check is above average or no. # # ---------------------------------------------------------------------- # Input: # A list with two elements: # The first element will be the list of data of integers and # The second element will be an integer check. # # Output: # True if check is above average and False otherwise # Take input here # we will take input using ast sys import ast from functools import reduce input_str = input() input_list = ast.literal_eval(input_str) # Remember how we took input in the Alarm clock Question in previous Session? # Lets see if you can finish taking input on your own data = input_list[0] check = input_list[1] s = 0 # start writing your code to find if check is above average of data s = int(reduce(lambda x, y: x + y, data)) avg = s / len(data) print(check > avg)
8134e9b86592e07cf1cd0da048c825ca28038332
hShivaram/pythonPractise
/Practice/practice5.py
207
3.71875
4
n=int(input()) sum=0 digits = [int(x) for x in str(n)] #print(digits) for i in range(len(digits)): sum+=(digits[i]**3) #print(i,sum) #print(sum) if(sum==n): print("True") else: print("False")
ea9f715320a8b82965a8f9a5057eaf6dd2a00470
pmartincalvo/tick-tack-refactor
/solutions/requirements_group_1_solution/rendering.py
1,116
3.84375
4
""" Functions for presenting the state of the game visually. """ from typing import List from solutions.requirements_group_1_solution.board import Board, Cell def render_board(board: Board) -> str: """ Build a visual representation of the state of the board, with the contents of the cells being their marks or, if they are empty, their number id. :param board: the board object. :return: an ASCII art-style representation of the board. """ cells_by_position = board.cells_by_position rendered_board = _render_divider_row(column_count=board.column_count) for row in cells_by_position: rendered_board += "\n" + (_render_cell_row(row)) rendered_board += "\n" + (_render_divider_row(column_count=board.column_count)) return rendered_board def _render_cell_row(row: List[Cell]) -> str: return "|" + "".join([f" {_render_cell(cell)} |" for cell in row]) def _render_cell(cell: Cell) -> str: return cell.number_id if cell.is_empty else cell.contents def _render_divider_row(column_count: int) -> str: return "-" + "-" * (column_count * 4)
91c3151db15aff8be38a477f70dab75f6db92e0b
1180301001SHEN/HIT_evolutionary_computation
/Utils/Distance.py
2,553
4
4
''' @ auther Sr+''' import math class Distance(): '''Some methods to compute the distance''' def compute_EUC_2D(node1, node2): '''EUC_2D distance''' node1_x, node1_y = node1.get_coordinate() node2_x, node2_y = node2.get_coordinate() distance_x = abs(node1_x-node2_x) distance_y = abs(node1_y-node2_y) distance = math.sqrt(distance_x**2+distance_y**2) return round(distance) def compute_Manhattan_2D(node1, node2): '''Manhattan_2D distance''' node1_x, node1_y = node1.get_coordinate() node2_x, node2_y = node2.get_coordinate() distance_x = abs(node1_x-node2_x) distance_y = abs(node1_y-node2_y) distance = distance_x+distance_y return round(distance) def compute_Maximum_2D(node1, node2): '''Maximum_2D distance''' node1_x, node1_y = node1.get_coordinate() node2_x, node2_y = node2.get_coordinate() distance_x = abs(node1_x-node2_x) distance_y = abs(node1_y-node2_y) distance = max(round(distance_x), round(distance_y)) return distance def compute_Geographical(node1, node2): '''Geographical distance''' node1_x, node1_y = node1.get_coordinate() node2_x, node2_y = node2.get_coordinate() PI = 3.141592 deg1_x = round(node1_x) min1_x = node1_x - deg1_x latitude1_x = PI * (deg1_x + 5.0 * min1_x / 3.0) / 180.0 deg1_y = round(node1_y) min1_y = node1_y - deg1_y longitude1_y = PI * (deg1_y + 5.0 * min1_y / 3.0) / 180.0 deg2_x = round(node2_x) min2_x = node2_x - deg2_x latitude2_x = PI * (deg2_x + 5.0 * min2_x / 3.0) / 180.0 deg2_y = round(node2_y) min2_y = node2_y - deg2_y longitude2_y = PI * (deg2_y + 5.0 * min2_y / 3.0) / 180.0 RRR = 6378.388 q1 = math.acos(longitude1_y-longitude2_y) q2 = math.acos(latitude1_x-latitude2_x) q3 = math.acos(latitude1_x+latitude2_x) distance = int(RRR * math.acos(0.5*((1.0+q1)*q2 - (1.0-q1)*q3)) + 1.0) return distance def compute_Pseudo_Euc_2D(node1, node2): '''Pseudo_Euc_2D distance''' node1_x, node1_y = node1.get_coordinate() node2_x, node2_y = node2.get_coordinate() xd = node1_x - node2_x yd = node1_y - node2_y rij = math.sqrt((xd**2 + yd**2)/10.0) tij = round(rij) if tij < rij: dij = tij + 1 else: dij = tij return dij
88b0bb352312bcc91504585873afb726428d2e8c
valours/sandbox-python
/main.py
743
3.734375
4
# coding: utf-8 from random import randint first_names = ["Valentin", "Melanie", "Mathilde"] last_names = ["Bark", "Four", "Quick"] def get_random_name(names): random_index = randint(0, 2) return names[random_index] print(get_random_name(first_names)) freelancer = { "first_name": get_random_name(first_names), "last_name": get_random_name(last_names) } generate_freelancer_requested = input( 'Voulez vous générer un freelance ? [Y/n]') or 'Y' if generate_freelancer_requested not in ['y', 'n']: print("La commande n'existe pas") if generate_freelancer_requested == "y": print(freelancer) elif generate_freelancer_requested == "n": print("On ne te connais pas") else: print('Commande inconnu')
5b54d69790c6d524c1b253b8bec1c32ad83c4bf8
LoktevM/Skillbox-Python-Homework
/lesson_011/01_shapes.py
1,505
4.25
4
# -*- coding: utf-8 -*- # На основе вашего кода из решения lesson_004/01_shapes.py сделать функцию-фабрику, # которая возвращает функции рисования треугольника, четырехугольника, пятиугольника и т.д. # # Функция рисования должна принимать параметры # - точка начала рисования # - угол наклона # - длина стороны # # Функция-фабрика должна принимать параметр n - количество сторон. import simple_draw as sd def get_polygon(n): def draw_shape(point, angle, length): v_first = sd.get_vector(start_point=point, angle=angle, length=length, width=3) sd.line(v_first.start_point, v_first.end_point, width=3) v_next = v_first for i in range(n - 1): if i != n - 2: v_next = sd.get_vector(start_point=v_next.end_point, angle=angle + (360 / n) * (i + 1), length=length, width=3) sd.line(v_next.start_point, v_next.end_point, width=3) else: sd.line(v_next.end_point, v_first.start_point, width=3) return draw_shape draw_triangle = get_polygon(n=8) draw_triangle(point=sd.get_point(200, 200), angle=13, length=100) sd.pause()
8e0b377e80418e6ff51ddc1a5394544c1423dabf
LoktevM/Skillbox-Python-Homework
/lesson_005/02_district.py
1,413
3.609375
4
# -*- coding: utf-8 -*- # Составить список всех живущих на районе и Вывести на консоль через запятую # Формат вывода: На районе живут ... # подсказка: для вывода элементов списка через запятую можно использовать функцию строки .join() # https://docs.python.org/3/library/stdtypes.html#str.join import district.central_street.house1.room1 as cs_h1_r1 import district.central_street.house1.room2 as cs_h1_r2 import district.central_street.house2.room1 as cs_h2_r1 import district.central_street.house2.room2 from district.soviet_street.house1.room1 import folks as people_of_ss_h1_r1 from district.soviet_street.house1.room2 import folks from district.soviet_street.house2 import room1 razdelitel = ', ' people = [] for person in cs_h1_r1.folks: people.append(person) for person in cs_h1_r2.folks: people.append(person) for person in cs_h2_r1.folks: people.append(person) for person in district.central_street.house2.room2.folks: people.append(person) for person in people_of_ss_h1_r1: people.append(person) for person in folks: people.append(person) for person in room1.folks: people.append(person) new_str = razdelitel.join(people) print("На районе живут:", new_str)
f5689f9880f64dd2b65bfd4035b34287388f7a3d
LoktevM/Skillbox-Python-Homework
/lesson_004/practice/02_fractal.py
1,162
3.5625
4
# -*- coding: utf-8 -*- import simple_draw as sd sd.resolution = (1000,600) # нарисовать ветку дерева из точки (300, 5) вертикально вверх длиной 100 point_0 = sd.get_point(300, 5) # написать цикл рисования ветвей с постоянным уменьшением длины на 25% и отклонением на 30 градусов angle_0 = 90 length_0 = 200 delta = 30 next_angle = angle_0 next_length = length_0 next_point = point_0 # сделать функцию branch рекурсивной # def branch(point, angle, length, delta): if length < 1: return v1 = sd.get_vector(start_point=point, angle=angle, length=length, width=3) v1.draw() next_point = v1.end_point next_angle = angle - delta next_length = length * .75 branch(point=next_point, angle=next_angle, length=next_length, delta=delta) for delta in range(0, 51, 10): branch(point=point_0, angle=90, length=150, delta=delta) for delta in range(-50, 1, 10): branch(point=point_0, angle=90, length=150, delta=delta) sd.pause()
ada930e3b25e2523238eea7cb49b332b60da7f7d
madanmeena/python_hackerrank
/Built-Ins/python-sort-sort.py
449
3.703125
4
#https://www.hackerrank.com/challenges/python-sort-sort/problem #!/bin/python3 import math import os import random import re import sys if __name__ == '__main__': nm = input().split() n = int(nm[0]) m = int(nm[1]) arr = [] for _ in range(n): arr.append(input()) k = int(input()) sortedarray=sorted(arr,key=lambda x:int(x.split()[k])) for x in sortedarray: print(x)
19798513e26fdf780beab48cb257b9c1fac3b903
madanmeena/python_hackerrank
/set/py-set-add.py
220
3.84375
4
#https://www.hackerrank.com/challenges/py-set-add/problem # Enter your code here. Read input from STDIN. Print output to STDOUT stamps = set() for _ in range(int(input())): stamps.add(input()) print(len(stamps))
dd1602abd3d3c7f238c29f9f74e53ef6372549f6
dianazmihabibi/Case1_Basic
/assessment.py
1,275
3.640625
4
import re from collections import Counter word_list = [] file = 'sample_text.txt' #Read file Words = open(file, 'r').read() #Removing delimiter and replace with space for char in '\xe2\x80\x93-.,\n\"\'!': Words=Words.replace(char,' ') Words = Words.lower() #Split the words word_list = Words.split() #Find how much the words on the txt files numWords = len(word_list) print '1. Jumlah kata pada text adalah : ', numWords, 'kata\n' #Count words using Counter module count = Counter(word_list).most_common() #Find how much a word would appear in text print '2. Jumlah kemunculan tiap kata dari teks adalah :\n', count, '\n' #Rearrange the position of key and value to value in front of key d = {} for word in word_list: d[word] = d.get(word, 0) + 1 word_freq=[] for key, value in d.items(): word_freq.append((value, key)) word_freq.sort(reverse=True) #Find how much words would appear only once once = [] for value, key in d.items(): if key == 1: once.append((value, key)) print '3. Jumlah kata yang muncul satu kali adalah :\n', once, '\n' #Find words that most appear print '4. Kata yang paling banyak muncul adalah :\n', max(word_freq), '\n' #Find words that less appear print '5. Kata yang paling sedikit muncul adalah :\n', min(word_freq), '\n'
9e9b8426a682a43c61c770039736edf5437b86a3
nandap1/foodCourtOrder
/foodCourt.py
4,061
4.15625
4
''' Displays DeAnza's food court menu and produces a bill with the correct orders for students and staff. ''' #initialize variables food_1 = 0 food_2 = 0 food_3 = 0 food_4 = 0 food_5 = 0 flag = True item = ("") staff = ("") exit_loop = False def display_menu(): print("DEANZA COLLEGE FOOD COURT MENU:") print("1. DeAnza Burger - $5.25") print("2. Bacon Cheese - $5.75") print("3. Mushroom Swiss - $5.95") print("4. Western Burger - $5.95") print("5. Don Cali Burger - $5.95") print("6. Exit") #check if item is between 1 and 5, only then ask for quantity def get_inputs(): global food_1, food_2, food_3, food_4, food_5, staff, exit_loop while not exit_loop: item = input("Enter food:\n").strip() #check if item is between 1 and 5, only then ask for quantity if int(item) > 0 and int(item) < 6: try: quantity = input("Enter quantity: ").strip() #only when quantity is a positive value, it'll go into loop try: if int(quantity) > 0: if item == '1': food_1 += quantity elif item == '2': food_2 += quantity elif item == '3': food_3 += quantity elif item == '4': food_4 += quantity elif item == '5': food_5 += quantity else: print("Invalid quantity, try again.") except: print("Invalid entry. Try order again.") except: break else: if item == '6': exit_loop = True else: print("Invalid entry, try again.") #asking whether staff or student if (food_1 > 0 or food_2 > 0 or food_3 > 0 or food_4 > 0 or food_5 > 0): while flag: staff = input("Are you a student or a staff:").strip().lower() if staff == 'student': break elif staff == 'staff': break else: print('Invalid entry') return food_1, food_2, food_3, food_4, food_5, staff def compute_bill(food_1, food_2, food_3, food_4, food_5, staff): total_after_tax = 0 tax = 0 #total for student (default) total = (food_1 * 5.25) + (food_2 * 5.75) + (food_3 * 5.95) + (food_4 * 5.95) + (food_5 * 5.95) if staff == 'staff': #factor in tax for staff tax = total * 0.09 total_after_tax = total + tax return total, tax, total_after_tax def print_bill(food_1, food_2, food_3, food_4, food_5, total, tax, total_after_tax): print("\nDEANZA COLLEGE ORDER BILL:") print("Quantity of food item(s)") print("DeAnza Burger: ", food_1) print("Bacon Cheese: ", food_2) print("Mushroom Swiss: ", food_3) print("Western Burger: ", food_4) print("Don Cali Burger:", food_5) print("------------------------------------") print("Food item(s) and cost") print("DeAnza Burger: ", food_1 * 5.25) print("Bacon Cheese: ", food_2 * 5.75) print("Mushroom Swiss: ", food_3 * 5.95) print("Western Burger: ", food_4 * 5.95) print("Don Cali Burger:", food_5 * 5.95) print("------------------------------------") print("Total before tax:", round(total,2)) print("------------------------------------") print("Tax amount:", round(tax,2)) print("------------------------------------") print("Total price after tax:", round(total_after_tax,2)) def main(): #python debugger #import pdb; pdb.set_trace() display_menu() food_1, food_2, food_3, food_4, food_5, staff = get_inputs() total, tax, total_after_tax = compute_bill(food_1, food_2, food_3, food_4, food_5, staff) print_bill(food_1, food_2, food_3, food_4, food_5, total, tax, total_after_tax) main()
63a055bb9ee454b6c6ad68defb6b540b6cb74323
Hosen-Rabby/Guess-Game-
/randomgame.py
526
4.125
4
from random import randint # generate a number from 1~10 answer = randint(1, 10) while True: try: # input from user guess = int(input('Guess a number 1~10: ')) # check that input is a number if 0 < guess < 11: # check if input is a right guess if guess == answer: print('Correct, you are a genius!') break else: print('Hey, are you insane! I said 1~10') except ValueError: print('Please enter number')
1b1432b1123ef3781466f454e1b04fca7134dd4f
kvsingh/lyrics-sentiment-analysis
/text_analysis.py
1,277
3.515625
4
import nltk from nltk.corpus import stopwords # Filter out stopwords, such as 'the', 'or', 'and' import pandas as pd import config import matplotlib.pyplot as plt artists = config.artists df1 = pd.DataFrame(columns=('artist', 'words')) df2 = pd.DataFrame(columns=('artist', 'lexicalrichness')) i=0 for artist in artists: f = open('lyrics/' + artist + '-cleaned', 'rb') all_words = '' num_words = 0 raw_text = '' for sentence in f.readlines(): this_sentence = sentence.decode('utf-8') raw_text += this_sentence num_words_this = len(this_sentence.split(" ")) num_words += num_words_this words = raw_text.split(" ") filtered_words = [word for word in words if word not in stopwords.words('english') and len(word) > 1 and word not in ['na', 'la']] # remove the stopwords df1.loc[i] = (artist, num_words) a = len(set(filtered_words)) b = len(words) df2.loc[i] = (artist, (a / float(b)) * 100) i+=1 df1.plot.bar(x='artist', y='words', title='Number of Words for each Artist'); df2.plot.bar(x='artist', y='lexicalrichness', title='Lexical richness of each Artist'); #plt.show()
233b8e8cc6295adad5919285230971a293dfde80
abhaydixit/Trial-Rep
/lab3.py
430
4.1875
4
import turtle def drawSnowFlakes(depth, length): if depth == 0: return for i in range(6): turtle.forward(length) drawSnowFlakes(depth - 1, length/3) turtle.back(length) turtle.right(60) def main(): depth = int(input('Enter depth: ')) drawSnowFlakes(depth, 100) input('Close the graphic window when done.') turtle.mainloop() if __name__ == '__main__': main()
51558f22e5262038813d7f4ce3e5d2ad2836e6d9
Creativeguru97/Python
/Syntax/ConditionalStatementAndLoop.py
1,372
4.1875
4
#Condition and statement a = 300 b = 400 c = 150 # if b > a: # print("b is greater than a") # elif a == b: # print("a and b are equal") # else: # print("a is greater than b") #If only one of statement to excute, we can put togather # if a == b: print("YEAHHHHHHHHH !!!!!!!!!!!") # print("b is greater than a") if b > a else print("a is greater than b") #or print("b is greater than a") if b > a else print("a and b are equal") if a == b else print("a is greater than b") # if a > b and c > a: # print("Both condtions are true!!!!!") # if a > b or c > a: # print("one of the condtions are true!!!!!") fruits = ["apple", "banana", "cherry"] # for x in fruits: # print(x) # # for x in "apple": # print(x) # # for x in fruits: # print(x) # if x == "banana": # break # # for x in fruits: # if x == "banana": # break # print(x) # for x in fruits[0:2]:# Specify the range in the list # print(x) #With continue statement, we can skip the iteration and go next # for x in fruits: # if x == "banana": # continue # print(x) #Specify the range fruits2 = ["apple", "banana", "cherry", "berry", "melon", "grape"] # for x in range(4): # 0 - 3 # print(x) # # for x in range(2, 9): # 2 - 8 # print(x) # # for x in range(2, 30, 3): #Specify the increment value by adding a third parameter
d988912a14c4fe3d6bb41458d10898d6cddc991a
fairypeng/a_python_note
/leetcode/977有序数组的平方.py
825
4.1875
4
#coding:utf-8 """ 给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。   示例 1: 输入:[-4,-1,0,3,10] 输出:[0,1,9,16,100] 示例 2: 输入:[-7,-3,2,3,11] 输出:[4,9,9,49,121]   提示: 1 <= A.length <= 10000 -10000 <= A[i] <= 10000 A 已按非递减顺序排序。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/squares-of-a-sorted-array 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ class Solution(object): def sortedSquares(self, A): """ :type A: List[int] :rtype: List[int] """ return sorted([i*i for i in A]) s = Solution() A = [-4,-1,0,3,10] print(s.sortedSquares(A))
f3ea4fb3de5655c3732e57eb23b625ec6903d210
fairypeng/a_python_note
/leetcode/908最小差值I.py
1,818
4.0625
4
#coding:utf-8 """ 给定一个整数数组 A,对于每个整数 A[i],我们可以选择任意 x 满足 -K <= x <= K,并将 x 加到 A[i] 中。 在此过程之后,我们得到一些数组 B。 返回 B 的最大值和 B 的最小值之间可能存在的最小差值。   示例 1: 输入:A = [1], K = 0 输出:0 解释:B = [1] 示例 2: 输入:A = [0,10], K = 2 输出:6 解释:B = [2,8] 示例 3: 输入:A = [1,3,6], K = 3 输出:0 解释:B = [3,3,3] 或 B = [4,4,4]   提示: 1 <= A.length <= 10000 0 <= A[i] <= 10000 0 <= K <= 10000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/smallest-range-i 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。给定一个整数数组 A,对于每个整数 A[i],我们可以选择任意 x 满足 -K <= x <= K,并将 x 加到 A[i] 中。 在此过程之后,我们得到一些数组 B。 返回 B 的最大值和 B 的最小值之间可能存在的最小差值。   示例 1: 输入:A = [1], K = 0 输出:0 解释:B = [1] 示例 2: 输入:A = [0,10], K = 2 输出:6 解释:B = [2,8] 示例 3: 输入:A = [1,3,6], K = 3 输出:0 解释:B = [3,3,3] 或 B = [4,4,4]   提示: 1 <= A.length <= 10000 0 <= A[i] <= 10000 0 <= K <= 10000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/smallest-range-i 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ class Solution(object): def smallestRangeI(self, A, K): """ :type A: List[int] :type K: int :rtype: int """ A.sort() return max(A[-1]-A[0]-2*K,0) s = Solution() A = [1] k = 0 print(s.smallestRangeI(A,k))
67a57fa1510b08374f7e0401a3f86e9963318652
fairypeng/a_python_note
/leetcode/961重复N次的元素.py
863
3.953125
4
#coding:utf-8 """ 在大小为 2N 的数组 A 中有 N+1 个不同的元素,其中有一个元素重复了 N 次。 返回重复了 N 次的那个元素。   示例 1: 输入:[1,2,3,3] 输出:3 示例 2: 输入:[2,1,2,5,3,2] 输出:2 示例 3: 输入:[5,1,5,2,5,3,5,4] 输出:5   提示: 4 <= A.length <= 10000 0 <= A[i] < 10000 A.length 为偶数 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/n-repeated-element-in-size-2n-array 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ class Solution(object): def repeatedNTimes(self, A): """ :type A: List[int] :rtype: int """ for a in A: if A.count(a) > 1: return a s = Solution() A = [1,2,3,3] print(s.repeatedNTimes(A))
7b8c35c4f8a982eca181334b692273f15fdcb0f1
fairypeng/a_python_note
/cookbook/1.2解压可迭代对象赋值给多个变量.py
536
3.59375
4
def drop_first_last(grades): first,*middle,last = grades return sum(middle) / len(middle) gra = (100,99,89,70,56) print(drop_first_last(gra)) line = 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false' uname,*fields,homedir,sh = line.split(":") print(uname,fields,homedir,sh) uname,*_,homedir,sh = line.split(":") print(uname,homedir,sh) # 实现递归算法 def sumlist(items): header,*tail = items if tail: return header + sumlist(tail) else: return header print(sum([1,10,7,4,5,9]))
c484b80169ea63e5b7df08d01f2433421786ad6e
hhweeks/Mandelbrot
/Mandelbrot.py
2,813
3.875
4
import numpy as np from PIL import Image, ImageDraw """ True/False convergence test """ def test_convergeance(c, maxiter): n = 0 # count iterations z = c while (abs(z) <= 2 and n < maxiter): z = z * z + c n += 1 if (abs(z) > 2): # catch diverging z on n=maxiter return False return True """ Num iterations convergeance function """ def iterations_to_convergeance(c, maxiter): n = 0 z = c while (abs(z) <= 2 and n < maxiter): z = z * z + c n += 1 return n """ loop over all complex vals given bounds """ def mset_from_bounds(maxiter, width, height, xstart, xend, ystart, yend, mystart, myheight): arr = np.empty((width, myheight), dtype=int) for i in range(0, width): for j in range(mystart, (mystart + myheight)): re = xstart + (i / width) * (xend - xstart) im = ystart + (j / height) * (yend - ystart) c = complex(re, im) color = iterations_to_convergeance(c, maxiter) col = j - mystart arr[i, col] = color return arr """ given an array of pixel val, draw image ideas on how to map iterations to color via HSV from: https://tech.io/playgrounds/2358/how-to-plot-the-mandelbrot-set/adding-some-colors """ def draw_array(arr, width, height, maxiter): image = Image.new('HSV', (width, height), (0, 0, 0)) draw = ImageDraw.Draw(image) h = arr.shape[0] w = arr.shape[1] for i in range(w): for j in range(h): color = arr[i, j] hue = int(255 * color / maxiter) sat = 255 value = 255 if color < maxiter else 0 draw.point([i, j], (hue, sat, value)) image.convert('RGB') image.show() """ original BW drawing of arr """ def draw_array_bw(arr, width, height, maxiter): image = Image.new('RGB', (width, height), (0, 0, 0)) draw = ImageDraw.Draw(image) h = arr.shape[0] w = arr.shape[1] for i in range(w): for j in range(h): color = arr[i, j] if color < maxiter: color = 255 else: color = 0 draw.point([i, j], (color, color, color)) image.show() """ takes a list of tuples as args, (proc_num, resultsArr) sorts on process number, concats arrays to draw """ def process_result_pairs(resultPairs, width, height, maxiter): resultPairs = sorted(resultPairs, key=lambda x: x[0]) # sort pairs by process number resultArrays = [] for res in resultPairs: # array of just result arrays resultArrays.append(res[1]) resultsTuple = tuple(resultArrays) finalArray = np.concatenate((resultsTuple), axis=1) #draw_array_bw(finalArray, width, height, maxiter) draw_array(finalArray, width, height, maxiter)
ec7d0173a8eb106805370b4a596256b1c8ac1342
gurmehakk/CO_Assignment_1
/CO_M21_Assignment-main/Simple-Assembler/assembler.py
13,877
3.890625
4
def spaceerror(): for i in statements.keys(): for j in statements[i][0]: x=len(j) j=j.strip() y=len(j) if(x!=y): print("More than one spaces for separating different elements of an instruction at line "+str(statements[i][1])) exit(0) def checkr(): #function to check if any variable is defined after a non var instruction is given i=0 while(statements[i][0][0]=="var"): i=i+1 for j in range(i,len(statements)): if(statements[j][0][0]=="var"): print("variable decleration after an instruction at line "+str(statements[j][1])) exit(0) def error(): b = None for i in statements.keys(): b = error1(statements[i]) if (b == None): continue else: return b return False def error1(l): if (l[0][0] != "var" and l[0][0] not in op.keys()): print("Typo in instruction in line "+str(l[1])) return True elif ((l[0][0] == 'jmp' or l[0][0] == 'jlt' or l[0][0] == 'jgt' or l[0][0] == 'je') and ( l[0][1] in v.keys() or (l[0][1] in reg.keys() and l[0][1] !="FLAGS"))): print("Illegal memory address "+str(l[1])) return True # to check errors in A type instructions elif (l[0][0] == "add" or l[0][0] == "sub" or l[0][0] == "mul" or l[0][0] == "xor" or l[0][0] == "or" or l[0][0] == "and"): if (len(l[0]) != 4): print("Wrong syntax used for instructions in line "+str(l[1])) return True if(l[0][1]=="FLAGS"): print("Illegal use of flags register at line "+str(l[1])) return True elif (l[0][1] not in reg.keys() or l[0][2] not in reg.keys() or l[0][3] not in reg.keys()): print("Typos in register name in line "+str(l[1])) return True # to check errors in both mov type instructions elif(l[0][0]=="mov"): if (len(l[0]) != 3): print("Wrong syntax used for instructions in line "+str(l[1])) return True if (l[0][1] == "FLAGS"): print("Illegal use of flags register at line "+str(l[1])) return True elif(l[0][2][0:1]=="R"): if(l[0][2] not in reg.keys()): print("Invalid register name in line "+str(l[1])) return True elif(l[0][2][0:1]=="$"): if (int(l[0][2][1:],10)<0 and int(l[0][2][1:],10)>255): print("Invalid immidiete in line "+str(l[1])) return True # to check errors in B type instructions elif ( l[0][0] == "rs" or l[0][0] == "ls"): if (len(l[0]) != 3): print("Wrong syntax used for instructions in line "+str(l[1])) return True if (l[0][1] == "FLAGS" or l[0][2]=="FLAGS"): print("Illegal use of flags register") return True elif (l[0][1] not in reg.keys()): print("Typos in register name "+str(l[1])) return True elif (l[0][2] not in reg.keys() and l[0][2] not in v.keys()): print("invalid register/variable name/immidiete in line "+str(l[1])) # to check errors in C type instructions elif (l[0][0] == "div" or l[0][0] == "not" or l[0][0] == "cmp"+str(l[1])): if (len(l[0]) != 3): print("Wrong syntax used for instructions in line "+str(l[1])) return True if(l[0][0]=="not" and l[0][1]=="FLAGS"): print("Illegal use of flags register") return True elif (l[0][2] not in reg.keys()): print("Typos in register name in line "+str(l[1])) return True elif (l[0][1] not in reg.keys()): print("Typo in register name in line "+str(l[1])) # to check errors in D type instructions elif (l[0][0] == "ld" or l[0][0] == "st"): if (len(l[0]) != 3): print("Wrong syntax used for instructions in line "+str(l[1])) return True if (l[0][1] not in reg.keys()): print("Typo in register name in line "+str(l[1])) return True if(l[0][0]=="ld" and l[0][1]=="FLAGS"): print("Illegal use of flags register") return True if l[0][2] not in v.keys(): print("Typo in memory address in line "+str(l[1])) return True # to check errors in E type instructions elif (l[0][0] == "jmp" or l[0][0] == "jlt" or l[0][0] == "jgt" or l[0][0] == "je"): if (len(l[0]) != 2): print("Wrong syntax used for instructions in line "+str(l[1])) return True if l[0][1] not in labels.keys(): print("Typo in memory address in line "+str(l[1])) return True # to check errors in F type instructions elif (l[0][0] == "hlt"): if (len(l[0]) != 1): print("Wrong syntax used for instructions in line "+str(l[1])) return True def convert1(a): # convert integer to 16 bit binary bnr = bin(a).replace('0b', '') x = bnr[::-1] while len(x) < 16: x += '0' bnr = x[::-1] return bnr def convert(a): # convert integer to 8 bit binary bnr = bin(a).replace('0b', '') x = bnr[::-1] while len(x) < 8: x += '0' bnr = x[::-1] return bnr def mov1(l): s = "00010" s = s + reg[l[1]][0] s = s + convert(int(l[2][1:])) return s def mov2(l): s = "0001100000" s = s + reg[l[1]][0] s = s + reg[l[2]][0] return s def add(l): s = "0000000" s = s + reg[l[1]][0] s = s + reg[l[2]][0] s = s + reg[l[3]][0] return s def sub(l): s = "0000100" s = s + reg[l[1]][0] s = s + reg[l[2]][0] s = s + reg[l[3]][0] return s def mul(l): s = "0011000" s = s + reg[l[1]][0] s = s + reg[l[2]][0] s = s + reg[l[3]][0] return s def div(l): s = "0011100000" s = s + reg[l[1]][0] s = s + reg[l[2]][0] return s def left_shift(l): s = "01001" s = s + reg[l[1]][0] s = s + convert(int(l[2][1:])) return s def right_shift(l): s = "01000" s = s + reg[l[1]][0] s = s + convert(int(l[2][1:])) return s def xor_fnc(l): s = "0101000" s = s + reg[l[1]][0] s = s + reg[l[2]][0] s = s + reg[l[3]][0] return s def or_fnc(l): s = "0101100" s = s + reg[l[1]][0] s = s + reg[l[2]][0] s = s + reg[l[3]][0] return s def and_fnc(l): s = "0110000" s = s + reg[l[1]][0] s = s + reg[l[2]][0] s = s + reg[l[3]][0] return s def not_fnc(l): s = "0110100" s = s + reg[l[1]][0] s = s + reg[l[2]][0] return s def load(l): s = "00100" s = s + reg[l[1]][0] s = s + v[l[2]][0] return s def store(l): s = "00101" s = s + reg[l[1]][0] s = s + v[l[2]][0] return s def compare(l): s = "0111000000" s = s + reg[l[1]][0] s = s + reg[l[2]][0] return s def jump_uncond(l): s = "01111000" s = s + labels[l[1]] return s def jump_if_less(l): s = "10000000" s = s + labels[l[1]] return s def jump_if_greater(l): s = "10001000" s = s + labels[l[1]] return s def jump_if_equal(l): s = "10010000" s = s + labels[l[1]] return s def halt(l): return "1001100000000000" # the raise error line was used so that we can raise error during binary creation but then we handled the error generation using aa different fucntion def main(line): if (line[0][0] in op.keys()): if (line[0][0] == 'mov'): if (line[0][2] in reg.keys()): ret.append(mov2(line[0])) else: ret.append(mov1(line[0])) elif (line[0][0] == "add"): ret.append(add(line[0])) elif (line[0][0] == "sub"): ret.append(sub(line[0])) elif (line[0][0] == "mul"): ret.append(mul(line[0])) elif (line[0][0] == "div"): ret.append(div(line[0])) elif (line[0][0] == "ld"): ret.append(load(line[0])) elif (line[0][0] == "st"): ret.append(store(line[0])) elif (line[0][0] == "rs"): ret.append(right_shift(line[0])) elif (line[0][0] == "ls"): ret.append(left_shift(line[0])) elif (line[0][0] == "or"): ret.append(or_fnc(line[0])) elif (line[0][0] == "xor"): ret.append(xor_fnc(line[0])) elif (line[0][0] == "and"): ret.append(and_fnc(line[0])) elif (line[0][0] == "not"): ret.append(not_fnc(line[0])) elif (line[0][0] == "cmp"): ret.append(compare(line[0])) elif (line[0][0] == "jmp"): ret.append(jump_uncond(line[0])) elif (line[0][0] == "jlt"): ret.append(jump_if_less(line[0])) elif (line[0][0] == "jgt"): ret.append(jump_if_greater(line[0])) elif (line[0][0] == "je"): ret.append(jump_if_equal(line[0])) elif (line[0][0] == "hlt"): ret.append(halt(line[0])) else: # raise error pass #ret list is for storing the final binary output ret = [] #statements dictionary is storing our input keys are line numbers (starting from 0 and are in base 10) # values are a 2d list storing #[ [<instuction in list format after splitting thee string >],line number of this instruction] statements = {} #op dictionary contains all our instructions as keys and values as their op codes op = {"add": '00000', "sub": '00000', "mov": '0001100000', "ld": '00000', "st": '00000', "mul": '00000', "div": '00000', "rs": '00000', "ls": '00000', "xor": '00000', "or": '00000', "and": '00000', "not": '00000', "cmp": '00000', "jmp": '00000', "jlt": '00000', "jgt": '00000', "je": '00000', "hlt": '00000'} #v dictionary to store keys as variable names and values as memory addresses v = {} #reg dictionary stores the register name as key and value is #a list containing binary representation of register and the value contained in it''' reg = {'R0': ['000', 0], 'R1': ['001', 0], 'R2': ['010', 0], 'R3': ['011', 0], 'R4': ['100', 0], 'R5': ['101', 0], 'R6': ['110', 0], 'FLAGS': ['111', 0]} #var is counting number of lines in our input var = 0 #labels dictionary is for storing labels as keys and values are addresses labels = {} #to check if reserved words are used in variable and label name reserved=["add","sub","mul","div","jmp","jgt","jlt","je","cpm","ld","st","not","xor","or","and","ls","rs","mov","hlt","R0","R1","R2","R3","R4","R5","R6","FLAGS","var",] # to check if anything other than alphanumeric and _ is used in variable and label names vname="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_" # loop to take input from user(will end when the inout is completed while (1): try: line = input() line=line.strip() if (line != ""): if (line.split(" ")[0] != "hlt" and (len(line.split(" ")) == 1)): print("Invalid Instruction at line "+str(var+1)) exit(0) statements[var] = [line.split(" "), var] var += 1 except EOFError: break # storing variable addresses and removing labels after storing the label addresss in labels dictionary for i in statements.keys(): if (statements[i][0][0] == 'var'): if (len(statements[i][0]) == 1): print("Invalid Instruction at line "+str(statements[i][1])) exit(0) if(statements[i][0][1] in reserved): print("Reserved words cannot be used as variable names line no =>"+str(statements[i][1])) exit(0) for k in statements[i][0][1]: if(k not in vname): print("invalid literal in variable names at line "+str(statements[i][1])) exit(0) v[statements[i][0][1]] = 0 elif (statements[i][0][0][-1:] == ':'): if (statements[i][0][0][:-1] in labels): print("Two labels with same name -> Invalid Instruction at line "+str(statements[i][1])) exit(0) if(statements[i][0][0][:-1] in reserved): print("Reserved words cannot be used as label names line number =>"+str(statements[i][1])) exit(0) for k in statements[i][0][0][:-1]: if(k not in vname): print("invalid literal in label names at line "+str(statements[i][1])) exit(0) # binary conversion labels[statements[i][0][0][:-1]] = convert(int(i) - len(v)) del statements[i][0][0] #assinging addresses to variables k = 0 for i in v.keys(): # binary v[i] = [convert(len(statements) - len(v) + k), ""] k += 1 # checking for more than one halt statement spaceerror() # functio to check if multiple spaces are entered checkr() # to check if variables are decleared after an instruction of some opcode is given for i in statements.keys(): if (statements[i][0][0] == "hlt" and statements[i][1] != len(statements) - 1): print("More than one hlt statement at line "+str(statements[i][1])+"\n") exit(0) if(len(statements)<256 and statements[len(statements)-1][0][0]!="hlt"): print("Missing halt statement") exit(0) if (error()): #if any arror then we exit and do not print anything anymore exit() # if no error found binary file creation starts and then printing it else: sk = 0 while (len(v) + sk in statements.keys()): main(statements[len(v) + sk]) sk += 1 # Printing the binary file for i in range(len(ret)): print(ret[i])
ddaaf31b0c7fe36cbf57e17a20f188c276a9f075
jefte23/Python
/Operadores
668
4.0625
4
print ("Test Equality and Relational Operators") number1 = input("Enter first number:") number1 = int(number1) number2 = input("Enter second number:") number2 = int(number2) if number1 == number2 : print("%d is equal to %d" % (number1, number2)) if number1 != number2 : print("%d is not equal to %d" % (number1, number2)) if number1 < number2 : print("%d is less than %d" % (number1, number2)) if number1 > number2 : print("%d is greater than %d" % (number1, number2)) if number1 <= number2 : print("%d is less than or equal %d" % (number1, number2)) if number1 >= number2 : print("%d is greater than or equal %d" % (number1, number2))
17f3d115d3764b69ebb8cdc9ae70c6a255ffc223
EvidenceN/DS-Unit-3-Sprint-1-Software-Engineering
/sprint-challenge - answers/acme_report.py
1,870
3.75
4
import random from random import randint, sample, uniform from acme import Product import math adjectives = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved'] nouns = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???'] def generate_products(num_products=30): ''' generate a given number of products (default 30), randomly, and return them as a list ''' products = [] adjectives_sample = random.sample(adjectives, 1) nouns_sample = random.sample(nouns, 1) name = f'{adjectives_sample} {nouns_sample}' price = random.randint(5, 100) weight = random.randint(5, 100) flammability = random.uniform(0.0, 2.5) prod = Product( name=name, price=price, weight=weight, flammability=flammability ) products_list = [prod.name, prod.price, prod.weight, prod.flammability] products.append(products_list * num_products) return products def inventory_report(products): ''' takes a list of products, and prints a "nice" summary ''' for name in products: count = [] if name not in count: count.append(name) num_unique_products = len(count) return num_unique_products unique_products = num_unique_products average_price = sum(products.price)/len(products.price) average_weight = sum(products.weight)/len(products.weight) average_flammability = sum(products.flammability)/len(products.flammability) print('ACME CORPORATION OFFICIAL INVENTORY REPORT') print(f'Unique product names: {unique_products}') print(f'Average Price: {average_price}') print(f'Average Weight: {average_weight}') print(f'Average Flammability: {average_flammability}') if __name__ == '__main__': inventory_report(generate_products())
5d3bb4e438cf010e62b2fe97cf05ce191a65d29c
samuelmutinda/leetcode-practice
/palindrome.py
827
3.875
4
def isPalindrome(x): """ :type x: int :rtype: bool """ def split(word): return [char for char in word] if x < 0: return False digitarray = split(str(x)) xstring = str(x) if len(digitarray)%2 == 0: b = int((len(digitarray)/2) - 1) right = "" left = xstring[0:b+1] i = len(digitarray) - 1 while i > b: right += digitarray[i] i -= 1 if right == left: return True return False else: mid = int(len(digitarray)/2) right = "" left = xstring[0:mid] j = len(digitarray) - 1 while j > mid: right += digitarray[j] j -= 1 if right == left: return True return False print(isPalindrome(120021))
dee57a6ebf2ca0350a8449f9cb4474ab93811dce
AleksC/bioskop
/src/provere.py
1,557
4.0625
4
def unos_stringa(ciljana_provera): ''' Provera namenjena pravilnom unosu imena i prezimena novih korisnika. ''' provera = False while not provera: string_za_proveru = input("Molimo unesite " + ciljana_provera + " novog korisnika: ") pom_prom = string_za_proveru.split() if len(pom_prom) != 1: print("Unesite samo " + ciljana_provera + ".") provera = False continue else: provera = True if not string_za_proveru.isalpha(): print(ciljana_provera.capitalize() + " ne sme sadrzati brojeve.") provera = False else: provera = True return string_za_proveru def unos_broja(tekst = "Vas izbor: "): ''' Funkcija za proveru unosa broja. Uglavnom koriscena za navigaciju kroz menije. ''' while True: try: unos = int(input(tekst)) return unos except ValueError: print("Molimo unesite odgovarajuci broj.") def provera_poklapanja(unos, tekst_za_unos, lokacija_pretrage): ''' Funkcija za proveru postojanja unetog podatka u vec postojecim podacima. ''' pom_prom = True while pom_prom: pretraga = input(tekst_za_unos) pom_prom = False for i in lokacija_pretrage: if pretraga in i[unos]: print(unos.capitalize().replace("_", " ") + " je nemoguce upotrebiti. Molimo pokusajte sa drugim unosom.") pom_prom = True break return pretraga
a867f7c5bc43e29c40a6ad5b475c43ce447217b8
leo10816/practice-git
/bubblesort.py
427
3.90625
4
def bubblesort(data): print('原始資料為:') listprint(data) for i in range(len(data)-1,-1,-1): for j in range(i): if data[j]>data[j+1]: data[j],data[j+1]=data[j+1],data[j] print('排序結果為:') listprint(data) def listprint(data): for j in range(len(data)): print('%3d'%data[j],end=' ') print() data=[16,25,39,27,12,8,45,63,1] bubblesort(data)
663ac97205d487837d27cd973cb1a91bdf9b8702
Antoniel-silva/ifpi-ads-algoritmos2020
/Fabio 2b/Questão 7.py
1,890
4.25
4
#7. As Organizações Tabajara resolveram dar um aumento de salário aos seus colaboradores e lhe #contrataram para desenvolver o programa que calculará os reajustes. Escreva um algoritmo que leia o #salário de um colaborador e o reajuste segundo o seguinte critério, baseado no salário atual: #o salários até R$ 280,00 (incluindo) : aumento de 20% #o salários entre R$ 280,00 e R$ 700,00 : aumento de 15% #o salários entre R$ 700,00 e R$ 1500,00 : aumento de 10% #o salários de R$ 1500,00 em diante : aumento de 5% Após o aumento ser realizado, informe na tela: #· o salário antes do reajuste; #· o percentual de aumento aplicado; #· o valor do aumento; #· o novo salário, após o aumento. #entradas salario = float(input("Digite o salário do colaborador: ")) if salario <= 280: novo_salario = salario + (salario * .2) print(f'O salario antes do reajuste é {salario}') print('O percentual de aumento foi de 20%') print(f'O aumento foi de {novo_salario - salario}') print(f'O novo salario é: {novo_salario}') elif salario > 280 and salario <= 700: novo_salario = salario + (salario * .15) print(f'O salario antes do reajuste é {salario}') print('O percentual de aumento foi de 15%') print(f'O aumento foi de {novo_salario - salario}') print(f'O novo salario é: {novo_salario}') elif salario > 700 and salario <= 1500: novo_salario = salario + (salario * .10) print(f'O salario antes do reajuste é {salario}') print('O percentual de aumento foi de 10%') print(f'O aumento foi de {novo_salario - salario}') print(f'O novo salario é: {novo_salario}') elif salario > 1500: novo_salario = salario + (salario * .05) print(f'O salario antes do reajuste é {salario}') print('O percentual de aumento foi de 5%') print(f'O aumento foi de {novo_salario - salario}') print(f'O novo salario é: {novo_salario}')
9921976bf20825da1a5ce71bf4ba52d01ee5f106
Antoniel-silva/ifpi-ads-algoritmos2020
/App celular.py
2,066
4.15625
4
def main(): arquivo = [] menu = tela_inicial() opcao = int(input(menu)) while opcao != 0: if opcao == 1: listacel = cadastrar() arquivo.append(listacel) elif opcao == 2: lista = listar(arquivo) print(lista) elif opcao == 3: print("Voce selecionou a busca por celulares cadastrados!") a = str(input("Digite uma palavra chave: ")) for a in arquivo[0]["marca"] == True: print(a) else: print(""" Essa opção não é válida! ________________________ """) input("Precione enter e continue a execução. . . ") opcao = int(input(menu)) def tela_inicial(): menu = "<<<<<<<<<< App Celular >>>>>>>>>>\n" print() menu += '1 - Cadastre um novo modelo de celular\n' menu += '2 - Lista todos os modelos cadastrados\n' menu += '3 - Fazer busca nos celulares cadastrados\n' menu += '0 - para sair\n' menu += 'Digite sua opção: ' return menu def cadastrar(): listacell = {} print() print("Voce selecionou cadastro de novos celulares!") print() marca = str(input("Digite a fabricante do dispositivo: ")) modelo = str(input("Digite o modelo do dispositivo: ")) tela = str(input("Digite o tamaho da tela do dispositivo: ")) valor = float(input("Digite quanto custa o dispositivo: ")) listacell["Marca"] = marca listacell["Modelo"] = modelo listacell["Tela"] = tela listacell["Valor"] = valor #arquivo.append(listacell) print("Dados gravados com sucesso!") return listacell def listar(tamanho): print() print("Foram localizados", len(tamanho), "cadastros!") print() print("<<<<<Mostrando lista de dispositivos cadastrados>>>>>") print() for i in tamanho: print(i) print() main()
ed36575ff8fa252383163fa040ec476df213a1de
Antoniel-silva/ifpi-ads-algoritmos2020
/Questão Alongamento.py
743
3.625
4
num = int(input("Digite a quantidade de números que você pretende digitar: ")) v = [-1] * num v2 = [] par = 0 impar = 0 pos = 0 neg = 0 for i in range(len(v)): for i in range(len(v2): v[i] = int(input("valor: ?")) if v[i] % 2 == 0 and v[i] >=0: #v2[i] = v[i]*2 pos+=1 par +=1 v2[i] = v[i]*ArithmeticError if v[i] % 2 == 0 and v[i] <0: neg+=1 par +=1 if v[i] % 2 != 0 and v[i] >=0: pos+=1 impar +=1 if v[i] % 2 != 0 and v[i] <0: neg+=1 impar +=1 print(v) print(v2) print(par, "números pares") print(impar," números impares") print(pos, "números positivos") print(neg, "numeros negativos")
2a49008676cac7c25bc0914644706f5056798ef5
Antoniel-silva/ifpi-ads-algoritmos2020
/Fabio 2a/Questão 4.py
357
3.8125
4
#4. Leia 1 (um) número de 2 (dois) dígitos, verifique e escreva se o algarismo da dezena é igual ou diferente #do algarismo da unidade. #entradas a = int(input("Digite um número inteiro de 2 algarismos: ")) num1 = a // 10 num2 = a % 10 if num1 == num2: print("Os algarismos são iguais.") else: print("Os algarismos são diferentes!")
4bb55dfeb2640ca2ba99d32ff68d1c1440126898
Antoniel-silva/ifpi-ads-algoritmos2020
/Fabio 2b/Questão 13.py
1,567
4.21875
4
#13. Faça 5 perguntas para uma pessoa sobre um crime. As perguntas são: #a) "Telefonou para a vítima ?" #b) "Esteve no local do crime ?" #c) "Mora perto da vítima ?" #d) "Devia para a vítima ?" #e) "Já trabalhou com a vítima ?" #O algoritmo deve no final emitir uma classificação sobre a participação da pessoa no crime. Se a pessoa #responder positivamente a 2 questões ela deve ser classificada como "Suspeita", entre 3 e 4 como #"Cúmplice" e 5 como "Assassino". Caso contrário, ele será classificado como "Inocente". #entradas contador = 0 pergunta1 = str(input("Telefonou para a vítima ? ")) pergunta2 = str(input("Esteve no local do crime ? ")) pergunta3 = str(input("Mora perto da vítima ? ")) pergunta4 = str(input("Devia para a vítima ? ")) pergunta5 = str(input("Já trabalhou com a vítima ? ")) if pergunta1 == "s" and pergunta2 == "s" and pergunta3 == "s" and pergunta4 == "s" and pergunta5 == "s": print("Assassino") elif pergunta1 == "s" and pergunta2 == "s": print("Suspeita") elif pergunta2 == "s" and pergunta3 == "s": print("Suspeita") elif pergunta1 == "s" and pergunta3 == "s": print("Suspeita") elif pergunta3 == "s" and pergunta4 == "s": print("Suspeita") elif pergunta4 == "s" and pergunta5 == "s": print("Suspeita") elif pergunta3 == "s" and pergunta5 == "s": print("Suspeita") elif pergunta1 == "s" and pergunta5 == "s": print("Suspeita") elif pergunta1 == "s" and pergunta4 == "s": print("Suspeita")
351bc82a4422af759022c5f84c26a7f35d266f59
Antoniel-silva/ifpi-ads-algoritmos2020
/semana 4 Exploração de marte.py
205
4.09375
4
#Exploração de marte palavra = str(input("Digite a palavra: ")) con = 0 qtdpalvras = con / 3 for i in palavra: con +=1 print("A quantidade de palavras recebidas foi: ", con/3, "palavras")
46c32dc5a42d22168f750d26e8608afeb34390c7
Antoniel-silva/ifpi-ads-algoritmos2020
/Fabio 2a/Questão 3.py
396
3.875
4
#3. Leia 3 (três) números, verifique e escreva o maior entre os números lidos. a = float(input("Digite o primeiro valor: ")) b = float(input("Digite o segundo valor: ")) c = float(input("Digite o terceiro valor: ")) if a > b and a > c: print(f'O numero {a} é maior') if a < b and b > c: print(f'O numero {b} é maior') if a < c and b < c: print(f'O número {c} é maior')
5e9b4e2f255ea65059abfeb8a68658de961e9902
sudh29/Algorithms
/selectionSort.py
298
3.96875
4
# function to sort a list using selction sort def selectionSort(a): n = len(a) for i in range(n): for j in range(i + 1, n): if a[j] < a[i]: a[j], a[i] = a[i], a[j] # print(a) return a x = [5, 2, 6, 7, 2, 1, 0, 3] print(selectionSort(x))
63f54656115085c99710905f8ff2f020a382c1ef
odhran456/pythonComputationalPhysics
/blocks.py
4,571
3.609375
4
import pygame WIDTH = 640 HEIGHT = 480 FPS = 30 BLACK = (0, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) WHITE = (255, 255, 255) counter = 0 class Square(pygame.sprite.Sprite): def __init__(self, x, y, size, mass, velocity, color): self.mass = mass self.velocity = velocity pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface((size, size)) self.image.fill(color) self.rect = self.image.get_rect() self.rect.bottomleft = (x, y) def update(self): self.rect.x += self.velocity # initialisers pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Block Collision Demo") clock = pygame.time.Clock() font_name = pygame.font.match_font('arial') # group all the sprites together to make updating the game easier all_sprites = pygame.sprite.Group() square1 = Square(300, HEIGHT, 50, 1, 0, GREEN) square2 = Square(400, HEIGHT, 100, 100, -1, BLUE) wall = Square(-2000, HEIGHT, 2000, 0, 0, BLACK) all_sprites.add(square1) all_sprites.add(square2) def is_wall(square): return square.mass == 0 def do_collision(body1, body2): x_initial_velocity = body1.velocity y_initial_velocity = body2.velocity body1.velocity = ((float(body1.mass - body2.mass) / float(body1.mass + body2.mass)) * x_initial_velocity) + ( (float(2 * body2.mass) / float(body1.mass + body2.mass)) * y_initial_velocity) body2.velocity = ((float(2 * body1.mass) / float(body1.mass + body2.mass)) * x_initial_velocity) + ( (float(body2.mass - body1.mass) / float(body1.mass + body2.mass)) * y_initial_velocity) # TO FINISH def check_collisions(*args): bodies = args global counter for x in range(len(bodies)): # SQUARES COLLISION for y in range(x + 1, len(bodies)): # LEFT if bodies[x].rect.bottomleft[0] + bodies[x].velocity <= bodies[y].rect.bottomright[0] and \ bodies[y].rect.bottomleft[0] <= bodies[x].rect.bottomleft[0] + bodies[x].velocity: while bodies[x].rect.bottomleft >= bodies[y].rect.bottomright: bodies[x].rect.bottomleft = (bodies[x].rect.bottomleft[0] - 1, HEIGHT) if is_wall(bodies[y]): bodies[x].velocity *= -1 counter = counter + 1 print(counter) print(bodies[x].velocity) break else: do_collision(bodies[x], bodies[y]) counter = counter + 1 print(bodies[y].velocity) print(bodies[x].velocity) break # RIGHT if bodies[x].rect.bottomright[0] + bodies[x].velocity >= bodies[y].rect.bottomleft[0] and \ bodies[y].rect.bottomright[0] >= bodies[x].rect.bottomright[0] + bodies[x].velocity: while bodies[x].rect.bottomright <= bodies[y].rect.bottomleft: bodies[x].rect.bottomleft = (bodies[x].rect.bottomleft[0] + 1, HEIGHT) if is_wall(bodies[y]): bodies[x].velocity *= -1 counter = counter + 1 break else: do_collision(bodies[x], bodies[y]) counter = counter + 1 print(counter) print(bodies[y].velocity) print(bodies[x].velocity) break def draw_text(surf, text, size, x, y): font = pygame.font.Font(font_name, size) text_surface = font.render(text, True, WHITE) #creates surface for python to render pixels onto to write text, true is for pixellation (aliasing) text_rect = text_surface.get_rect() #figures out the rectangle size and shape fo the surface text_rect.midtop = (x, y) surf.blit(text_surface, text_rect) #takes the text surface and blits it onto the screen # Game Loop running = True while running: # keep loop running at right time clock.tick(FPS) # Process inputs for event in pygame.event.get(): # check for closing the window if event.type == pygame.QUIT: running = False check_collisions(square1, square2, wall) # Update all_sprites.update() # Draw events screen.fill(BLACK) all_sprites.draw(screen) draw_text(screen, "Collisions: " + str(counter), 36, 500, 30) # Flip comes after drawing everything pygame.display.flip() pygame.quit()
4ff81247fecf557f505793e1d0e62bf1e420c4f8
mariakalfountzou/First-Coding-Bootcamb
/Python_Part_I/Exercise 3.py
457
3.953125
4
import math input_a=input("Give me the first side of the triangle:") input_b=input("Give me the second side of the triangle:") input_c=input("Give me the third side of the triangle:") r= (float(input_a)+ float (input_b)+ float (input_c))*(-float (input_a)+ float (input_b)+ float (input_c))*(float (input_a)- float (input_b)+ float (input_c))*( float (input_a)+ float (input_b)- float (input_c)) A= (1/4)* math.sqrt(r) print("The triangle's area is:", A)
47aaec0bae9d6547b03ba391cc316f101217ba93
mariakalfountzou/First-Coding-Bootcamb
/Python_Part_I/Exercise 4.py
567
3.984375
4
import math a = input("Enter the value for a, not 0!:") b = input("Enter the value for b:") c = input("Enter the value for c:") d= (float(b)**2-4*float (a)* float (c)) if (float (d) >=0): x1= (-float(b)+math.sqrt(d)) / (2*float (a)) x2= (-float(b)- math.sqrt(d)) / (2*float (a)) if (x1==x2): print("The equation has a double solution: ", x1) else: print("The first solution is:", x1) print("The second solution is:", x2) else: print("This equation has no real-valued solutions.")
5812c74bf9c585094496173797da68ef29aaad19
GuiMarion/Musical-Needleman
/functions.py
16,837
3.75
4
from __future__ import print_function # In order to use the print() function in python 2.X import numpy as np import math DEBUG = False def printMatrix(M, str1, str2): P = [] for i in range(len(M)+1): P.append([]) for j in range(len(M[0])+1): P[i].append('') for i in range(2, len(P[0])): P[0][i] = str2[i-2] for i in range(2, len(P)): P[i][0] = str1[i-2] for i in range(1, len(P)): for j in range(1, len(P[i])): P[i][j] = M[i-1][j-1] for i in range(len(P)): print() for j in range(len(P[0])): if i == 0 and j ==0: print(" ", end="") if i == 1 and j ==0: print(" ", end="") if len(str(P[i][j])) > 0 and str(P[i][j])[0] != '-': print(" ", end="") if len(str(P[i][j])) == 1: print(" ", end="") print(P[i][j], end=" ") print() print() def match(): return 1 def mismatch(a, b): return -1 def indel(): return -1 def compare(a,b): if a == b: return match() else: return mismatch(a, b) def getDistanceDictionaryFromFile(file): ''' Open a dist file and construct the proper dictionary ''' f=open(file, "r") contents = f.read() # delete the comments if there is if contents.rfind('#') != -1: contents = contents[contents.rfind('#'):] M = contents.split("\n") # Find how many spaces there is at the begining d = 0 for i in range(len(M[0])): if M[i] != ' ': d = i+1 break if M[0][0] == "#": del M[0] alpha = M[0][d:].split(" ")[1:] dist = {} for i in range(1, len(M)-1): dist[M[i][0]] = M[i][3:].replace(" ", " ") for key in dist: temp = dist[key].split(" ") dist[key] = {} for i in range(len(alpha)): # In order to have integers in the dict dist[key][alpha[i]] = int(temp[i]) return dist def getDist(a, b, matrix = "Linear", bonus=5, malus=-3, dist = ''): if matrix == "Linear": return (a==b)*bonus + (not a==b)*malus else: return dist[a][b] def myNeedleman(str1, str2, matrix='atiam-fpa_alpha.dist', gap_open=-5, gap_extend=-5, bonus=5, malus=-3): dist = {} if matrix != "Linear": # We get the distance dictionary from the file try: dist = getDistanceDictionaryFromFile(matrix) except FileNotFoundError : try: # If the one provided is not found we use the default one dist = getDistanceDictionaryFromFile('atiam-fpa_alpha.dist') except FileNotFoundError : raise FileNotFoundError("No dist file was found.") print("The dist file you provided (", matrix,") was not found, we will use the default one.") # Initialize matrix M = np.ones((len(str1)+1, len(str2)+1)) M[0][0] = 0 M[0][1] = gap_open M[1][0] = gap_open for i in range(2, len(M[0])): M[0][i] = M[0][i-1] + gap_extend for i in range(2, len(M)): M[i][0] = M[i-1][0] + gap_extend for i in range(1, len(M)): for j in range(1, len(M[i])): # in order to see if we already opened a gap if i > 1: top_opened = (M[i-1][j] == M[i-2][j] + gap_extend) or (M[i-1][j] == M[i-2][j] + (gap_open)) or \ (M[i-1][j] == M[i-1][j-1] + gap_extend) or (M[i-1][j] == M[i-1][j-1] + (gap_open)) else: top_opened = (M[i-1][j] == M[i-1][j-1] + gap_extend) or (M[i-1][j] == M[i-1][j-1] + (gap_open)) if j > 1: left_opened = (M[i][j-1] == M[i][j-2] + gap_extend) or (M[i][j-1] == M[i][j-2] + (gap_open)) or \ (M[i][j-1] == M[i-1][j-1] + gap_extend) or (M[i][j-1] == M[i-1][j-1] + (gap_open)) else: left_opened = (M[i][j-1] == M[i-1][j-1] + gap_extend) or (M[i][j-1] == M[i-1][j-1] + (gap_open)) # Filling matrix with the recursive formula M[i][j] = max(M[i-1][j] + top_opened*gap_extend + (not top_opened)*gap_open, \ M[i][j-1] + left_opened*gap_extend + (not left_opened)*gap_open, \ M[i-1][j-1] + getDist(str1[i-1], str2[j-1], matrix =matrix, dist = dist)) if DEBUG: print("Position:", i,j,'__',str2[j-1], "vs", str1[i-1], ": max", M[i-1][j] + top_opened*gap_extend + (not top_opened)*gap_open, \ M[i][j-1] + left_opened*gap_extend + (not left_opened)*gap_open, (M[i-1][j-1]) + dist[str1[i-1]][str2[j-1]],\ "=", max(M[i-1][j] + top_opened*gap_extend + (not top_opened)*gap_open, M[i][j-1] + left_opened*gap_extend + (not left_opened)*gap_open, M[i-1][j-1]) + getDist(str1[i-1], str2[j-1], matrix =matrix, dist = dist)) if DEBUG: printMatrix(M, str1, str2) # We construct the alignement from the matrix i,j = (len(M)-1, len(M[0])-1) retA = "" retB = "" posA = len(str1) -1 posB = len(str2) -1 while (i,j) != (0, 0): if M[i][j] == M[i][j-1] + gap_extend or M[i][j] == M[i][j-1] + gap_open : retB = str2[posB] + retB posB -= 1 retA = '-' + retA j -= 1 elif M[i][j] == M[i-1][j] + gap_extend or M[i][j] == M[i-1][j] + gap_open: retA = str1[posA] + retA posA -= 1 retB = '-' + retB i -= 1 elif M[i][j] == M[i-1][j-1] + getDist(str1[i-1], str2[j-1], matrix =matrix, dist = dist): retA = str1[posA] + retA posA -= 1 retB = str2[posB] + retB posB -= 1 i -= 1 j -= 1 else: return (str1, str2, 0) if DEBUG: print(retA) print(retB) print("SCORE:", int(M[-1][-1])) return (retA, retB, int(M[-1][-1])) # in order to improve computation def checkFirstSimilarities(a, b): dic1 = {} for elem in a+b: dic1[elem] = 0 for elem in a: dic1[elem] += 1 dic2 = {} for elem in a+b: dic2[elem] = 0 for elem in b: dic2[elem] += 1 similarity = 0 for elem in dic1: similarity += (dic1[elem] - dic2[elem])**2 similarity = float(similarity) / min(len(a), len(b)) return similarity def musicNameDist(a, b): # We define all atom that are the same Table = [["n", "number", "numero", "num", "no.","no"], \ ["1", "un", "one", "premier"], \ ["2", "deux", "two", "second"], \ ["3", "trois", "three", "toisieme"], \ ["4", "quatre", "four", "quatrieme"], \ ["5", "cinq", "five", "cinquieme"], \ ["6", "six", "six", "sixieme"], \ ["7", "sept", "seven", "septieme"], \ ["8", "huit", "eight", "huitieme"], \ ["9", "neuf", "nine", "neuvieme"], \ ["10", "dix", "ten", "dixieme"], \ ["11", "onze", "eleven", "onzieme"], \ ["12", "douze", "twelve", "douzieme"], \ ["13", "treize", "thirteen", "treizieme"], \ ["14", "quatorze", "fourteen", "quatorzieme"], \ ["15", "quize", "fiveteen", "quinzieme"], \ ["16", "seize", "sixteen", "seizieme"], \ ["17", "dix-sept", "seventeen", "dix-spetieme"], \ ["18", "dix-hui", "eighteen", "dix-huitieme"], \ ["19", "dix-neuf", "nineteen", "dix-neuvieme"], \ ["20", "vingt", "twenty", "vingtieme"], \ ["mineur", "minor", "mino"], \ ["majeur", "major", "majo"], \ ["c", "do", "ut"],\ ["c#", "do diese", "do#"], \ ["d", "re"], \ ["d#", "re diese", "re#"], \ ["e", "mi"], \ ["f", "fa"], \ ["f#", "fa dise", "fa#"], \ ["g", "sol"], \ ["g#", "sol diese", "sol#"], \ ["a", "la"], \ ["a#", "la diese", "la#"], \ ["b", "si"], \ ["bb", "si bemol", "sib"], \ ["eb", "mi bemol", "mib"], \ ["ab", "la bemol", "lab"], \ ["db", "re bemol", "reb"], \ ["gb", "sol bemol", "solb"], \ ["cb", "do bemol", "dob"], \ ["fb", "fa bemol", "fab"]] # For digit we have to be clear equal or not equal if a.isdigit(): if b.isdigit() and int(a) == int(b): return 1 else: return 0 if b.isdigit(): if a.isdigit() and int(a) == int(b): return 1 else: return 0 # if we see a match in the table return 1 for elem in Table: if a in elem: if b in elem: return 1 # else we rely on Needleman for the taping mistakes if len(a)>0 and len(b)>0 and abs(len(a)-len(b))<3 and checkFirstSimilarities(a, b) < 0.5 and \ myNeedleman(a, b, matrix= "Linear", gap_extend=-2, gap_open=-2)[2] > 0.9*min(len(a), len(b))*5 - 0.4*min(len(a), len(b)): return 1 return 0 def musicNameMatching(name1, name2): # we process the replacement for the flat and sharp and put the names in lower case # Sharp name1 = name1.replace("#", " diese").lower() name2 = name2.replace("#", " diese").lower() # Flat flat = [ ["bb", "si bemol", "sib"], \ ["eb", "mi bemol", "mib"], \ ["ab", "la bemol", "lab"], \ ["db", "re bemol", "reb"], \ ["gb", "sol bemol", "solb"], \ ["cb", "do bemol", "dob"], \ ["fb", "fa bemol", "fab"]] for elem in flat: name1 = name1.replace(elem[0], elem[1]).replace(elem[2], elem[1]) name2 = name2.replace(elem[0], elem[1]).replace(elem[2], elem[1]) # we split the names and replace some sybols name1 = name1.replace("(","").replace(")","").replace("_", " ").replace(".", " ").split(" ") name2 = name2.replace("(","").replace(")","").replace("_", " ").replace(".", " ").split(" ") temp = [] for elem in name1: if elem != "": temp.append(elem) name1 = temp temp = [] for elem in name2: if elem != "": temp.append(elem) name2 = temp # Case catalog Bach-Werke-Verzeichnis for i in range(len(name1)-1): if name1[i] == "bwv": name1 = ["bwv "+ name1[i+1]] break for i in range(len(name2)-1): if name2[i] == "bwv": name2 = ["bwv "+ name2[i+1]] break # Case catalog Kochel for i in range(len(name1)-1): if name1[i] == "kv": name1 = ["kv "+ name1[i+1]] break for i in range(len(name2)-1): if name2[i] == "kv": name2 = ["kv "+ name2[i+1]] break score = 0 # We assume that there is no missing word for word in name1: for word2 in name2: if musicNameDist(word, word2) == 1: score += 1 break if score >= min(len(name1), len(name2)): return True return False def getListRepresentation(dic): L = [] for key in dic: L.append(dic[key]) return L def compareList(a, b): if len(a) != len(b): return False for i in range(len(a)): if str(list(a[i])) != str(list(b[i])): return False break return True def compareMidiFiles(a, b): a = getListRepresentation(a) b = getListRepresentation(b) tobreak = False k = 0 # 2 loops in order to detect if the voices are not in the same order in the dictionary for elem1 in a: for elem2 in b: if compareList(elem1, elem2): k +=1 break if k >= len(a): return True return False def get_start_time(el,measure_offset,quantization): if (el.offset is not None) and (el.measureNumber in measure_offset): return int(math.ceil(((measure_offset[el.measureNumber] or 0) + el.offset)*quantization)) # Else, no time defined for this element and the functino return None def get_end_time(el,measure_offset,quantization): if (el.offset is not None) and (el.measureNumber in measure_offset): return int(math.ceil(((measure_offset[el.measureNumber] or 0) + el.offset + el.duration.quarterLength)*quantization)) # Else, no time defined for this element and the functino return None def get_pianoroll_part(part,quantization): # Get the measure offsets measure_offset = {None:0} for el in part.recurse(classFilter=('Measure')): measure_offset[el.measureNumber] = el.offset # Get the duration of the part duration_max = 0 for el in part.recurse(classFilter=('Note','Rest')): t_end = get_end_time(el,measure_offset,quantization) if(t_end>duration_max): duration_max=t_end # Get the pitch and offset+duration piano_roll_part = np.zeros((128,int(math.ceil(duration_max)))) for this_note in part.recurse(classFilter=('Note')): note_start = get_start_time(this_note,measure_offset,quantization) note_end = get_end_time(this_note,measure_offset,quantization) piano_roll_part[this_note.midi,note_start:note_end] = 1 return piano_roll_part def quantify(piece, quantization): all_parts = {} k = 0 for part in piece.parts: try: track_name = part[0].bestName() except AttributeError: track_name = str(k) cur_part = get_pianoroll_part(part, quantization); if (cur_part.shape[1] > 0): all_parts[track_name] = cur_part; k +=1 return all_parts def getMinDuration(p): minDuration = 10.0 for n in p.flat.notes: if n.duration.quarterLength < minDuration and n.duration.quarterLength > 0: minDuration = n.duration.quarterLength return minDuration ''' The alforithm compute the meaned quadratic loss between a non quantized and a quantized representation of the piece More the error is worth is the file ''' def getQuality(p): # we quantisize with two different levels (a super-large one and a smaller depends on the smallest duration) q1 = 1/getMinDuration(p) q2 = 512 quantified = quantify(p, q1) unquantified = quantify(p, q2) L_q = [] L_u = [] # we store position of all notes in a list for key in quantified: for elem in quantified[key]: rest = True for t in range(len(elem)): if elem[t] != 0: if rest: L_q.append(t/q1) rest = False else: rest = True for key in unquantified: for elem in unquantified[key]: rest = True for t in range(len(elem)): if elem[t] != 0: if rest: L_u.append(t/q2) rest = False else: rest = True # In order to be sure that we have all notes in the right order L_q.sort() L_u.sort() ERROR = 0 # We add 1 in order to not sqare number less than 1 for i in range(len(L_q)): ERROR += (L_q[i]- L_u[i] + 1)**2 ERROR = ERROR / len(L_u) -1 return ERROR def printAlign(s1, s2, size = 70): for i in range(len(s1)//size): for e in range(size): print(s1[i*size+e], end="") print() for e in range(size): print(s2[i*size+e], end="") print("\n") def alignMidi(p1, p2): p1 = quantify(p1, 16) p2 = quantify(p2, 16) keylist1 = p1.keys() keylist2 = p2.keys() P1 = [] P2 = [] for part in range(min(len(keylist1), len(keylist2))): P1.append([]) P2.append([]) for i in range(len(p1[keylist1[part]])): if "".join(p1[keylist1[part]][i].astype(int).astype(str)) == "".join(p2[keylist2[part]][i].astype(int).astype(str)): P1[part].append("".join(p1[keylist1[part]][i].astype(int).astype(str))) P2[part].append("".join(p1[keylist1[part]][i].astype(int).astype(str))) else: N = myNeedleman("".join(p1[keylist1[part]][i].astype(int).astype(str)), "".join(p2[keylist2[part]][i].astype(int).astype(str)), matrix="Linear", gap_open=-4, gap_extend=-2) P1[part].append(N[0]) P2[part].append(N[1]) for i in range(len(P1)): print("New Part: \n") for j in range(len(P1[i])): print("New Slice: \n") printAlign(P1[i][j], P2[i][j])
60aa3a51ff78c2b24027c2534e4e09f3b4f27bcd
anay-jain/PythonNotebook
/keywordArguments.py
515
3.921875
4
# passing a dictonary as a argument def cheeseshop(kind , *arguments ,**keywords): print("I would like to have " , kind , "?") print("Sorry ! OUT OF STOCK OF" , kind ) for arg in arguments : # *name must occur before **name print(arg) print('-'*50) for kw in keywords: # its a dictonary that is passed as a argument print(kw , ":" , keywords[kw]) cheeseshop('pasta' , "its funny " , "its very funny " , "It really very funy" , shopkeeper="Depak", client="anay" , amount="0$")
8399f69c52f360f57163477fdec3a96e40b9242d
Tsidia/FizzBuzz
/FizzBuzz.py
992
3.984375
4
import argparse parser = argparse.ArgumentParser(description="A program that plays FizzBuzz") parser.add_argument("-target", metavar="-t", type=int, default=100, help="The number to play up to") parser.add_argument("-fizz", metavar="-f", type=int, default=3, help="The number to print Fizz on") parser.add_argument("-buzz", metavar="-b", type=int, default=5, help="The number to print Buzz on") def FizzBuzz(target_number=100, fizz=3, buzz=5): for i in range(target_number): output = "" #This is what the function will return if i % fizz == 0: #If a multiple of Fizz, add "Fizz" to output output += "Fizz" if i % buzz == 0: #If a multiple of Buzz, add "Buzz" to output output += "Buzz" if output == "": #If neither Fizz nor Buzz is in the output, print number instead output += str(i) print(output) # if target_number and fizz and buzz: args = parser.parse_args() FizzBuzz(args.target, args.fizz, args.buzz)
d64bfea5f97a202ed2ae72e5aa7e3c9e0922a7b5
mourafc73/EclipsePython
/PyEclipseProj/Test/EPAM_SampleTest.py
934
3.765625
4
# Write a function: # def solution(A) # that, given an array A of N integers, returns the smallest positive integer # (greater than 0) # that does not occur in A. # For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. # Given A = [1, 2, 3], the function should return 4. # Given A = [−1, −3], the function should return 1. # Write an efficient algorithm for the following assumptions: # N is an integer within the range [1..100,000]; # each element of array A is an integer within the range # [−1,000,000..1,000,000]. # Copyright 2009–2020 by Codility Limited. All Rights Reserved. # Unauthorized copying, publication or disclosure prohibited. # you can write to stdout for debugging purposes, e.g. # print("this is a debug message") import EPAM_SampleFunc as instEPAM make = "BMW" model = "M3" color = "red" my_car = instEPAM.Car(make, model, color) print (my_car.model)
8efa2c375ab800d39f8fb78569e22e4b869a2e72
xstaticxgpx/netsnmp-py3
/netsnmp/_hex.py
2,065
3.609375
4
import binascii, struct def snmp_hex2str(type, value): """ Helper func to convert various types of hex-strings, determined by length """ # Remove any surrounding quotes if value[0]=='"' and value[-1]=='"': # '"AB'" -> 'AB' _hexstr = value[1:-1] else: _hexstr = value _hexstrl = len(_hexstr) if _hexstrl==18: # Return cleanly formatted MAC address, no conversion nescessary type = "MacAddress" value = '%s:%s:%s:%s:%s:%s' % tuple(_hexstr.split()) elif _hexstrl==12 or _hexstrl==4: ## Convert octal IpAddress # example input: 'C0 A8 01 01 ' or 'DV8W' # C0 = 192 # A8 = 168 # 01 = 1 # 01 = 1 type = "IpAddress" if _hexstrl==4: # Convert ascii-alike strings value = '%d.%d.%d.%d' % tuple((ord(char) for char in _hexstr)) else: # Convert hex strings value = '%d.%d.%d.%d' % tuple((ord(binascii.unhexlify(part)) for part in _hexstr.split())) elif _hexstrl==33: ## Convert DateAndTime # example input: '07 DF 0C 0E 16 15 09 00 2D 05 00 ' # 07 DF = year # 0C = month # 0E = day # 16 = hour # 15 = minutes # 09 = seconds # 00 = deci-seconds # 2D = direction from UTC ('+'/'-'), e.g. chr(45)==str('-') # 05 = hours from UTC # 00 = minutes from UTC type = "DateAndTime" # given above example, unhexlify "07DF" (b'\x07\xdf') then unpack as big-endian unsigned short (2015) year = struct.unpack('>H', binascii.unhexlify("".join(_hexstr.split()[:2])))[0] (month, day, hour, minute, second, decisecond, utcdir, utchour, utcminute) = (ord(binascii.unhexlify(part)) for part in _hexstr.split()[2:]) # zero padded hour, minute, second value = '%d-%d-%d,%0#2d:%0#2d:%0#2d.%d,%s%s:%s' % ( year, month, day, hour, minute, second, decisecond, chr(utcdir), utchour, utcminute) return (type, value)
10ff6f69a2918ba5ca3ca0d6220f2441f894b500
Ege3/HELLO
/YL10.py
409
3.984375
4
puuvilja_list = ['pirn', 'kirss', 'ploom'] print(puuvilja_list[0]) puuvilja_list.insert(3,'apelsin') print(puuvilja_list[3]) #print(puuvilja_list) puuvilja_list[2] = 'õun' print(puuvilja_list) if "õun" in puuvilja_list: print("Jah, 'õun' on listis") print(len(puuvilja_list)) del puuvilja_list[0] print(puuvilja_list) puuvilja_list.reverse() print(puuvilja_list) puuvilja_list.sort() print(puuvilja_list)
7d85621e7b0f989d3c1bca7b45e8a43ced8fed3b
Ege3/HELLO
/YL9.py
783
4.03125
4
esimene = float(input("Sisesta kolmnurga esimene külg: ")) teine = float(input("Sisesta kolmnurga teine külg: ")) kolmas = float(input("Sisesta kolmnurga kolmas külg: ")) #kaks lühemat külge peavad kokku andma kõige pikema külje: list = [esimene, teine, kolmas] if (max(list)) == esimene and teine + kolmas >= (max(list)) or (max(list)) == teine and esimene + kolmas >= (max(list)) or (max(list)) == kolmas and teine + esimene >= (max(list)): if esimene == teine and esimene == kolmas: print("Tegemist on võrdkülgse kolmnurgaga") elif esimene == teine or esimene == kolmas or teine == kolmas: print("Tegemist on võrdhaarse kolmnurgaga") else: print("Tegemist on erikülgse kolmnurgaga") else: print("Kolmnurka ei saa eksisteerida")
18cbdad0a3cfb067b08e9e4710a4bcc67cab413b
sachin-611/practicals_sem3
/fds/prac_4/file4.py
6,493
4
4
def input_matrix(): # function to take matrix as input row1=int(input("\nEnter no of rows in Matrix : ")) col1=int(input("Enter no of column in Matrix : ")) matrix=[[0]*col1]*row1 for i in range(row1): ls=list(map(int,input().split())) while(len(ls)!=col1): print("Enter",i+1,"th row again: ") ls=list(map(int,input().split())) matrix[i]=ls return matrix def upper_triangular(matrix): #function to check whether the matrix is upper triangular or not for i in range(1,len(matrix)): for j in range(0,i): if matrix[i][j]!=0: return False return True def addition_of_matrix(matrix_a,matrix_b): #function to calculate the summation of two matrix matrix=[] for i in range(len(matrix_a)): tam=[] for j in range(len(matrix_a[0])): tam.append(matrix_a[i][j]+matrix_b[i][j]) matrix.append(tam) return matrix def product_of_matrix(matrix_a,matrix_b): #function to calculate the product of two matrix (if possible) result=[] for i in range(len(matrix_a)): te=[] for j in range(len(matrix_b[0])): res=0 for k in range(len(matrix_b)): res += matrix_a[i][k] * matrix_b[k][j] te.append(res) result.append(te) return result def transpose_of_matrix(matrix): #function to calculate the transpose of the matrix temp=[] for i in range (len(matrix[0])): t=[] for j in range (len(matrix)): t.append(matrix[j][i]) temp.append(t) return temp def mini(array): #function to find the minimum of the array minimum=array[0] indx=0 for i in range(len(array)): if(minimum>array[i]): indx=i minimum=array[i] return minimum,indx def saddle_point(matrix): #function to calculate saddle point if any exist for i in range(len(matrix)): minu,idx=mini(matrix[i]) for j in range(len(matrix)): if(matrix[j][idx]>minu): ans=False break else: ans=True if(ans): return i,idx return -1,-1 def diagonal_sum(matrix): #function to calculate the diagonal sum (both principle and other diagonal sum) principal=0 other=0 for i in range(len(matrix)): principal+=matrix[i][i] other+=matrix[i][len(matrix)-1-i] return principal,other def check_magic_square(matrix,val): #function to check whether matrix is magic square or not for i in range(len(matrix)): row_sum=0 col_sum=0 for j in range(len(matrix)): row_sum+=matrix[i][j] col_sum+=matrix[j][i] if(matrix[i][j]<1 or matrix[i][j]>(len(matrix)*len(matrix))): return False if(row_sum!=val or col_sum!=val): return False return True if __name__ == '__main__': #input 2 matrix matrix_1=input_matrix() matrix_2=input_matrix() #diagonal sum of Matrix 1 if(len(matrix_1)!=len(matrix_1[0])): print("\nSum of Diagonals cannot be calculated as it is not square matrix") else: princi_dia_1,other_dia_1=diagonal_sum(matrix_1) print("\nSum of Principle Diagonal of Matrix 1 is",princi_dia_1," and sum of Other Diagonal of Matrix 1 is",other_dia_1) #diagonal sum of Matrix 2 if(len(matrix_2)!=len(matrix_2[0])): print("\nSum of Diagonals cannot be calculated as it is not square matrix") else: princi_dia_2,other_dia_2=diagonal_sum(matrix_2) print("\nSum of Principle Diagonal of Matrix 1 is",princi_dia_2," and sum of Other Diagonal of Matrix 2 is",other_dia_2) # addition of two matrix if(len(matrix_1)!=len(matrix_2) or len(matrix_1[0])!=len(matrix_2[0])): print("\nThe given two matrix cannot be added as they dont have same no of rows or same no of column") else: sum_of_mat1_and_mat2=addition_of_matrix(matrix_1,matrix_2) print("\nMatrix formed by addition of Matrix 1 and Matrix 2 is:") for i in sum_of_mat1_and_mat2: print(i) #product of matrix 1 and matrix 2 if(len(matrix_1[0])==len(matrix_2)): mat=product_of_matrix(matrix_1,matrix_2) print("\nMatrix produced by product of Given Matrix is : ") for i in mat: print(i) else: print("\nGiven Matrix cannot be multipied") #transpose of Matrix 1 trans_mat_1=transpose_of_matrix(matrix_1) print("\nTranspose of amtrix 1 is : ") for i in trans_mat_1: print(i) #transpose of Matrix 2 trans_mat_2=transpose_of_matrix(matrix_2) print("\nTranspose of matrix 2 is : ") for i in trans_mat_2: print(i) # matrix 1 is upper triangular of not if(len(matrix_1)==len(matrix_1[0]) and upper_triangular(matrix_1)): print("\nMatrix 1 is upper traingular matrix") else: print("\nMatrix 1 is not upper triangular matrix") # matrix 2 is upper triangular or not if(len(matrix_2)==len(matrix_2[0]) and upper_triangular(matrix_2)): print("\nMatrix 2 is upper traingular matrix") else: print("\nMatrix 2 is not upper triangular matrix") #check matrix 1 is magic square or not if(len(matrix_1)==len(matrix_1[0]) and princi_dia_1==other_dia_1 and check_magic_square(matrix_1,princi_dia_1)): print("\nWOW!! Matrix 1 is Magic square!!") else: print("\nMatrix 1 is not Magic square!!") #check matrix 2 is magic square or not if(len(matrix_2)==len(matrix_2[0]) and princi_dia_2==other_dia_2 and check_magic_square(matrix_2,princi_dia_2)): print("\nWOW!! Matrix 2 is Magic square!!") else: print("\nMatrix 2 is not Magic square!!") #find saddle point if exist in matrix 1 i_co,j_co=saddle_point(matrix_1) if(i_co>=0 and j_co>=0): print("\nSaddle point is at position",i_co+1,j_co+1,"of matrix 1(where count start with 1)") else: print("\nSaddle point does not exist in matrix 1") #find saddle point if exist in matrix 2 i_co1,j_co2=saddle_point(matrix_2) if(i_co1>=0 and j_co2>=0): print("\nSaddle point is at position",i_co1+1,j_co2+1,"of matrix 2(where count start with 1)") else: print("\nSaddle point does not exist in matrix 2")
77385aa72ad3f52dee6494bea4570320d89c4cbb
tmaxe/labs
/Lab_1/spider.py
194
3.796875
4
import turtle turtle.shape('turtle') c=12 x=0 a=100 n=360 b=180-n/c while x<c: turtle.forward(a) turtle.stamp() turtle.left(180) turtle.forward(a) turtle.left(b) x +=1
cc33612f8e1f927c1ed1108e5bd3271792b925d7
EDDChang/Junyi-2021
/2.py
682
3.59375
4
import unittest import math class TargetCalculator: def count(self, x): return x - math.floor(x/3) - math.floor(x/5) + 2*math.floor(x/15) class TargetCalculatorTest(unittest.TestCase): def test_example_testcase(self): TC = TargetCalculator() self.assertEqual(TC.count(15), 9) def test_my_testcase0(self): TC = TargetCalculator() self.assertEqual(TC.count(0), 0) def test_my_testcase1(self): TC = TargetCalculator() self.assertEqual(TC.count(13), 7) def test_my_testcase2(self): TC = TargetCalculator() self.assertEqual(TC.count(199), 120) if __name__ == '__main__': unittest.main()
9bda1a952f1ae43c3abb1c02df2a54f943be97aa
arpitmx/PyProjectFiles
/Prog11.py
1,201
3.6875
4
def PUSH(l): ll = savelist.l ll.append(l) savelist(ll) return ll def POP(): ll = savelist.l if not(l.__len__() == 0): ll.pop() savelist(ll) return ll else: print("Can't Pop, No Items in the list.") def PEEK(n): ll = savelist.l return print("Value at ",n," : ",ll[n]) def TRAVESE(): ll = savelist.l return ll def savelist(ll): savelist.l = ll l = [] savelist(l) while(True): print("===============================\nLIST =>\n",savelist.l,"\n=============================") print("1.PUSH\n2.POP\n3.PEEK\n4.TRAVERSE\n5.QUIT") inp = int(input("Choose(1,2,3,4) :")) if(inp == 1): bid = input("Enter id :") bn = input("Enter name :") ba = input("Enter author :") bp = input("Enter publisher :") bprice = input("Enter price :") l = [bid,bn,ba,bp,bprice] lpushed = PUSH(l) if (inp==2): lpop = POP() print(lpop) if (inp ==3): n = int(input("Enter index :")) PEEK(n) if (inp==4): print(TRAVESE()) if (inp==5): quit()
5f7d1a176d30334fff1acd74acd30443ee63fcbc
malaikaandrade/BOA
/OriObjetos.py
662
3.59375
4
class Perro: #molde de obejetos def __init__(self, nombre, raza, color, edad): self.nombre = nombre self.raza = raza self.color = color self.edad = edad self.otro = otra_persona #metodos def saludar(self): print('Hola {nombre}, cómo estás? '.format(nombre=self.nombre)) def saludar_a_otra_persona(self): print('Hola {nombre}! muy bien y tú {otro} ? '.format(nombre=self.nombre, otro=self.otra_persona.nombre)) #OBJETOS Lua = Perro('Lua', 'chihuahua', 'beige', 3) Lazaro = Perro('Lazaro', 'labrador', 'miel', 5) """ Lua.saludar() Lazaro.saludar_a_otra_persona() """ Lua.saludar_a_otra_persona(Lazaro) Lazaro.saludar_a_otra_persona(Lua)
a42ed5941d4c983e667a840cc59b74087b0aba7b
thodge03/CD_Python
/ScoresAndGrades.py
691
3.96875
4
import random def scores(num): for i in range(0,num): random_num = random.randrange(60,101,1) if random_num >= 60: if random_num >= 70: if random_num >= 80: if random_num >= 90: print 'Score: ' + str(random_num) + '; Your grade is A.' else: print 'Score: ' + str(random_num) + '; Your grade is B.' else: print 'Score: ' + str(random_num) + '; Your grade is C.' else: print 'Score: ' + str(random_num) + '; Your grade is D.' print 'End of program. Bye!' scores(10)
423c89bd1b2284cbe7ae7ca1588990f99690f602
CrazyBinXXX/Stock-Project-X
/test.py
1,026
3.953125
4
class ListNode: def __init__(self, x): self.val = x self.next = None def oddEvenList(head): # write code here odd = True cur = head head2 = ListNode(-1) cur2 = head2 last = None final = None while cur: print(cur.val) if odd: if not cur.next or not cur.next.next: final = cur last = cur cur = cur.next odd = False else: print('last', last.val) last.next = cur.next cur2.next = cur cur2 = cur2.next temp = cur cur = cur.next temp.next = None odd = True final.next = head2.next print(final.val) return head head = ListNode(2) head2 = ListNode(3) head3 = ListNode(4) head4 = ListNode(5) head5 = ListNode(6) head.next = head2 head2.next = head3 head3.next = head4 head4.next = head5 ret = oddEvenList(head) print( ) print(ret.val) print(ret.next.val) print(ret.next.next.next.val)
6ae10197706b1ade4728287d8c80f19081a62b46
GingerWW/turtle
/spiral.py
591
4.0625
4
import turtle turtle.color('purple') #设置画笔颜色 turtle.pensize(2) #设置画笔宽度 turtle.speed(5) #设置画笔移动速度 t=turtle.Screen() def draw(turtle, length): if length>0: #边长大于0递归,画到最中心停止 turtle.forward(length) turtle.left(90) #每次画线后,画笔左转90度 draw(turtle,length-4) #利用递归再次画线,设置离上一圈的画线距离 draw(turtle,200) #设置第一圈的边长 t.exitonclick() #使turtle对象进入等待模式,点击清理退出运行
32a4d948882e3266e9d27bdb147c2b5234ef55e3
adykumar/Grind
/module3.py
1,158
3.8125
4
#------------------------------------------------------------------------------- # Name: module3 # Purpose: # # Author: Swadhyaya # # Created: 17/12/2016 # Copyright: (c) Swadhyaya 2016 # Licence: <your licence> #------------------------------------------------------------------------------- def count_palindromes( S): l= len(S) count=0 for i in range(0,l): left= i; right=i; while(left>=0 and right<l): print "\n*",S[left:right+1], "-",S[right:left-1:-1], if len(S[left:right+1])==1 or (S[left:right+1] == S[right:left-1:-1]): count=count+1 print 1, left=left-1 right=right+1 left2= i; right2=i+1; while(left2>=0 and right2<l): print "\n**",S[left2:right2+1], S[right2:left2-1:-1], if S[left2:right2+1] == S[right2:left2-1:-1]: count=count+1 print 1, left2=left2-1 right2=right2+1 return count def main(): count_palindromes("wowpurerocks") s= "worldr" print "999",s[4:0:-1] if __name__ == '__main__': main()
1bbc9011bd011a7f80be71042f27fb4ebebf4171
adykumar/Grind
/py_MergeSortedArrays.py
854
3.75
4
#------------------------------------------------------------------------------- # Name: module11 # Purpose: # # Author: Swadhyaya # # Created: 25/12/2016 # Copyright: (c) Swadhyaya 2016 # Licence: <your licence> #------------------------------------------------------------------------------- def merge2(arr1,arr2): res=[] l1= len(arr1)-1; l2= len(arr2)-1 i=0; j=0; while i<=l1 and j<=l2: if arr1[i]<=arr2[j]: res.append(arr1[i]) i=i+1 else: res.append(arr2[j]) j=j+1 if i>l1: return res+arr2[j:l2+1] return res+arr1[i:l1+1 ] def main(): arr1=[-3,1,3,6,7,7,11,11,12] arr2=[0,2,2,3,4,5,8,11,11,11,21,22,23,24,34] print arr1,arr2 print sorted(arr1+arr2) print merge2(arr1,arr2) if __name__ == '__main__': main()
77ad0d661f7eace3987f0b8c1d6ba2b037862474
Phoenix951/LabsForMSU
/Exc_4.py
789
3.9375
4
def exercise_one(search_number): """ В упорядоченном по возрастанию массиве целых чисел найти определенный элемент (указать его индекс) или сообщить, что такого элемента нет. Задание 3. Страница 63. :param search_number: искомое число :return: индекс искомого числа """ list_of_numbers = [5, 1, 12, 15, 2, 9, 21, 45, 33, 30] list_of_numbers.sort() print(f"Массив чисел: {list_of_numbers}") for i in range(len(list_of_numbers)): if search_number == list_of_numbers[i]: print(f"Индекс числа {search_number} равен {i}") exercise_one(15)
430a7b1e252b2b4dd93b638b72570599f46828ca
anhpt1993/generate_number
/generate_number.py
1,772
3.828125
4
# generate numbers according to the rules def input_data(): while True: try: num = int(input("Enter an integer greater than or equal to 0: ")) if num >= 0: return num break else: print("Wrong input. Try again please") print() except ValueError: print("Input value shall be an integer, not decimal or string") print() def generate(number): my_string = "0123456789" convert_number = str(number) result = "" for i in range(len(convert_number)): my_string = my_string.replace(convert_number[i],"") #print(my_string) for i in range(len(my_string)): if my_string[i] > convert_number: result = my_string[i] + my_string[0] * (len(convert_number) - 1) break else: if my_string[0] != "0": result = my_string[0] * (len(convert_number) + 1) else: result = my_string[1] + my_string[0] * len(convert_number) return result def again(): print() answer = input("Do you want to play again? (Y/N): ").upper().strip() if answer == "Y" or answer == "YES": return True else: print("Bye! See you next time!!!") exit() if __name__ == '__main__': while True: print("Please enter the index of the number that you want to display") index = input_data() count = 0 string = "" while True: print(f"{generate(string)}", end = " ") string = generate(string) if count == index: break else: count = count + 1 print("\n----------------------------------\n") again()
4b7303be78949893da7503bb769445ca372be4b2
xxmatxx/orvilleVM
/examples/power.py
244
3.921875
4
def print_int(max_int): i = 0 while (i < max_int): print(i) i = i + 1 print_int(3) def power(x,p): i = 0 temp = 1 while(i < p): temp = temp * x i = i + 1 return temp print(power(3,4))
8cecdbd7fa5f734297d5668e3d047f7418899023
dkurchigin/gb-py-lesssons
/lesson6/kd_lesson6_medium.py
2,709
3.734375
4
import random def programm_title(): print("**************************") print("*GB/Python/Lesson6/MEDIUM*") print("**************************") class Person: def __init__(self, name="Person"): self.name = name self.health = 100 self.damage = 25 self.armor = 10 self.greetings() def attack(self, player2): player2.health = player2.health - self._calculate_attack_power(player2) print("{} наносит удар... У игрока {} осталось {} единиц жизни!".format(self.name, player2.name, player2.health)) def _calculate_attack_power(self, player2): return round(self.damage / player2.armor) def greetings(self): print("Игрок {} готов к бою!".format(self.name)) class Player(Person): def __init__(self, name="Player"): super().__init__(name) class Enemy(Person): def __init__(self, name="Enemy"): super().__init__(name) class GamePlay: def __init__(self, player1, player2): self.first_turn, self.second_turn = self._check_first_turn(player1, player2) print("Первым ходит игрок {}".format(self.first_turn.name)) self.main_block(self.first_turn, self.second_turn) def _check_first_turn(self, player1, player2): if random.randint(0, 1) == 0: return player1, player2 else: return player2, player1 def main_block(self, player1, player2): current_turn = player1.name while True: if player1.health <= 0: print("\nВы храбро погибли от рук {}! А ведь у него осталось всего лишь {} единиц жизни...".format(player2.name, player2.health)) break if player2.health <= 0: print("\n{}, Вы выиграли! У вас осталось {} единиц жизни".format(player1.name, player1.health)) break if current_turn == player1.name: player1.attack(player2) current_turn = player2.name else: player2.attack(player1) current_turn = player1.name programm_title() player = Player("Рыцарь-88") enemy = Enemy("Гоблин-69") player.damage = 300 print("{} нашёл крутой мечь! Теперь его урон равен {} единиц".format(player.name, player.damage)) enemy.armor = 50 print("{} одевает шлем варваров! Защита персонажа увелечина до {} единиц".format(enemy.name, enemy.armor)) new_game = GamePlay(player, enemy)
dddc3e4b90c6260f9b6e0726ebda2063062760d3
yegeli/Practice
/Practice(pymsql)/exercise01.py
1,557
3.703125
4
""" pymysql使用流程: 1. 创建数据库连接 db = pymsql.connect(host = 'localhost',port = 3306,user='root',password='123456',database='yege',charset='utf8') 2. 创建游标,返回对象(用于执行数据库语句命令) cur=db.cursor() 3. 执行sql语句 cur.execute(sql,list[])、cur.executemany(sql,[(元组)]) 4. 获取查询结果集: cur.fetchone()获取结果集的第一条数据,查到返回一个元组 cur.fetchmany(n)获取前n条查找到的记录,返回结果为元组嵌套((记录1),(记录2)) cur.fetchall()获取所有查找到的结果,返回元组 提交到数据库执行 db.commit() 回滚,用于commit()出错回复到原来的数据状态 db.rollback() 5. 关闭游标对象 cur.close() 6. 关闭连接 db.close() 练习1: 从终端用input输入一个学生姓名,查看该学生的成绩 """ import pymysql db = pymysql.connect(host = "localhost", port = 3306, user="root", password='1234', database="yege", charset="utf8") cur = db.cursor() l = [ ("qiaoshang1",22,'w',99), ("xiaoming",43,'w',87), ("pp",29,'m',69), ] # 写 # sql = "insert into cls(name,age,sex,score) values (%s,%s,%s,%s);" # 查 sql = "select * from cls where name like 'qiaoshang%';" cur.execute(sql) print(cur.fetchmany(2)) # try: # cur.executemany(sql,l) # db.commit() # except: # db.rollback() cur.close() db.close()
3ebcdb40617f4f0628d4329c652a288b009a160a
yegeli/Practice
/Review/day13_exercise01.py
824
3.9375
4
""" 手雷爆炸,伤害玩家生命(血量减少,闪现红屏),伤害敌人得生命(血量减少,头顶爆字) 要求: 可能还增加其他事物,但是布恩那个修改手雷代码 体会: 封装:分 继承:隔 多态:做 """ class Granade: """ 手雷 """ def explode(self,target): if isinstance(target,AttackTarget): target.damage() class AttackTarget(): """ 攻击目标 """ def damage(self): pass class Player(AttackTarget): def damage(self): print("扣血") print("闪现红屏") class Enemy(AttackTarget): def damage(self): print("扣血") print("头顶爆血") g01 = Granade() p01 = Player() e01 = Enemy() g01.explode(e01)
373d5194589ea6da392963fa046cb8478a9d52c4
yegeli/Practice
/第16章/threading_exercise02.py
483
4.15625
4
""" 使用Thread子类创建进程 """ import threading import time class SubThread(threading.Thread): def run(self): for i in range(3): time.sleep(1) msg = "子线程" + self.name + "执行,i=" + str(i) print(msg) if __name__ == "__main__": print("------主进程开始-------") t1 = SubThread() t2 = SubThread() t1.start() t2.start() t1.join() t2.join() print("------主进程结束-------")
e48b8c38a7a871f60a541a850fb58a177425adbe
hupeipeii/sf
/日历的算法.py
2,124
3.875
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Nov 2 09:49:04 2017 @author: hupeipei8090 """ def is_leaf_years(year): if year%400==0 or year%4==0 and year%100!=0: True else: False def get_num_of_days_in_month(year,month): if month in [1,3,5,7,8,10,12]: return 31 elif month in [4,6,9,11]: return 30 elif is_leaf_years(year): return 29 else: return 28 def get_total_num_of_days(year,month): days=0 for year in range(1800,year): if is_leaf_years(year): days+=366 else: days+=365 for month in range(1,month): days+=get_num_of_days_in_month(year,month) return days def get_start_day(year,month): return 3+get_total_num_of_days(year,month)%7 month_dict = {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'} def get_month_name(month): print month_dict[month]#字典调用 def print_month_title(year,month): print" %s %s"%(year,get_month_name(month)) print"-"*35 print" Sun Mon Tue Wed Thu Fri Sat " def print_month_body(year,month): #''''' #打印日历正文 #格式说明:空两个空格,每天的长度为5 #需要注意的是print加逗号会多一个空格 #''' i = get_start_day(year, month) if i != 7: print ' ', # 打印行首的两个空格 print ' ' * i, # 从星期几开始则空i几个空格 for j in range(1, get_num_of_days_in_month(year, month)+1): print '%4d' %j, # 宽度控制,4+1=5,j这个数占4个字符。 i += 1 if i % 7 == 0: # i用于计数和换行 print ' ' # 每换行一次行首继续空格 if __name__=='__main__': year = int(raw_input('Please input target year:') ) month = int(raw_input('Please input target month:') ) print_month_title(year, month) print_month_body(year, month)
38d91e9da11c1e369a56fa4034362cdfe300e258
jionchu/Problem-Solving
/BOJ/10001~11000/10996.py
140
3.859375
4
num = int(input()) for i in range(num*2): for j in range(num): if j%2 == i%2: print('*',end='') else: print(' ',end='') print()
a31c2c79b1f13f4a24f8b3fb9e3b7f48f7860b38
wkqls0829/codingprac
/baekjoonnum/9506.py
368
3.59375
4
def divisorsum(): n = int(input()) while(n!=-1): div = [] for i in range(1, n): if not n%i: div.append(i) if sum(div) == n: print(f'{n} = ' + ' + '.join(map(str, div))) else: print(f'{n} is NOT perfect.') n = int(input()) if __name__ == "__main__": divisorsum()
95aa1c3ba7723fe3accc9183b884d0ed188f2cb9
wkqls0829/codingprac
/baekjoonnum/camoflage.py
462
3.5625
4
import sys from collections import defaultdict def solution(clothes): result = 1 clothes_dict = defaultdict(list) for c in clothes: clothes_dict[c[1]].append(c[0]) for _, cd in clothes_dict.items(): result *= len(cd)+1 return result-1 if __name__ == '__main__': num_clothes = int(input()) clothes = [] for _ in range(num_clothes): clothes.append(sys.stdin.readline().split()) print(solution(clothes))
800f664cf6cd49ef40573f67f0c945971a70fb09
raekhan1/pythonpractice
/bfsmoles.py
2,988
3.515625
4
class Board: def __init__(self, moles): self.board = [] * 6 for i in range(0, 6): self.board.append([0] * 6) for mole in moles: column = (mole - 1) % 4 row = (mole - 1) // 4 self.board[row + 1][column + 1] = 1 def print(self): for row in range(4, 0, -1): for column in range(1,5): print(self.board[row][column], end="", flush=True) print() def whack(self, mole): column = (mole - 1) % 4 row = (mole - 1) // 4 # Center self.board[row + 1][column + 1] = (self.board[row + 1][column + 1] + 1) % 2 # Top and bottom for i in range(-1, 2): self.board[row + 1 + i][column + 1] = (self.board[row + 1 + i][column + 1] + 1) % 2 # Sides for i in range(-1, 2): self.board[row + 1][column + 1 + i] = (self.board[row + 1][column + 1 + i] + 1) % 2 def check(self): for row in range(1, 5): for column in range(1, 5): if self.board[row][column] == 1: return False return True def is_there_mole(self, position): column = ((position - 1) % 4) + 1 row = ((position - 1) // 4) + 1 if self.board[row][column] == 1: return True return False def dfs_search(board, limiter): if limiter == 0: return False, [] for hole in range(1, 17): if board.is_there_mole(hole): board.whack(hole) if board.check(): return True, [hole] state, solution = dfs_search(board, limiter - 1) if state == True: solution = [hole] + solution return state, solution board.whack(hole) return False, [] def bfs_search(board, limiter, visited=[]): if limiter == 0: return False, [] for hole in range(1, 17): # check for mole if board.is_there_mole(hole): # checking is hole already visited if hole not in visited: visited.append(hole) board.whack(hole) # checking if board is clear if board.check(): return True, [hole] # un-whacking hole to get to original board board.whack(hole) # if all the holes are visited then move to the next layer # calling up recursively state, solution = bfs_search(board, limiter - 1) if state == True: solution = [hole] + solution return state, solution return False, [] #state, solution = dfs_search(board, 5) #print(solution) moles= [5,1,3,9] board = Board(moles) state, solution = dfs_search(board, 5) print(solution) board = Board(moles) board.print() for whack in solution: print() board.whack(whack) board.print()
3fb2f1666a744d8d2c08ac8492d2025f3f6f7c9f
raekhan1/pythonpractice
/catchthefruit4.py
3,714
3.5
4
class gameObject(): def __init__(self, c, xpos, ypos, velocity): self.c = c self.xpos = xpos self.ypos = ypos self.vel = velocity class Basket(gameObject): # using inheritance for the object # drawing the basket def display(self): stroke(self.c) fill(self.c) rect(self.xpos , height - 10, 80, 10) rect(self.xpos , height - 20, 10, 15) rect( self.xpos + 70 , height - 20, 10, 15) def move(self): # moving with wrap around effect (may change later) if keyPressed: if keyCode == RIGHT: self.xpos = (self.xpos + (10 * self.vel)) % width if keyCode == LEFT: self.xpos = (self.xpos - (10 * self.vel)) % width def intersect(self, bally,ballx): #checking to see if the basket and ball intersect if height - 20 <= bally <= height : if self.xpos < ballx < self.xpos + 70: return True return False return False class Ball(gameObject): def __init__(self, c, xpos, ypos, velocity): gameObject.__init__(self, c, xpos, ypos, velocity) #using the super class so that I still inherit the game object self.create() def display(self): fill (self.c) noStroke() ellipse (self.xpos,self.ypos,20,20) def fall (self): self.ypos = self.ypos + self.vel def create (self): self.ypos = random(-1000,-200) self.xpos = random(width) def check(self): if height - 10 <= self.ypos <= height: self.create() return True return False def xposition(self): return self.xpos def yposition(self): return self.ypos class Score(): def __init__(self): self.score = 0 def addScore(self): self.score += 1 class Life(): def __init__(self): self.lives = 5 self.back = 255 def removeLife(self): if self.lives > 1: self.lives = self.lives - 1 return False elif self.lives == 1: self.back = 0 self.lives = 0 else: return True def gameOver(self): if self.lives == 0: return True return False basket = Basket(color(0), 0, 100, 2) score = Score() life = Life() balls = [] def setup(): size(450,400) frameRate(30) for i in range(int(random(1,3))): balls.append(Ball(color(255, 0, 0), 100, 100, 5) ) def draw(): background(life.back) textSize(12) fill(0) text('score:',20,30) text(score.score,20,50) text('lives Left:',100,30) text(life.lives,100,50) if life.gameOver(): fill(255) textSize(60) textAlign(CENTER, BOTTOM) text("Game over", 0.5*width, 0.5*height) del balls[:] for ball in balls: ball.display() ball.fall() if basket.intersect(ball.yposition(),ball.xposition()): #Every time a ball is caught a new ball is added to the array ball.create() score.addScore() balls.append(Ball(color(random(255),random(255),random(255)), 100, 100, random(5,10))) if ball.check(): life.removeLife() basket.move() basket.display()
d896c5ed8d00d633d4cfd6fc2b83484440d482ef
tan-adelle/hacktoberfest-entry
/myapp.py
1,665
3.921875
4
print("Title of program: Exam Prep bot") print() while True: description = input("Exams are coming, how do you feel?") list_of_words = description.split() feelings_list = [] encouragement_list = [] counter = 0 for each_word in list_of_words: if each_word == "stressed": feelings_list.append("stressed") encouragement_list.append("you should take sufficient breaks and relax, some stress is good but too much is unhealthy") counter += 1 if each_word == "confident": feelings_list.append("confident") encouragement_list.append("you can do it, continue working hard and you will make it") counter += 1 if each_word == "tired": feelings_list.append("tired") encouragement_list.append("you are stronger than you think, take a break and continue your good work") counter += 1 if counter == 0: output = "Sorry I don't really understand. Please use different words?" elif counter == 1: output = "It seems that you are feeling quite " + feelings_list[0] + ". However, do know that "+ encouragement_list[0] + "! Hope you feel better :)" else: feelings = "" for i in range(len(feelings_list)-1): feelings += feelings_list[i] + ", " feelings += "and " + feelings_list[-1] encouragement = "" for j in range(len(encouragement_list)-1): encouragement += encouragement_list[i] + ", " encouragement += "and " + encouragement_list[-1] output = "It seems that you are feeling quite " + feelings + ". Please always remember "+ encouragement + "! Hope you feel better :)" print() print(output) print()
c385a9dfffedbd0794a4775937ca642a3510d7d3
Cyberfallen/Latihan-Bahasa-Pemrograman
/python/File/dasar.py
408
3.953125
4
print("Baca Tulis File") print("Menulis Sebuah Teks Nama Ane Ke Txt Ngeh") f = open("ngeh.txt", "w") f.write("Aji Gelar Prayogo\n") f.write("1700018016") f.close() print("Mengakhiri Fungsi Tulis File") print() print("Membaca File Ngeh.txt") f = open("ngeh.txt", "r") for baris in f.readlines(): print(baris) #The readlines() method returns a list containing each line in the file as a list item print()
874b927a486d77e79b3797f610ebcf7daf0a082d
Cyberfallen/Latihan-Bahasa-Pemrograman
/python/random_angka.py
169
3.53125
4
import random print("Program Untuk Menampilkan Angka Sembarang") print("Batas = 20") print("Pembatas = 50") for x in range(20): print (random.randint(1,10)) print
2391e9662e168d79c6021d15b27af3411d56cb33
Cyberfallen/Latihan-Bahasa-Pemrograman
/python/kondisi.py
485
3.78125
4
print "Program Untuk Membuat Suatu Kondisi Sekaligus Meneima Inputan" print "Apa Tipe Gender Anda : " a = raw_input("L/P : ") if a == "L" or a == "l" : print "Anda Laki-Laki" elif a == "P" or a == "p" : print "Anda Perempuan" else : print "Inputan Tidak Sesuai" print "Bentuk Logika" print " " print "Apakah Anda Siap Belajar Python?" b = raw_input("y/t : ") percaya = b =="y" if percaya : print "Anda Siap Menjadi Programmers" else : print "Anda Belum Siap Menjadi Programmers"
a0cc1bb2589478949fa5ebf250857dda8c9ce464
Cyberfallen/Latihan-Bahasa-Pemrograman
/python/Memotong_List.py
266
3.625
4
finisher = ["aji", "gelar", "pray"] first_two = finisher[1:3] print(first_two) """ Kepotong Sebelah Kiri 1: --> gelar, pray 2: --> pray 3: --> Memotong Dari Sebelah Kanan :1 --> aji :2 --> aji, gelar :3 --> aji, gelar, pray 1:3 -->gelar, pray """
ff2c02e52a904c563aaf56b47e8ef57bd921a4a1
Cyberfallen/Latihan-Bahasa-Pemrograman
/python/While.py
107
3.703125
4
print("Contoh Program Untuk Penggunaan While") print("Batas = 20") a=0 while a<=20: a = a+1 print(a)
df273e0b1a4ec97f7884e64e0fe1979623236fb2
bdjilka/algorithms_on_graphs
/week2/acyclicity.py
2,108
4.125
4
# Uses python3 import sys class Graph: """ Class representing directed graph defined with the help of adjacency list. """ def __init__(self, adj, n): """ Initialization. :param adj: list of adjacency :param n: number of vertices """ self.adj = adj self.size = n self.clock = 1 self.post = [0 for _ in range(n)] self.visited = [0 for _ in range(n)] def previsit(self): self.clock += 1 def postvisit(self, v): self.post[v] = self.clock self.clock += 1 def explore(self, v): self.visited[v] = 1 self.previsit() for u in self.adj[v]: if not self.visited[u]: self.explore(u) self.postvisit(v) def deepFirstSearch(self): """ Visits all nodes and marks their post visit indexes. Fills list post[]. """ for v in range(self.size): if not self.visited[v]: self.explore(v) def acyclic(self): """ Checks whether graph has edge in that post visit index of source vertex is less than its end vertex post index. If such edge exists than graph is not acyclic. :return: 1 if there is cycle, 0 in other case. """ self.deepFirstSearch() for v in range(self.size): for u in self.adj[v]: if self.post[v] < self.post[u]: return 1 return 0 if __name__ == '__main__': """ Input sample: 4 4 // number of vertices n and number of edges m, 1 <= n, m <= 1000 1 2 // edge from vertex 1 to vertex 2 4 1 2 3 3 1 Output: 1 // cycle exists: 3 -> 1 -> 2 -> 3 """ input = sys.stdin.read() data = list(map(int, input.split())) n, m = data[0:2] data = data[2:] edges = list(zip(data[0:(2 * m):2], data[1:(2 * m):2])) adj = [[] for _ in range(n)] for (a, b) in edges: adj[a - 1].append(b - 1) graph = Graph(adj, n) print(graph.acyclic())
16753f583825a4a04c044a314ade735202b7076d
ggrecco/python
/basico/zumbis/surfSplitNomeNotas.py
310
3.59375
4
f = open("surf.txt") #maior = 0 notas = [] for linha in f: nome, pontos = linha.split() notas.append(float(pontos)) #if float(pontos) > maior: #maior = float(pontos) f.close() #print(maior) notas.sort(reverse = True) print("1º - {}\n2º - {}\n3º - {}".format(notas[0],notas[1],notas[2]))
e3161b35c014b11888d835507c3eb8de8105b426
ggrecco/python
/basico/zumbis/imprimeParSemIF.py
135
3.953125
4
#imprimir pares de 0 ao digitado sem o if n = int(input("Digite um número: ")) x = 0 while x <= n: print(x, end = " ") x += 2
d8fe9b832e0927a1fe6d869bb10854b4c2d53bee
ggrecco/python
/basico/coursera/verifica_ordenamento_lista.py
198
3.78125
4
def ordenada(lista): b = sorted(lista) print(lista) print(b) if b == lista: return True #print("Iguais") else: return False #print("Diferente")
8c35008e3eafc6f0877dd65325ee051cea3afaf3
ggrecco/python
/basico/zumbis/jogo_2.py
291
3.734375
4
from random import randint secreta = randint(1, 100) while True: chute = int(input("Chute:")) if chute == secreta: print("parabéns, vc acertou o número {}".format(secreta)) break else: print("Alto" if chute > secreta else "Baixo") print("Fim do jogo")
e3d7c97584d737e341caae29dc639be446b80159
ggrecco/python
/basico/zumbis/trocandoLetras.py
311
3.75
4
#ler uma palavra e trocar as vogais por "*" i = 0 troca = "" palavra = input("Palavra: ") j = input("Letra: ") t = input("trocar por: ") while i < len(palavra): if palavra[i] in str(j): troca += t else: troca += palavra[i] i += 1 print("Nova: {}\nAntiga:{}".format(troca,palavra))
3542c66b49e08f505395c9f76b2bbee070677991
ggrecco/python
/basico/coursera/calculadoraVelocidadeDownload_importando_funcao_tempo.py
401
3.75
4
import fun_Tempo def calcVel(k): return k/8 i = 1 while i != 0: n = int(input("Velocidade contratada[(zero) para sair]: ")) t = (float(input("Tamanho do arquivo em MegaBytes: "))) segundos = t / calcVel(n) fun_Tempo.calcTempo(segundos) print("Velocidade máxima de Download {} MB/s\n".format(calcVel(n))) i = n #comentário de modificação nesse 1 arquivo
b49c3aaa2c6ba16a47729c07471b6ca18795fa56
ggrecco/python
/basico/zumbis/latasNecessarias.py
526
3.828125
4
''' usuário informa o tamanho em metros quadrados a ser pintado Cada litro de tinta pinta 3 metros quadrados e a tinta é vendida em latas de 18 litros, que custam R$ 80,00 devolver para o usuário o numero de latas necessárias e o preço total. Somente são vendidas nº inteiro de latas ''' m = float(input("Metros²: ")) if m % 54 != 0:#1 lata tem 18 litros que pintam o total de 54 metros latas = int(m / 54) + 1 else: latas = m / 54 valor = latas * 80 print("{} Latas custando R$ {:.2f}".format(latas,valor))
bd2dbd08dfd85e478fd10e6416536ac6490bdf62
ggrecco/python
/basico/coursera/imprime_retangulo_vazado.py
317
4.03125
4
n = int(input("digite a largura: ")) j = int(input("digite a altura: ")) x = 1 while x <= j: print("#", end="") coluna = 0 while coluna < (n - 2): if x == 1 or x == j: print("#", end="") else: print(end=" ") coluna = coluna + 1 print("#") x = x + 1
59d1bf3ee1afee7ebd9c03797a779f4beae41c18
sohanur-it/programming-solve-in-python3
/cricket-problem.py
476
3.640625
4
#!/usr/bin/python3 T=int(input("Enter the inputs:")) for i in range(1,T+1): RR,CR,RB=input("<required run> <current run> <remaining balls> :").split(" ") RR,CR=[int(RR),int(CR)] RB=int(RB) balls_played=300-RB current_run_rate=(CR/balls_played)*6 current_run_rate=round(current_run_rate,2) print("current run rate:",current_run_rate) required_run_rate=(((RR+1)-CR)/RB)*6 required_run_rate=round(required_run_rate,2) print("required run rate :",required_run_rate)
7971c61b321c45254f4d74d20494dba9b172c5b2
uchicagotechteam/HourVoice
/workbench/data_collection/combine_data.py
2,335
3.71875
4
import json from collections import defaultdict def combine_databases(databases, compared_keys, equality_functions, database_names): ''' @param databases: a list of dicts, where each dict's values should be dictionaries mapping headers to individual data points. For example, [db1, db2] with db1 = {'1': , '2': {'name': 'bar'}} @param compared_keys: a list of lists of corresponding keys to compare. For example, [['name', 'db_name']] would match solely based on comparing the 'name' column of db1 and the 'db_name' column of db2 @param database_names: corresponding names to assign to each database @param equality_functions: binary equality testing functions for each corresponding index of compared_keys, each should return a boolean @return: a combined dict of all the data, using the primary key of the first database as the primary key for the result. For example, with database_names = ['db1', 'db2'], data = {'1': {'db1': {'name': 'foo'}, 'db2': {'db_name': 'Foo'}}, '2': {'db1': {'name': 'bar'}, 'db2': {'db_name': 'Baz'}} Note: all comparisons are done to the first database ''' n = len(databases) if not n: return dict() result = defaultdict(dict) for (key, data) in databases[0].items(): result[key][database_names[0]] = data for (db_keys, equal) in zip(compared_keys, equality_functions): for base_name in databases[0].keys(): base_value = databases[0][base_name][db_keys[0]] for i in range(1,n): for (name, data) in databases[i].items(): test_value = data[db_keys[i]] if equal(base_value, test_value): result[base_name][database_names[i]] = data return result # for name in databases[0].keys(): # result[name] = {db_name: dict() for db_name in database_names} if __name__ == '__main__': db1 = {'A': {'name': 'A', 'id': 1}, 'B': {'name': 'B', 'id': 2}} db2 = {'Ark': {'name2': 'Ark', 'desc': 'I like Noah'}, 'Boo': {'name2': 'Boo', 'desc': 'I like to scare Noah'}} combined = combine_databases( databases=[db1, db2], compared_keys=[['name', 'name2']], equality_functions=[lambda x,y: x[0]==y[0]], database_names=['DB1', 'DB2']) print(combined)
9390fdf52e3768a4828ded73fefccd059537eb22
nguyenl1/evening_class
/python/notes/python0305.py
1,088
4.03125
4
""" Dictionaries Key-values pairs dict literals (bracket to bracket) {'key': 'value' } [ array: list of strings ] Immutable value (int, float, string, tuple) List and dicts cannot be keys """ product_to_price = {'apple': 1.0, "pear": 1.5, "grapes": 0.75} print(product_to_price['apple']) # print(product_to_price[1.0]) #can only access a dictionary through key not value. #update dictionary product_to_price['apple'] = 300 print(product_to_price['apple']) # add to the dictionary product_to_price['avocado'] = 5000 print(product_to_price['avocado']) #checking if key exist if 'apple' in product_to_price: print('apple ' + str(product_to_price['apple'])) #merge dictionaries product_to_price.update({'banana': 0.25}) print(product_to_price) #list of all the keys, values, and items print(list(product_to_price.keys())) print(list(product_to_price.values())) print(list(product_to_price.items())) #order dict print(sorted(product_to_price.keys())) names_and_colors = [('alice', "red"), ('david', 'green')] new_dict = dict(names_and_colors) print(new_dict)
a90e7646813c7645935894105d63434178909703
nguyenl1/evening_class
/python/labs/lab15.py
1,779
3.9375
4
""" Convert a given number into its english representation. For example: 67 becomes 'sixty-seven'. Handle numbers from 0-99. Hint: you can use modulus to extract the ones and tens digit. x = 67 tens_digit = x//10 ones_digit = x%10 Hint 2: use the digit as an index for a list of strings. """ noindex = [0,1,2,3,4,5,6,7,8,9] tens = [" ", " ", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] teens = ["ten", "eleven", "twelve", "thirteen", "forteen", "fifthteen", "sixteen", "seventeen", "eighteen", "nineteen"] ones = [" ","one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] hundreds = [" ", "one hundred and ", "two hundred and ", "three hundred and ", "four hundred and ", "five hundred and", "six hundred and ", "seven hundred and ", "eight hundred and ", "nine hundred and "] user_input = int(input("Enter a number ")) def eng(): if user_input > 9 and user_input < 20: teen_digit = user_input%10 x = noindex.index(teen_digit) teen = teens[x] print (teen) elif user_input == 0: print("zero") elif user_input > 0 and user_input < 100: tens_digit = user_input//10 x = noindex.index(tens_digit) ten = tens[x] ones_digit = user_input%10 x = noindex.index(ones_digit) one = ones[x] print (ten + one) elif user_input > 99 and user_input < 1000: hundred_index = user_input//100 x = noindex.index(hundred_index) hundred = hundreds[x] tens_digit = (user_input%100)//10 x = noindex.index(tens_digit) ten = tens[x] ones_digit = (user_input%100)%10 x = noindex.index(ones_digit) one = ones[x] print (hundred + ten + one) eng()
e39edeb39458969cef046410d03535f2f5d8a64a
nguyenl1/evening_class
/python/notes/python0225.py
851
4.0625
4
''' def my_add(num_1, num_2): a_sum = num_1 + num_2 return a_sum sum = my_add(5, 6) #the contract between the users and the function print(sum) ''' """ #variables x = 5 print (x) greeting = "hello" print (greeting) bool = 5 > 10 print (bool) """ ''' # my_string = "ThIs Is A StRiNG" # print(my_string.lower()) # def my_add(num_1, num_2): # a_sum = num_1 + num_2 # return a_sum # sum = my_add(5, 6) #the contract between the users and the function # print(sum) ''' # my_string = "ThIs Is A StRiNG" # print(my_string.lower()) # x = 5 # y = x # y += 2 #this is the same as saying y = y + 2 # print (x) # print (y) # name = input ('what is your name? ') # print(f'hello {name}') x = 'a string' user_input = input (' enter something pretty: ') print(x + " is not a " + user_input) print(f'{x} is not a {user_input')
4b3922cdedf4f4c7af87235b94af0f763977b191
nguyenl1/evening_class
/python/labs/lab23final.py
2,971
4.25
4
import csv #version 1 # phonebook = [] # with open('lab23.csv') as file: # read = csv.DictReader(file, delimiter=',') # for row in read: # phonebook.append(row) # print(phonebook) #version2 """Create a record: ask the user for each attribute, add a new contact to your contact list with the attributes that the user entered.""" # phonebook = [] # while True: # name = input("Enter your name. ") # fav_fruit = input("Enter your your favorite fruit. ") # fav_color = input("Enter your your favorite color. ") # phonebook.append({ # 'name': name, # 'fav fruit': fav_fruit, # 'fav color': fav_color}) # with open('lab23.csv', 'a') as csv_file: # writer = csv.writer(csv_file, delimiter = ',') # row = [name,fav_fruit,fav_color] # writer.writerow(row) # cont = input("Want to add another? Y/N ") # if cont != "Y": # break # print(phonebook) """Retrieve a record: ask the user for the contact's name, find the user with the given name, and display their information""" # phonebook = [] # with open('lab23.csv') as file: # read = csv.DictReader(file, delimiter=',') # for row in read: # phonebook.append(row) # print(phonebook) # user_input = input("Please enter the name of the person you would information of. ").lower() # for row in phonebook: # if row['name'] == user_input: # print(row) """Update a record: ask the user for the contact's name, then for which attribute of the user they'd like to update and the value of the attribute they'd like to set.""" # phonebook = [] # with open('lab23.csv') as file: # read = csv.DictReader(file, delimiter=',') # for row in read: # phonebook.append(row) # print(phonebook) # user_input = input("Please enter the name of the person you would information of. ").lower() # for i in phonebook: # if i['name'] == user_input: # print(i) # break # att = input("Which attribute would you like to update? (name, fav fruit, fav color) ") # change = input("What would you like to update it to? ") # if att == "name": # i["name"] = change # print (i) # elif att == "fav fruit": # i["fav fruit"] = change # print (i) # elif att == "fav color": # i['fav color'] = change # print (i) # else: # print("Try again") """ Delete a record: ask the user for the contact's name, remove the contact with the given name from the contact list. """ # phonebook = list() # user_input = input("Please enter the name of the person you would like to delete ").lower() # with open('lab23.csv', 'r') as file: # read = csv.reader(file) # for row in read: # phonebook.append(row) # for i in row: # if i == user_input: # phonebook.remove(row) # with open('lab23.csv', 'w') as writeFile: # writer = csv.writer(writeFile) # writer.writerows(phonebook)
6e52d2a6e99a95375e37dace8a996a9f10ca87cd
nguyenl1/evening_class
/python/notes/python0227.py
647
3.796875
4
# x = 5 # y = 5 # print(x is y) # print(id(x)) #returns ID of an object # truthy falsey # empty lists, strings, None is a falsey value x = [] y = [1,2,3] i = "" j = "qwerty" z = None if x: print(x) if y: print(y) # [1,2,3] if i: print(i) if j: print(j) # qwerty if z: print(z) # my_flag = True while my_flag: #will always run if the conditio is true. print("hey there ") user_input = input("do you want to say hi again?") if user_input == 'n': my_flag = False my_list = [1,2,3,4,5,6] for item in my list: if item == 4: continue print(item) x = 7 y = 34 z = 9 print(6 < y < 100)
3bd0c70f91a87d98797984bb0b17502eac466972
nguyenl1/evening_class
/python/labs/lab18.py
2,044
4.40625
4
""" peaks - Returns the indices of peaks. A peak has a lower number on both the left and the right. valleys - Returns the indices of 'valleys'. A valley is a number with a higher number on both the left and the right. peaks_and_valleys - uses the above two functions to compile a single list of the peaks and valleys in order of appearance in the original data. # """ data = [1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 5, 6, 7, 8, 9, 8, 7, 6, 7, 8, 9] noindex= [0, 1, 2, 3, 4, 5, 6, 7, 8,9, 10, 11, 12, 13,14,15,16,17,18,19,20] def peaks(): length = len(data) middle_index = length//2 first_half = data[:middle_index] second_half = data[middle_index:] # peak = first_half.index('P') peak = data.index(max(first_half)) peak_2 = data.index(max(second_half)) print(f"The index of the peak on the left is {peak}") print(f"The index of the peak on the right is {peak_2}") # peaks() def valleys(): valleys = [] for i in noindex[1:]: if data[i] <= data[i-1] and data[i] <= data[i+1]: valleys.append(i) # return valleys print(f"The indices of the valleys are {valleys}") # valleys() def peaks_and_valleys(): peaks() valleys() peaks_and_valleys() def p_v(): for i in data: print ("x" * i) p_v() #jon's ex: """ def get_data(): data = [1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 5, 6, 7, 8, 9, 8, 7, 6, 7, 8, 9] return data def get_valleys(data): valleys = [] index_list = list(range(len(data))) for i in index_list: if (i-1) in index_list and (i+1) in index_list: # makes the index start at 1 so the indexing is not out of range? if data[i] <= data[i-1] and data[i] <= data[i+1]: valleys.append(i) return valleys def get_peaks(data): peaks = [] index_list = list(range(len(data))) for i in index_list: if (i-1) in index_list and (i+1) in index_list: if data[i] >= data [i-1] and data [i] >= data [i+1]: peaks.append(i) return peaks """
208f0481f2b86a5487202000de30700f754ad873
rxbook/study-python
/06/12.py
125
3.796875
4
def power(x,n): if n == 0: return 1 else: return x * power(x,n-1) print power(2,3) print power(2,5) print power(3,4)
ca672ad960d02bc62c952f5d8bab44670fa03c24
rxbook/study-python
/05/t02.py
115
3.75
4
score = input('Enter your score:') if score >= 85: print 'Good' elif score < 60: print 'xxxxx' else: print 'OK'
530effec6984850539b440dc14870a2bd4af2f71
rxbook/study-python
/05/t13.py
133
3.796875
4
names = ['zhang','wang','zhao','li'] ages = [12,46,32,19] zip(names,ages) #for name,age in zip(names,ages): # print name,'-----',age