blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
5110936e39117ad59aabf0a69b03f11627b43def
The-Riz5-Iz6-Wiz4/PythonExercise1
/RunwayLengthRizky.py
315
3.890625
4
#input, v for velocity, a for acceleration v = float(input("Enter the plane's take off speed in m/s: ")) a = float(input("Enter the plane's acceleration in m/s^2: ")) #Formula for min runway length Runway = (v**2)/(2*a) #Output print("The minimum runway length for this airplane is", round(Runway, 4), "meters")
a3ae007c55ee2cfe220cd9094b4eaa38822ded38
CountTheSevens/dailyProgrammerChallenges
/challenge001_easy.py
803
4.125
4
#https://www.reddit.com/r/dailyprogrammer/comments/pih8x/easy_challenge_1/ # #create a program that will ask the users name, age, and reddit username. have it tell them the information back, #in the format: your name is (blank), you are (blank) years old, and your username is (blank) #for extra credit, have the program log this information in a file to be accessed later. name = input("What is your name? ") age = input("How old are you? ") if age is not int: age = input("Please enter a numeric value for your age. ") redditName = input("What's your Reddit username? ") f = open('challenge001_easy_output.txt', 'a') print('Your name is', name,', you\'re', age, 'years old, and your Reddit username is', redditName, '.') out = name,age, redditName f.write(str(out)) f.write('\n') f.close()
d23e945fb14965f2d07e327149378f79389e26bc
emanuele1234/esercitazione-22-03-2020
/main.py
364
3.953125
4
nome=input('inserisci il tuo nome ' ) età= input('inserisci la tua età ') DoveVivi=input('inserisci la città in cui abiti ') Fam=input('inserisci il numero di persone nella tua famiglia ') print(" ciao " + nome + " hai " + età+ " anni " + " vivi a " + DoveVivi + " nella tua famiglia siete " + Fam ) x=10 b=4 for i in range (5): x+=2 b*=3 print(x,b)
2b9725c92b14019c5dbf3add29d24f99c37c0554
ramneekc/Python-practice
/Prime_Factors.py
480
4.09375
4
#Function to find prime factors of a number def prime_factors(x): number =2 arr = list() while (number <= x): if (x % number) == 0: #Checks if remainder is 0 arr.append(number) #if remainder is 0, appends the number in the list x = x/number #Then keep dividing else: number+=1 #else increment the number to see next number return print(arr) prime_factors(630)
9ad6bdfc6dd78ccf4974011677b0b2d2a8e7ecab
Arsemon4ik/my_projects_OOP
/Figures(1.10.1)/Figures.py
585
3.84375
4
class Circle: def __init__(self, x=0 ,y=0 ,width=0 ,height=0): self.x = x self.y = y self.width = width self.height = height def GetInf(self): return print("Circle ({0}, {1}, {2}, {3}). ".format(self.x,self.y,self.width,self.height)) class Recktangle: def __init__(self, x=0 ,y=0 ,width=0 ,height=0): self.x = x self.y = y self.width = width self.height = height def GetInf(self): return print("Recktangle ({0}, {1}, {2}, {3}). ".format(self.x,self.y,self.width,self.height))
748b1fc72ef44444603c1ddb5d523361b2fef57d
joedave1/python
/permutethecollectionofnumbers.py
345
3.890625
4
def permutethenumber(nums): res_perms = [[]] for n in nums: new_perms = [] for perm in result_perms: for i in range(len(perm)+1): new_perms.append(perm[:i] + [n] + perm[i:]) res_perms = new_perms return res_perms a = [1,2,3] print("before permutation: ",a) print("after permutations:\n",permutethenumber(a))
7230422542419f317702d1ccd90bca72f6271c63
joedave1/python
/dletionofdictionary.py
127
3.609375
4
d={"red":10,"blue":34} if "red" in d: del d["red"] print(d)d={"red":10,"blue":34} if "red" in d: del d["red"] print(d)
fec114dd44a3b0725fed2699e1bf3b311969e1ab
joedave1/python
/patternreverse.py
211
3.734375
4
def pattern(n): for i in range(0,n): for k in range(n,i,-1): print(" ",end="") for j in range (0,i+1): print("*",end="") print("\r") n=int(input()) pattern(n)
0ac9dce99d8fa19c1b685d6b29ac8dab23176d40
dmsmiley/Python_FunProjects
/higher-lower_guessing_game.py
869
4.09375
4
#creating guessing game from 1-100. computer tells user if the num is higher or lower. congrats message when correct guess. print out num of guesses. allow users to restart import random import sys def end_game(): print("\nThank you for playing!") print("Good bye!") print(input("Press ENTER to exit")) sys.exit() def main_game(): guess = True a = random.randint(1,101) count = 0 while guess == True: b = int(input("What number am I thinking? ")) count += 1 if a == b: print("That's right!") print(f"It took you {count} guesses") go_again() elif a < b: print("Lower") else: print("Higher") def go_again(): reply = input("Would you like to play again?: ") reply = reply.lower() if reply == "yes": main_game() elif reply == "y": main_game() else: end_game() main_game()
64db6b4bc1cbdbbd32f0ff61f7ccc9b555a93f62
pillieshwar/heaven
/dict_of_bdays.py
768
4.03125
4
#!/usr/bin/python # -*- coding: utf-8 -*- from datetime import date from datetime import datetime def dict_of_bdays(): today = date.today() d1 = today.strftime("%d/%m") dict = { '17/07': 'Eshwar', '01/03': 'Devi', '04/11': 'Nana', '02/06': 'Amma', '04/09': 'Krishna', '31/10': 'Isha', '17/09': 'susan', '03/10': 'Rajeshwari', '06/08': 'anurag agarwal', '28/05': 'deepali', '02/02': 'sudeep', '10/04': 'sai chand', d1: 'no one' } print ('searched for birthdays') print ('dict[d1]',dict[d1]) print ('d1',d1) msg = 'There are no birthdays today BOSS' if(d1 in dict): msg = 'Let me check once Boss, Today '+ dict[d1] + 's birthday' return msg
199cc666d97a3fdc6e1afc98ec06c33f005ae051
iSkylake/Algorithms
/Tree/ValidBST.py
701
4.25
4
# Create a function that return True if the Binary Tree is a BST or False if it isn't a BST class Node: def __init__(self, val): self.val = val self.left = None self.right = None def valid_BST(root): inorder = [] def traverse(node): nonlocal inorder if not node: return traverse(node.left) inorder.append(node.val) traverse(node.right) traverse(root) if sorted(inorder) == inorder: return True else: return False a = Node(5) b = Node(2) c = Node(7) d = Node(4) e = Node(9) a.left = b a.right = c c.left = d c.righ = e print(valid_BST(a)) a = Node(5) b = Node(2) c = Node(7) d = Node(4) e = Node(9) a.left = b b.right = d a.right = c c.righ = e print(valid_BST(a))
7c6895415c7f493062c06626e567fa32c3e66928
iSkylake/Algorithms
/Array/Merge2Array.py
735
4.15625
4
# Given two sorted arrays, merge them into one sorted array # Example: # [1, 2, 5, 7], [3, 4, 9] => [1, 2, 3, 4, 5, 7, 9] # Suggestion: # Time: O(n+m) # Space: O(n+m) from nose.tools import assert_equal def merge_2_array(arr1, arr2): result = [] i, j = 0, 0 while i < len(arr1) and j < len(arr2): if arr1[i] <= arr2[j]: result.append(arr1[i]) i += 1 else: result.append(arr2[j]) j += 1 while i < len(arr1): result.append(arr1[i]) i += 1 while j < len(arr2): result.append(arr2[j]) j += 1 return result class Merge_2_Array(object): def test(self, func): assert_equal(func([1, 5, 7, 8], [2, 3, 4, 10]), [1, 2, 3, 4, 5, 7, 8, 10]) print("TEST PASSED") t = Merge_2_Array() t.test(merge_2_array)
4c06aaff66f7cd2dfd918d4249988da2375ec831
iSkylake/Algorithms
/Array/DynamicArray.py
641
3.609375
4
class Dynamic_Array: def __init__(self): self.array = [None for i in range(2)] self.capacity = 2 self.fill = 0 def incrementSize(self): tempArray = self.array self.capacity *= 2 self.array = [None for i in range(self.capacity)] for i in range(self.fill): self.array[i] = tempArray[i] def push(self, value): if self.fill >= len(self.array): self.incrementSize() self.array[self.fill] = value self.fill += 1 dynArray = Dynamic_Array() dynArray.push(1) print(dynArray.array) dynArray.push(2) print(dynArray.array) dynArray.push(3) dynArray.push(4) print(dynArray.array) dynArray.push(5) print(dynArray.array)
92803502bd1d37d5c73015816ba141e760938491
iSkylake/Algorithms
/Linked List/LinkedListReverse.py
842
4.15625
4
# Function that reverse a Singly Linked List class Node: def __init__(self, val=0): self.val = val self.next = None class LinkedList: def __init__(self): self.head = None self.tail = None self.length = 0 def append(self, val): new_node = Node(val) if self.length == 0: self.head = new_node else: self.tail.next = new_node self.tail = new_node self.length += 1 # First Attempt def reverse_list(node): previous = None current = node next_node = node.next while current != None: current.next = previous previous = current current = next_node if current != None: next_node = current.next # Cleaner def reverse_list(node): previous = None current = node next_node = node.next while current != None: next_node = current.next current.next = previous previous = current current = next_node
54cbfa4a99036b2435dd5568eca342d1a7a972a4
iSkylake/Algorithms
/Array/LongestPalindrome.py
1,542
3.921875
4
# Given a string, determine the longest substring palindrome # Example: # "OnlyBananaIsAlowed" => 5 # Suggestion: # Time: O(n^2) # Space: O(n) from nose.tools import assert_equal # def longestPalindrome(n, s): # max_lenght = 0 # for i in range(n): # left = i # right = i + 1 # count = 0 # while left >= 0 and right < n: # print('ENTER') # if s[left] == s[right]: # left += 1 # right += 1 # count += 2 # max_lenght = max(count, max_lenght) # print(max_lenght) # else: # left = -1 def longestPalindrome(string): max_odd = 0 s = string.lower() n = len(s) for i in range(n): left = i-1 right = i+1 count = 1 while left >= 0 and right < n: if s[left] == s[right]: left -= 1 right += 1 count += 2 max_odd = max(count, max_odd) else: left = -1 max_even = 0 for i in range(n): left = i right = i + 1 count = 0 while left >= 0 and right < n: if s[left] == s[right]: left -= 1 right += 1 count += 2 max_even = max(count, max_even) else: left = -1 return max(max_odd, max_even) print(longestPalindrome("monkeybananacarsaibohphobialoool")) print(longestPalindrome("bananaAButTuba")) print(longestPalindrome("mydadlikestodriveracecars")) class Longest_Palindrome(object): def test(self, func): assert_equal(func("monkeybananacarsaibohphobialoool"), 11) assert_equal(func("bananaAButTuba"), 8) assert_equal(func("mydadlikestodriveracecars"), 7) print("TESTS PASSED") t = Longest_Palindrome() t.test(longestPalindrome)
bfbbd4597dc0bd440c79c7caacf6b8a9da719db3
iSkylake/Algorithms
/Array/IslandCoordinate.py
725
3.765625
4
matrix = [ [0, 1, 1, 1, 1, 0], [0, 1, 0, 0, 1, 0], [1, 1, 0, 0, 1, 1], [0, 1, 1, 1, 1, 0], [0, 1, 0, 0, 1, 0], ] def islandCoordinate(matrix): coordinates = [] for i in range(len(matrix)): for j in range(len(matrix[i])): if matrix[i][j] == 0: if i == 0 and j == 0 or i == 0 and matrix[i][j-1] == 1 or j == 0 and matrix[i-1][j] == 1 or matrix[i-1][j] == 1 and matrix[i][j-1] == 1: coordinates.append(str(i) + str(j)) row = i col = j while col != len(matrix[row])-1 and matrix[row][col+1] != 1: col += 1 while row != len(matrix)-1 and matrix[row+1][col] != 1: row += 1 coordinates.append(str(row) + str(col)) return coordinates print(islandCoordinate(matrix))
7b96cb85af8b54357dc5a1a134016d6e34b1430d
NAruneshwar/SSW810
/HW08_Arun_Nalluri.py
3,480
3.59375
4
import os import datetime from prettytable import PrettyTable def date_arithmetic(): """ This function performs date Operations""" date1 = "Feb 27, 2000" dt1 = datetime.datetime.strptime(date1,"%b %d, %Y") #changing the date format into python date dt2 = dt1 + datetime.timedelta(days=3) date2 = "Feb 27, 2017" dm1 = datetime.datetime.strptime(date2,"%b %d, %Y") dm2 = dm1 + datetime.timedelta(days=3) date3 = "Jan 1, 2017" date4 = "Oct 31, 2017" dm3 = datetime.datetime.strptime(date3, "%b %d, %Y") dm4 = datetime.datetime.strptime(date4, "%b %d, %Y") delta = dm4 - dm3 #Returning the tuple return dt2, dm2, delta.days def file_reading_gen(path, fields, sep=',', header=False): """ Generator to read columns in the given file """ try: fp = open(path,"r") except FileNotFoundError: raise FileNotFoundError else: with fp: if header is True: next(fp) for offset, line in enumerate(fp): current = line.strip().split(sep) if len(current) != fields: raise ValueError(f" {fp} has {len(current)} on line {offset+1} and {fields} ") else: yield tuple(line.strip().split(sep)) class FileAnalyzer: """ Class to implement analyze_filers, pretty_print functions """ def __init__(self, directory): """ Function to initalizes variable directory """ self.directory = directory self.files_summary = self.analyze_files() def analyze_files(self): """ Function to count number of lines, characters, functions and classes in a file """ self.list_d = dict() try: list_files = os.listdir(self.directory) except FileExistsError: raise FileExistsError("not found") else: for file in list_files: if file.endswith(".py"): try: fp = open(os.path.join(self.directory, file), "r") except FileNotFoundError: raise FileNotFoundError("Cant find file pls") else: with fp: num_lines, num_char, num_func, num_class = 0,0,0,0 file_name = file for line in fp: line = line.strip() num_lines += 1 num_char = num_char + len(line) if line.startswith("def ") and line.endswith(":"): num_func += 1 elif line.startswith("class ") and line.endswith(":"): num_class += 1 self.list_d[file_name] = {"class": num_class, "function": num_func, "line": num_lines, "char": num_char} return self.list_d def pretty_print(self): """ To print the file summary in a pretty table""" pretty_table = PrettyTable(field_names = ["File Name", "Classes", "Functions", "Lines", "Characters"]) for file_name in self.list_d: pretty_table.add_row([file_name, self.list_d[file_name]["class"], self.list_d[file_name]["function"], self.list_d[file_name]["line"], self.list_d[file_name]["char"]]) return pretty_table
670c181474a898dedcab7c157a324d51e811a9a8
NAruneshwar/SSW810
/HW04_Arun_Nalluri.py
4,989
4.21875
4
import unittest def GCD(x,y): """Takes two inputs and returns the Greatest common divisor and returns it""" while(y): x, y = y, x % y return x class Fraction: """Class Fraction creates and stores variables while also doing operations with fractions""" def __init__(self,numerator,denominator): """Initialise the numerator and denominator""" self.numerator = numerator self.denominator = denominator if denominator==0: raise ZeroDivisionError("denominator can not be 0") def __str__(self): """Default print function""" return(f"{self.numerator}/{self.denominator}") def __add__(self,other): """Adds two fractions using + symbol""" numerator=self.numerator*other.denominator numerator2=self.denominator*other.numerator resultnumerator = numerator+numerator2 resultdenominator = self.denominator*other.denominator return (Fraction(resultnumerator,resultdenominator).simplify()) def __sub__(self,other): """subtracts two fractions using - symbol""" numerator=self.numerator*other.denominator numerator2=self.denominator*other.numerator resultnumerator = numerator-numerator2 resultdenominator = self.denominator*other.denominator return (Fraction(resultnumerator,resultdenominator).simplify()) def __mul__(self,other): """Multiplies two fractions using * symbol""" if(self.denominator*other.denominator<0): resultnumerator = -1*self.numerator*other.numerator resultdenominator = abs(self.denominator*other.denominator) else: resultnumerator = self.numerator*other.numerator resultdenominator = self.denominator*other.denominator return (Fraction(resultnumerator,resultdenominator).simplify()) def __truediv__(self,other): """Devides two fraction using / symbol""" resultnumerator = self.numerator*other.denominator resultdenominator = self.denominator*other.numerator return (Fraction(resultnumerator,resultdenominator).simplify()) def __eq__(self,other): """takes two fractions and tests if they are equal""" numerator1=self.numerator*other.denominator numerator2=self.denominator*other.numerator if(numerator1==numerator2): return True else: return False def __ne__(self, other): """takes two fractions and tests if they are not equal""" numerator=self.numerator*other.denominator numerator2=self.denominator*other.numerator if(numerator!=numerator2): return True else: return False def __lt__(self, other): """takes two fractions and tests if first one is less than second""" numerator=self.numerator*other.denominator numerator2=self.denominator*other.numerator if(numerator<numerator2): return True else: return False def __le__(self, other): """takes two fractions and tests if first one is less or equal to the second""" numerator=self.numerator*other.denominator numerator2=self.denominator*other.numerator if(numerator<=numerator2): return True else: return False def __gt__(self, other): """takes two fractions and tests if first one is greater than second""" numerator=self.numerator*other.denominator numerator2=self.denominator*other.numerator if(numerator>numerator2): return True else: return False def __ge__(self, other): """takes two fractions and tests if first one is greater than or equal to second""" numerator=self.numerator*other.denominator numerator2=self.denominator*other.numerator if(numerator>=numerator2): return True else: return False def simplify(self): """simplifing the fraction to least common dinominator""" theHCF= GCD(self.numerator,self.denominator) return Fraction(int(self.numerator/theHCF),int(self.denominator/theHCF)) def count_vowels(s): """Used to count the vowels in the sequence""" s = s.lower() counter=0 for x in s: if(x in ['a','e','i','o','u']): counter+=1 return counter def last_occurrence(target, sequence): """Used to return the last occurence of the target in the sequence""" counter=0 if target not in sequence: return None for x in sequence: if x == target: result = counter counter+=1 return result def my_enumerate(seq): """this emulates the enumerate function""" counter = 0 for k in seq: yield(counter,k) counter+=1
82a0de9056535e13b6096bf799a206446410dc6d
verronique/git-repo
/lesson1_normal.py
3,288
3.75
4
#__author__ = Veronika Zelenkevich # Задача-1: Дано произвольное целое число, вывести самую большую цифру этого числа. # Например, дается x = 58375. # Нужно вывести максимальную цифру в данном числе, т.е. 8. # Подразумевается, что мы не знаем это число заранее. # Число приходит в виде целого беззнакового. # Подсказки: # * постарайтесь решить задачу с применением арифметики и цикла while; # * при желании и понимании решите задачу с применением цикла for. import math print("Задача 1") n = int(input("Введите любое число")) i = 10 y = 1 b = 0 while (n * 10) > i: a = (n % i) // y i = i * 10 y = y * 10 if a >= b: b = a elif a < b: b = b print(b) # выводим самое большое число из n # Задача-2: Исходные значения двух переменных запросить у пользователя. # Поменять значения переменных местами. Вывести новые значения на экран. # Решите задачу, используя только две переменные. # Подсказки: # * постарайтесь сделать решение через действия над числами; # * при желании и понимании воспользуйтесь синтаксисом кортежей Python. print("Задача 2") a = int(input("Введи число, которое будет переменной a")) b = int(input("Введи число, которое будет переменной b")) print("Поменяем местами переменные a и b") a = a + b b = a - b a = a - b print("Переменная a = ", a) print("Переменная b = ", b) # Задача-3: Напишите программу, вычисляющую корни квадратного уравнения вида # ax² + bx + c = 0. # Коэффициенты уравнения вводятся пользователем. # Для вычисления квадратного корня воспользуйтесь функцией sqrt() модуля math: # import math # math.sqrt(4) - вычисляет корень числа 4 print("Задача 3") a = int(input("Введите коэффициент a, коэффициент не может быть равен 0")) b = int(input("Введите коэффициент b")) c = int(input("Введите коэффициент c")) print("Посчитаем корни квадратного уравнения с заданными коэффициентами") D = b**2 - (4 * a * c) if D > 0: root1 = ((b * (-1)) + math.sqrt(D)) / (2 * a) root2 = ((b * (-1)) - math.sqrt(D)) / (2 * a) print("Корни уравнения ", root1, root2) elif D == 0: root = (b * (-1)) / (2 * a) print("Корень уравнения ", root) elif D < 0: print("Уравнение не имеет корней")
9fa9a917c2e1b2087edd8e93461fa62b780e32d0
annafawn/CSC231---Introduction-to-Data-Structures
/Lab 02 - General Python and Classes/GeneratingPolygons.py
1,201
3.703125
4
import math, csv class RegularPolygon: def __init__(self, num_sides,side_length): self.num_sides = int(num_sides) self.side_length = float(side_length) def compute_perimeter(self): return round(self.num_sides * self.side_length, 2) class EquilaterialTriangle(RegularPolygon): def get_class(self): return 'EquilateralTriangle' def compute_area(self): return round(math.sqrt(3)/4 * (self.side_length)**2, 2) class Square(RegularPolygon): def get_class(self): return 'Square' def compute_area(self): return round((self.side_length)**2, 2) polygons = [] with open('polygons.csv') as csvfile: csvReader = csv.reader(csvfile) for row in csvReader: num_sides = row[0] side_length = row[1] if num_sides == '3': tri = EquilaterialTriangle(num_sides, side_length) polygons.append(tri) elif num_sides == '4': sqr = Square(num_sides, side_length) polygons.append(sqr) else: print('Invalid number of sides') for i in polygons: print(i.get_class(), i.num_sides, i.side_length, i.compute_perimeter(), i.compute_area())
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)