blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
aab14e0a5be87e456fdb4692241d5a0c427cf557
caiknife/test-python-project
/src/ProjectEuler/p059.py
2,203
4.34375
4
#!/usr/bin/python # coding: UTF-8 """ @author: CaiKnife XOR decryption Problem 59 Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107. A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byte with a given value, taken from a secret key. The advantage with the XOR function is that using the same encryption key on the cipher text, restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65. For unbreakable encryption, the key is the same length as the plain text message, and the key is made up of random bytes. The user would keep the encrypted message and the encryption key in different locations, and without both "halves", it is impossible to decrypt the message. Unfortunately, this method is impractical for most users, so the modified method is to use a password as a key. If the password is shorter than the message, which is likely, the key is repeated cyclically throughout the message. The balance for this method is using a sufficiently long password key for security, but short enough to be memorable. Your task has been made easy, as the encryption key consists of three lower case characters. Using cipher1.txt (right click and 'Save Link/Target As...'), a file containing the encrypted ASCII codes, and the knowledge that the plain text must contain common English words, decrypt the message and find the sum of the ASCII values in the original text. """ from itertools import permutations from string import ascii_lowercase def decrypt(code, password): l = len(password) return tuple(c ^ ord(password[i % l]) for i, c in enumerate(code)) def to_text(code): return "".join(chr(c) for c in code) def main(): code = tuple(int(x) for x in file("cipher1.txt").read().strip().split(",")) for p in permutations(ascii_lowercase, 3): c = decrypt(code, p) t = to_text(c) if t.find(' the ') > 0: print t print sum(ord(c) for c in t) return if __name__ == '__main__': main()
true
8c6c445d5ecc5430e418ae19f87b7231d6bd6c25
Phoenix795/learn-homework-2
/1_date_and_time.py
879
4.21875
4
""" Домашнее задание №2 Дата и время 1. Напечатайте в консоль даты: вчера, сегодня, 30 дней назад 2. Превратите строку "01/01/20 12:10:03.234567" в объект datetime """ from datetime import datetime, timedelta, date import locale locale.setlocale(locale.LC_TIME, 'ru_RU') def print_days(): delta = timedelta(days=1) today = date.today() format = '%d %B %Y - %A' print("Вчера: ", (today - delta).strftime(format)) print("Сегодня: ", today.strftime(format)) print("30 дней назад: ", (today - 30 * delta).strftime(format)) def str_2_datetime(date_string): dfs = datetime.strptime(date_string, '%d/%m/%y %H:%M:%S.%f') return dfs if __name__ == "__main__": print_days() print(str_2_datetime("01/01/20 12:10:03.234567"))
false
192cf81d9c683256b4f3d58a2701c99950159992
srirachanaachyuthuni/Basic-Programs-Python
/reverse.py
425
4.28125
4
''' Print the reverse of a number ''' def reverse(x): if (x < 0): x = abs(x) return(-1 * reverse_recursive(x,0)) else: return(reverse_recursive(x,0)) def reverse_recursive(n,rev): if n == 0: return int(rev) else: i = n % 10 rev = rev * 10 + i n = n // 10 return(reverse_recursive(n,rev)) if __name__ == '__main__': print(reverse(123))
true
abf2c7d27b5240fa1cc260633cf10106b268eec0
Stella2019/study
/57. 插入区间.py
2,809
4.46875
4
""" 给出一个无重叠的 ,按照区间起始端点排序的区间列表。 在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。   示例 1: 输入:intervals = [[1,3],[6,9]], newInterval = [2,5] 输出:[[1,5],[6,9]] 示例 2: 输入:intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] 输出:[[1,2],[3,10],[12,16]] 解释:这是因为新的区间 [4,8] 与 [3,5],[6,7],[8,10] 重叠。   注意:输入类型已在 2019 年 4 月 15 日更改。请重置为默认代码定义以获取新的方法签名。 跟LeetCode-Python-56. 合并区间类似,暴力解就是直接把新的区间插进去然后调用56的合并函数就好了。 """ # Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval] """ # tmp = Interval(newInterval[0], newInterval[1]) intervals.append(newInterval) # intervals[-1] = newInterval # print type(intervals[0]), type(tmp) return self.merge(intervals) def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ if not intervals: return [] intervals = sorted(intervals, key=lambda x: x[0]) res = [] left = intervals[0][0] right = intervals[0][1] for item in intervals: if item[0] <= right: right = max(right, item[1]) else: res.append([left, right]) left = item[0] right = item[1] res.append([left, right]) return res # Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval] """ intervals.append(newInterval) l = len(intervals) res = [] intervals = sorted(intervals, key = lambda intervals:intervals.start) low = intervals[0].start high = intervals[0].end for i in range(1, l): if intervals[i].start <= high: high = max(high, intervals[i].end) else: res.append([low, high]) low = intervals[i].start high = intervals[i].end res.append([low, high]) return res
false
2fbacc2de158d9b869a4991eafb234ba72a55d45
Cuneytyildiz/GlobalAIHubPythonCourse
/Homeworks/HW4.py
1,414
4.15625
4
from random import choice class Hangman(): def __init__(self): print("-----HANGMAN-----") print("\nRemember, you have 3 chances!\nGood Luck!") def Words(self): words = ["python","globalaihub","programming","computer"] rndword = choice(words) return rndword def Start(self,w): turns = 3 guess=[] while turns != 0: print(f"\nYour Remaining Right : {turns}\n") for letter in w: if letter in guess: print(letter,end=" ") else: print("___",end=" ") letter = input("\tGuess a Letter : ") if letter in w: print("You Guessed Right!") guess.append(letter) else: print("You Guessed Wrong!") turns -= 1 if set(w) == set(guess): print("\n-----Congratulations!-----\nYou won!") break if turns == 0: choice = input("\n-----You Lose...-----") while True: choose = input("Do you want to play ? ( Y / N ) :") if choose == 'Y' or choose == 'y': game = Hangman() newgame = game.Words() game.Start(newgame) else: print("Goodbye !!!") break
false
b42199140f19ba3c9ba2075fd35f3c53bd611b60
flacode/ds_and_algorithms
/sorting/merge_sort_2.py
1,027
4.34375
4
""" 1. merge_sort(array. start, end) 2. if elements less than 2 ie 1, array is sorted return; 3. find the midpoint 4. merge_sort(lefthalf) - always start with the left. 5. merge_sort(righthalf) 6. merge(lefthalf, righthalf) """ def merge_sort(arr): if len(arr) > 1: middle = len(arr)//2 left = arr[:middle] right = arr[middle:] merge_sort(left) merge_sort(right) i=j=k=0 while(i<len(left) and j<len(right)): if left[i] <= right[j]: # stable sort arr[k] = left[i] i += 1 else: arr[k] = right[j] j += 1 k += 1 while i<len(left): arr[k] = left[i] i += 1 k = k+1 while j<len(right): arr[k] = right[j] j += 1 k = k+1 if __name__ == '__main__': m = [7, 5, 3, 1] m_sorted = merge_sort(m) assert m_sorted == [7, 5, 3, 1].sort()
false
1d5fac9749533969f4aec92f8a5388c66f86ec18
An022/simple_calculating
/03_quadratic_solver/quadratic_solver.py
1,487
4.34375
4
""" File: quadratic_solver.py Name: An Lee ----------------------- This program should implement a console program that asks 3 inputs (a, b, and c) from users to compute the roots of equation: ax^2 + bx + c = 0 Output format should match what is shown in the sample run in the Assignment 2 Handout. """ import math import time def main(): """ If user give the constant a, b and C, we can find roots of quadratic equation: a^2x+bx+c=0. pre-condition: Inform user put the constant(a,b and c) data in order to find root(s) of quadratic equation: a^2x+bx+c=0. post-condition: Show user the root(s) of the quadratic equation: a^2x+bx+c=0 with the given input constant of a, b and c. """ print('stanCode Quadratic Solver:') a = int(input('Enter a: ')) b = int(input('Enter b: ')) c = int(input('Enter c: ')) start = time.time() discriminant = b*b-4*a*c # check discriminant is >0, ==0 or <0, then calculate the roots. if discriminant > 0: root_discriminant = math.sqrt(discriminant) ans1 = (-b + root_discriminant) / 2 * a ans2 = (-b - root_discriminant) / 2 * a print('Two roots: '+str(ans1)+' , '+str(ans2)) elif discriminant == 0: root_discriminant = math.sqrt(discriminant) ans1 = (-b + root_discriminant) / 2 * a print('One root: ' + str(ans1)) else: print('No real roots.') end = time.time() print("The time of execution of above program is :", end - start) ###### DO NOT EDIT CODE BELOW THIS LINE ###### if __name__ == "__main__": main()
true
02155e57221e342e387b76907ce8a11da6e66f54
lucasdasneves/python_puc_minas
/dictionary_16.py
413
4.125
4
#dictionary example with two loops for pessoas = { 'leasilva': { 'nome': 'Lea', 'sobrenome': 'Silva', 'curso': 'computação', }, 'eddiesilva': { 'nome': 'Eddie', 'sobrenome': 'Silva', 'curso': 'computação', } } for username, userinfo in pessoas.items(): print("Usuário: " + username) for chave, valor in userinfo.items(): print(chave + ": " + valor) print()
false
a034a5ba12a0fb5b6160dc92c5bc76d50e333472
cmnetto/PSU_GEO0485
/PennState_Data/Lesson2results/practice01.py
418
4.34375
4
#Lesson 2 Practice Exercise 01 #Find the spaces in a list of names- #Then write code that will loop through all the items in the list, printing a message like the following: #"There is a space in ________'s name at character ____." beatles = ["John Lennon", "Paul McCartney", "Ringo Star", "George Harrison"] for name in beatles: space = name.index(" ") print "There is a space in " + str(name) + "'s name at character " + str(space)
true
b448790814b573ea3795e6fec3f81e9be5eea1d2
Kumar72/PyCrashCourse
/Introduction/chapter_4.py
2,335
4.40625
4
# Working with Lists # EX: 4.1 pizzas = ['Veggie Lovers', 'Buffalo Chicken', 'Meat Lovers', 'Mediterranean'] for pizza in pizzas: print(pizza.title()) print('I can eat pizza for days!\n') # the colon indicated the start of a for loop # indent only when you are suppose to, as it is part of certain syntax ex. for loop # main cause of logical errors in python # EX: 4.2 animals = ['lion', 'leopard', 'tiger', 'cheetah'] for cat in animals: print('A '+cat.title()+' would make a nice pet.') print('Which cat would you pick as your pet?\n') # EX: 4.3 for value in range(1,20): print(value) # EX: 4.4 - 4.5 # using range() & list() function together numbers = list(range(1,1000)) print(numbers) print(min(numbers)) print(max(numbers)) print(sum(numbers)) # EX: 4.6 odd_numbers = list(range(1,20,2)) for odd in odd_numbers: print(odd) # we start the list at 2 and end at 11 and we are adding 2 every time # EX: 4.7 multiplication_list = [value*3 for value in range(1,11)] print(multiplication_list) for table in multiplication_list: print(table) # EX: 4.8 cubes = [] for value in range(1,11): cubes.append(value**3) print(cubes) # EX: 4.9 list comprehension cube_comprehension = [value**3 for value in range(1,11)] print(cube_comprehension) # EX: 4.10 slicing a list games = ['horizon zero dawn','fall out 4', 'far cry 4', 'skyrim', 'oblivion', 'witcher 3: wild hunt', 'GTA 5'] print("\nMy current list of open world games on my PS4: ") for game in games[:3]: print(game.title()) print('\nMy list of PS3 open world games: ') for game in games[3:5]: print(game.title()) print('\nGames I look forward to playing today: ') for game in games[5:]: print(game.title()) # EX: 4.11 copying a list friend_games = games[:] games.append('Battlefield 1') friend_games.append('Destiny: Collection') print('\nMy list of games: ') print(games) print("\nMy friend's list of games: ") print(friend_games) # EX: 4.12 SKIP # immutable list of objects is called a tuple and they use () instead of [] # EX: 4.13 buffet = ('Sushi', 'Burger', 'Pizza', 'Noodles' , 'Curry') for meal in buffet: print(meal) # you can reuse the variable by assigning it something new but the original list cannot be overwritten buffet = ('American', 'Chinese', 'Japanese', 'Indian', 'Mexican') for meal in buffet: print(meal)
true
61122474777f34046f69b1a5873084740dc0ca31
QuantumNovice/math-with-python
/monte_carlo_pi.py
526
4.125
4
import random NUM_POINTS = 10000 # Generates random numbers between -1 and 1 def rand(): return random.uniform(-1,1) # Generate a bunch of random points in the square which inscribes the unit circle. points = [(rand(), rand()) for i in xrange(NUM_POINTS)] # Find all points which are inside the circle - i.e. points which match the formula for # a circle: x**2 + y**2 <= 1 points_in_circle = filter(lambda point: point[0]**2 + point[1]**2 <= 1, points) print "Estimate of pi:", 4.0 * len(points_in_circle) / len(points)
true
038b1935df76cc8f72d125ce3cec86cf2fb42f26
Pops219/yoyo21
/Project_5_Leap_Year.py
344
4.125
4
leap_year = int(input("Which year do you want to check? ")) if leap_year % 4 == 0: print(str(leap_year) + " is a leap year.") elif leap_year % 100 == 0: print(str(leap_year) + " is a leap year.") elif leap_year % 400 == 0: print(str(leap_year) + " is a leap year.") else: print(str(leap_year) + " is not a leap year.")
false
bc25392f3df0f6fb26920374a477e6bfda204f14
MileyWright/cs-module-project-recursive-sorting
/src/sorting/sorting.py
1,638
4.1875
4
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): elements = len(arrA) + len(arrB) merged_arr = [0] * elements # Your code here a_counter = 0 b_counter = 0 for i in range(0, elements): if a_counter == len(arrA) or b_counter == len(arrB): # if one side runs out of numbers if a_counter == len(arrA): merged_arr[i] = arrB[b_counter] b_counter += 1 else: merged_arr[i] = arrA[a_counter] a_counter += 1 else: # compare and add lowest number if arrA[a_counter] < arrB[b_counter]: merged_arr[i] = arrA[a_counter] a_counter += 1 else: merged_arr[i] = arrB[b_counter] b_counter += 1 return merged_arr # TO-DO: implement the Merge Sort function below recursively def merge_sort(arr): # Your code here start = 0 end = len(arr) if end > start + 1: mid = int((start + end) / 2) arrA = merge_sort(arr[0:mid]) arrB = merge_sort(arr[mid:end]) arr = merge(arrA, arrB) return arr # STRETCH: implement the recursive logic for merge sort in a way that doesn't # utilize any extra memory # In other words, your implementation should not allocate any additional lists # or data structures; it can only re-use the memory it was given as input def merge_in_place(arr, start, mid, end): # Your code here pass def merge_sort_in_place(arr, l, r): # Your code here pass
true
09cbf67dd7234e78e48f66dad97724c4d38ee459
JANMAY007/python_practice
/Python language practice/python practice questions/smallest_divisor.py
240
4.15625
4
number=int(input('Enter the number whose smallest divisor you want:')) divisor=[] for i in range(1,number+1): if(number%i==0): divisor.append(i) divisor.sort() print("The smallest divisor of %d is %d."%(number,divisor[0]))
true
977539bd5a71a67ea02b097f832066891d9ae0be
asingh21/python
/data_structures/linked_list/prac/linkedlist_insert_end.py
595
4.15625
4
from linked_list import Node from linked_list import LinkedList def insert_at_end(head, data): temp = head while temp.next: temp = temp.next node_to_insert = Node(data) temp.next = node_to_insert if __name__ == '__main__': data_to_insert = 5 linked_list = LinkedList() llist = [1,2,3,4] linked_list.create_linked_list(input_list=llist) print("Linked list before") linked_list.print_list() current_head = linked_list.head insert_at_end(head=current_head, data=data_to_insert) print("Linked list after") linked_list.print_list()
true
5e70f534ccc4455d4142a9d39c4ad12801541f05
danzhou108/insertionsort
/InsertionSort.py
652
4.1875
4
def InsertionSort(input): #passes a 1-D array for insertion sort for ind in range(1,len(input)): val = input[ind] #get value of current key prevInd = ind-1 #get position of previous index while prevInd>=0 and input[prevInd]>val: #check for conditions: 1) index is in the first pos or higher 2) key in pos is greater than current key input[prevInd+1] = input[prevInd] #replace key in next pos with the key in previous pos prevInd -= 1 #move index counter down 1 input[prevInd+1] = val #once index holding smallest key value found in sorted list, replace key in that ind with current key
true
cb5f2759676c83dd7170bd97a4244b2a7dc8bd8c
nieberdinge/SchoolHelpers
/3rdDivisonAndMultiply.py
2,511
4.1875
4
def multiply(): # print("Enter the multiplicand \nexample: '0010'") # multiplicand = input("Multiplicand: ") # print("Enter product as one string\nexample: '00000011'") # product = input("Product:") multiplicand = '0110' product = '00000010' multiplicand = int(multiplicand,2) product = int(product,2) stepStr = "|{:^11}|{:^26}|{:^18}|{:^11}|".format('Iteration','Step', 'Multiplicand', 'Product') topRow = '' for x in range(len(stepStr)): if stepStr[x] == '|': topRow += '+' else: topRow += '-' step = '1 -> Prod = Prod + Mcand' shiftStep = 'Shift right Product' noStep = '0 -> No operation' #Making the table print(topRow) print(stepStr) print(topRow) print("|{:^11}|{:^26}| {:04b} | {:08b} |".format(0,'Initial Step', multiplicand,product)) print(topRow) for x in range(8): #If it is the first if(x % 2 == 0): if(str(bin(product))[2:][-1] == '0'): print("|{0:^11}|{1:^26}| {2:04b} | {3:08b} |".format(x/2+1,noStep,multiplicand,product)) else: binToStr = str(bin(product))[2:] while len(binToStr) < 8: binToStr = '0' + binToStr number = int(binToStr[0:4],2) + multiplicand number = str(bin(number))[2:] while len(number) < 4: number = '0' + number lastFour = str(bin(product)[2:])[-4:] while len(lastFour) < 4: lastFour = '0' + lastFour product = int(number + lastFour,2) print("|{0:^11}|{1:^26}| {2:04b} | {3:08b} |".format(x/2+1,step,multiplicand,product)) #Shift to the right else: product = product >> 1 if(len(str(product)) > 8): product = int(str(product)[1:],2) print("|{0:^11}|{1:^26}| {2:04b} | {3:08b} |".format('',shiftStep,multiplicand,product)) print(topRow) if __name__ == "__main__": # print("1. Multiply\n2. Divide\n3. Exit") # ans = input("Response:") # ans = int(ans) # while(ans < 1 or ans > 3): # ans = input("Enter a correct response (1 - 3): ") # ans = int(ans) ans = 1 if ans == 1: multiply() elif ans == 2: print("Too complicated") #divide() else: print("Thanks for using")
false
0f23c6652ceacec218afacdbf1766f43414c5833
derick-droid/pirple_python
/dict_set.py
654
4.3125
4
# black shoes shelves with sizes customers choose the size they wish to buy # if chosen the stock decreases and no one is allowed to choose zero and negative numbers black_shoes = {45: 2, 32: 4, 44: 4, 23: 5, 40: 2} while True: choice = int(input("enter your size: ")) if choice <= 0: print("invalid shoe size") elif choice not in black_shoes: print("your size is not currently available") elif black_shoes[choice] <= 0: print("it is out of stock") else: black_shoes[choice] -= 1 print(""" thank you for shopping with us your request is being processed """) print(black_shoes)
true
dfeb1bde407ce1eb034e0382bb009508884c3d6f
jwflory/python-howto-read-yaml
/read_yaml.py
1,185
4.4375
4
#!/usr/bin/env python3 """ A brief introduction to Python data objects. Refer to official Python docs or other online resources for more detailed explanations. list: - one - two - three list[0] -> return str list[1] -> return str dict: - "one": "first number" - "two": "second number" - "three": "third number" - "four": "obj1,obj2,obj3,obj4" dict[0].key() -> returns str dict[3].value() -> returns List """ import random import yaml # Load config file with open("test.yml") as f: config = yaml.safe_load(f) # What does this actually look like under the hood? print("An internal representation of test.yml with a list inside of a dict:\n" + str(config) + "\n") # Ask the user if they like a random food from our list print("Do you like {}?".format(random.choice(config["favorite_foods"]))) # Potatos? print("What about {}?".format(config["favorite_foods"][0])) # How about a couple foods? print("Or, there is always {} and {}.".format( config["favorite_foods"][1], config["favorite_foods"][2]) ) # I brought you a surprise... print("I knew you liked {0}, so I brought you ten boxes of {0}.".format( config["favorite_foods"][3]) )
true
1950e56dfaaa1eb686c71a41bf13f8f6a0bc8d9e
JohnBomber/mon_python
/Practice_Python/Birthday dictionaries.py
608
4.59375
5
birthday = {"Ben":"02/07/1980", "Franck":"19/08/1985", "Yann":"16/04/1988"} print("Welcome to the birthday dictionary. We know the birthdays of:") for name in birthday: print(name) name = input("Who's birthday do you want to look up?\n") if name in birthday: print("{}'s birthday is {}".format(name, birthday[name])) else: print("Sadly, we don't have {}'s birthday.".format(name)) date = input("What is {}'s birthdate ?, please type dd/mm/yyyy\n".format(name)) birthday[name] = date print("{}'s birthday is {}".format(name, birthday[name]))
true
b7e59c24ffa743bf6bef13357c3c3fb7a0684e3b
annejonas2/HW09
/presidents.py
1,113
4.21875
4
#!/usr/bin/env python # Exercise: Presidents # Write a program to: # (1) Load the data from presidents.txt into a dictionary. # (2) Print the years the greatest and least number of presidents were alive. # (between 1732 and 2015 (inclusive)) # Ex. # 'least = 2015' # 'most = 2015' # Bonus: Confirm there are no ties. ############################################################################## # Imports # Body def presidents_alive_dict(): with open("presidents.txt") as fin: d = {} for line in fin: x = line.split('\r') for item in x: pres_list = item.split(',') if pres_list[2] == 'None': pres_list[2] = 2015 d[pres_list[0]] = pres_list[1:] return d def life_ranges(d): alive_in_year_dict = {} years = [] for key in d: death_year = int(d[key][1]) birth_year = int(d[key][0]) years.append(range(birth_year,(death_year + 1))) print years ############################################################################## def main(): # CALL YOUR FUNCTION BELOW print life_ranges(presidents_alive_dict()) if __name__ == '__main__': main()
false
f017f26ee38df129916239a6adeb9af66bc922a3
KaylaZhou/python_bilibili
/慕课网/09面向对象/main/3_3.py
1,068
4.1875
4
# 在实例中访问实例变量与类变量 class Student(): sum = 0 name = '王云' age = 0 action = "xxx" # 实例方法 def __init__(self, name1, age): print('homework') # 构造函数,是一个特殊的实例方法 # print(self) self.name = name1+"xx" self.age = age + 1 # print(name1) # print(self.name) # 在实例方法中访问实例变量 # print(self.age) # 实例方法(是和对象实例相关联的.第一个参数需要传入self) # def do_homework(self): # self代表一个实例 # self.action = "到家了" # print('homework') def class_1(): xxxxx = Student("", 0) # student2 = Student('李显华', 18) print(xxxxx.name) print(xxxxx.age) # class_1() # 在实例中访问类变量 class Student(): sum1 = 88 def __init__(self, sum1): self.sum1 = sum1+2 print(self.__class__.sum1) # self内置的class,这个class代表类 print(Student.sum1) a1 = Student(22) print(a1.sum1)
false
d1c5cf061b3a84be538898f978dc02c8d1510560
KaylaZhou/python_bilibili
/慕课网/12函数式编程/main/12-1.py
481
4.125
4
# 常规函数 # def add(x, y): # return x+y # add(1, 2) # 匿名函数 def f(x, y): return x + y print(f(1, 2)) # 三元表达式 # 例子: x>y 取x,否则 取y # 其他语言的三元表达式 # x > y ? x: y # ?前面是条件判断,返回不同的结果用冒号相连(如果x>y,返回x,否则返回y) # python 中的三元表达 # 条件为真时返回的结果if 条件判断else 条件为假时的返回结果 # x = 2 # y = 5 # r = x if x > y else y # print(r)
false
a77acf91a983bd5b5e02aef23b3bd42c9585e307
KaylaZhou/python_bilibili
/慕课网/14Pythonic与Python杂记/main/2_switch.py
748
4.34375
4
''' 用python中的字典映射来代替switch 1.首先定义一个空的字典,switcher 2.用字典的key,代替1_switch的case后面的0 ,1 ,2 3.定义day_name,用字典的映射代替switch,并将变量day传入 得到的结果: 当day=0时,通过字典的映射,把'Sunday'赋值给day_name, 解决day取值之外的情况? 1.换一种字典的访问方式,用内置的get方法,get(第一个参数是key 为变量day,第二个参数将指定当day所对应的key不存在的时候方法调用的结果) get方法具有容错性 ''' day = 4 switcher = { # 字典可以是字符串,也可以是数字 0: 'Sunday', 1: 'Monday', 2: 'Tuesday' } # day_name = switcher[day] day_name = switcher.get(day, 'Unknown') print(day_name)
false
64a9c577acb0624d14b1a93f4d077f731e1c6be8
ama0322/Algorithms-in-Python
/leetcode-in-python/medium_difficulty/ZigZag Conversion.py
2,690
4.1875
4
def Solution(s, numRows): """ The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: string convert(string text, int nRows); convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". :param s: - the inputted string :param numRows: :return: """ # Edge Case if numRows == 1: return s # Edge Case if numRows == 2: first_half = "" second_half = "" for i in range(0, len(s)): if i % 2 == 0: first_half = first_half + s[i] else: second_half = second_half + s[i] return first_half + second_half # Edge Case if len(s) <= numRows: return s converted = "" row = 0 # boolean to determine whether this current character is in a column of the zig zag or a diagonal straight_col = True # Create a 2 dimensional list of lists to store the zigzag pattern zig_zag = [[] for i in range(0, numRows)] # put the characters from s into zig_zag in proper format for i in range(0, len(s)): current_char = s[i] # if in straight_column, put the current character into the proper list if straight_col: zig_zag[row].append(current_char) # if no longer in straight column, update straight_col and move the row back for the diagonal if row + 1 == numRows: straight_col = False row = row - 1 # otherwise, move on to the next row else: row = row + 1 # when not in straight_col, AKA in the diagonal. Put the current_char in to the proper list else: zig_zag[row].append(current_char) # if no longer in the diagonal, update straight_col and move the row back for the straight col if row - 1 == 0: straight_col = True row = row - 1 # should be zero # otherwise, move onto the next row else: row = row - 1 # END OF LOOP # figure out the converted strings based on the zigzag list for i in range(0, len(zig_zag)): for x in range(0, len(zig_zag[i])): converted = converted + zig_zag[i][x] return converted
true
5042813aa66e7e36365f1704fe083300ffa65701
leodengyx/LeoAlgmExercise
/DataStructure/Deque/deque.py
896
4.1875
4
class Deque(object): ''' Defines a class for double ended Queue ''' def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def addFront(self, value): return self.items.insert(0, value) def addBack(self, value): return self.items.append(value) def removeFront(self): return self.items.pop(0) def removeBack(self): return self.items.pop(-1) def __repr__(self): return "<front>%s<back>" % repr(self.items) def __str__(self): return "<front>%s<back>" % str(self.items) def main(): deque = Deque() deque.addFront(1) print(str(deque)) deque.addFront(2) print(str(deque)) deque.addFront(3) print(str(deque)) deque.addBack(10) print(str(deque)) deque.addBack(20) print(str(deque)) if __name__ == '__main__': main()
false
76e2f2d3c49bdf893496282eb9dc1a08b0826bee
aggies99/Lego-Mindstorms
/ms4/multitask/iteratorstudy/study2.py
2,144
4.4375
4
#!/usr/bin/python import random print("study2 - stand-alone iterator") # This class creates a random permutation (of size `num`). # The object is iterable; it has a stand-alone iterator. # Advantage: can have two iterators at the same time, disadvantage: extra class class Perm : def __init__(self,num) : self.nums= list(range(num)) # make a permutation for i1 in range(num) : i2 = random.randrange(i1,num) self.nums[i1],self.nums[i2] = self.nums[i2],self.nums[i1] # Having __iter__ makes an object iterable. # The __iter__() function shall return an object that has a __next__(). # Here we create a fresh iterator (it must know what to iterate) def __iter__(self) : return PermIterator(self) # An "internal" class, implementing an iterator of the Perm class class PermIterator : def __init__(self,perm) : self.perm = perm # ref to iterable self.index = 0 # the "cursor" of the iterator # Since this is an iterator, it must have __next__(). # __next__() must return all elements of the iterable, # one per call, and end by raising StopIteration # We know the internal structure of Perm (e.g. that it has a `nums`). def __next__(self) : if self.index == len(self.perm.nums ) : raise StopIteration val = self.perm.nums[ self.index ] self.index += 1 return val iterable = Perm(4) # Getting the iterator from the iterable: for-in print(" study2 - for-in") for element in iterable : print( " ", element ) # Does now work: create all combinations using two separate iterators print(" study2 - two iterators: does now work") for elm1 in iterable : for elm2 in iterable : print( " ",elm1,elm2) # study2 - stand-alone iterator # study2 - for-in # 0 # 2 # 3 # 1 # study2 - two iterators: does now work # 0 0 # 0 2 # 0 3 # 0 1 # 2 0 # 2 2 # 2 3 # 2 1 # 3 0 # 3 2 # 3 3 # 3 1 # 1 0 # 1 2 # 1 3 # 1 1
true
932a9de16a89dd0222fd70e35a44be4bff47a302
anjana24-r/projects
/abc/functional programming/demo.py
1,779
4.1875
4
#functional programming #used to reduce length of a code #they are:- #1.lambda functon #2.map fn #3.filter #4.list comprehension #.... #1.lambda function #..... #they are anonymous fn(nameless fn) # # def add(n1,n2): # return n1+n2 # print(add(10,30)) #use lambda fn # # f=lambda n1,n2 :n1+n2 # print(f(1,2)) #2.map #.......... #every object we do operation to get a output (every object need an output then we use map fn) #eg: lst=[10,20,30,40] ==>f(x) [100,400,900,1600] #[ab,cd,ef,gh,ij] ==>f(x) [AB,CD,EF,GH,IJ] #for convert each lower case to upper #3.filter #.... #filter use to get an output based on a specific condition (operation is not performed to every object) #[1,2,3,4,5,6,7,8,9,10] ==>f(x)=[2,4,6,8,10] (filter only even no.) #[ab,cd,ef]==>f(x)=[ab] #start with a only #syntax #...... #map #....... #map(fn,iterable) #filter #.. #filter(fn,iterable) #eg:square of every no. in the below list #lst=[1,2,3,4,5,6,7] # def sq(n1): # return n1*n1 # # s=list(map(sq,lst)) #lst iterable o/p should be list so list(map.....) # print(s) #above prgrm using lambda # lst=[1,2,3,4,5,6,7,8,9,10] # s=list(map(lambda num:num*num,lst)) # print(s) #filter #... #finding even no. from below list # lst=[1,2,3,4,5,6,7,8,9,10] # def even(n1): # return n1%2==0 # ev=list(filter(even,lst)) # print(ev) #using lambda # s=list(filter(lambda n1:n1%2==0,lst)) # print(s) #................... #1 to 50 # lst=[] # for i in range(1,51): # lst.append(i) # print(lst) #list comprehension # lst=[i for i in range(1,51)] # # print(lst) #map function #........... # lst=[2,3,4,5,6,7] # squares=list(map(lambda num:num**2,lst)) # print(squares) # names=["ammu","anjana"] # upp=list(map(lambda name:name.upper(),names)) # print(upp)
true
1a52735376529b9286ec9c2e6ebcdaee47c20e67
anjana24-r/projects
/abc/Function/factorial.py
442
4.21875
4
# def factorial(): # # n=int(input("enter a number")) # fact=1 # for i in range(1,n+1): # fact*=i # print(fact) # factorial() def factorial(n): fact=1 for i in range(1,n+1): fact=fact*i print(fact) factorial(3) # # def factorial(n): # fact=1 # for i in range(1,n+1): # fact=fact*i # return fact # number=int(input("enter a number")) # res=factorial(number) # print("fact=",res)
false
e4c89c0a8d86a0ce9de69817239ccc45456e9e04
anjana24-r/projects
/abc/Flow controls/3numbers.py
215
4.1875
4
n1=int(input("enter num1")) n2=int(input("enter num2")) n3=int(input("enter num3")) if(n1>n2) & (n1>n3): print(n1,"is greater") elif(n2>n1) & (n2>n3): print(n2,"is greater") else: print(n3,"is greater")
false
31fdfc3fd7ca164453ce9281decfa042d059546c
aliciawyy/sheep
/notes/iterator.py
1,229
4.1875
4
""" # Iterable vs Iterator vs Generator - s is an iterable whose method __iter__ instantiates a new iterator every time. - t is an iterator for whom the method __iter__ returns self ## Generator Any Python function that has the `yield` keyword in its body is a generator function, which, when called, returns a generator object. A generator function builds a generator object that wraps the body of the function. When we invoke `next(...)` on the generator object, execution advances to the next `yield` in the function body to evaluate the value yielded. Finally when the function body returns, the generator object raises a `StopIteration` in accordance with the iterator protocol. The iterator interface is designed to be lazy. A generator is considered as a lazy implementation as it postpones producing values to the last possible moment. This saves memory and may avoid useless processing as well. An iterator traverses a collection and yields items from it. While a generator may produce values without necessarily traversing a collection. """ s = "ABC" t = iter(s) print(repr(t)) print(repr(iter(t))) while True: try: print(next(t)) except StopIteration as e: print(repr(e)) break
true
c6c401260547cb1695540d33cc385c6b14d03324
jeffcore/algorithms-udacity
/P2/problem_1.py
1,934
4.53125
5
""" Finding the Square Root of an Integer Find the square root of the integer without using any Python library. You have to find the floor value of the square root. For example if the given number is 16, then the answer would be 4. If the given number is 27, the answer would be 5 because sqrt(5) = 5.196 whose floor value is 5. The expected time complexity is O(log(n)) Here is some boilerplate code and test cases to start with: """ import math def sqrt(number): """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root """ if number < 0: return None if number == 0 or number == 1 : return number start_num = 1 end_num = number while start_num <= end_num: mid = (start_num + end_num) // 2 mid_sqr = mid * mid if mid_sqr == number: return mid if mid_sqr < number: start_num = mid + 1 ans = mid else: end_num = mid - 1 return ans print('Test Batch 1') print ("Pass" if (3 == sqrt(9)) else "Fail") print ("Pass" if (0 == sqrt(0)) else "Fail") print ("Pass" if (4 == sqrt(16)) else "Fail") print ("Pass" if (1 == sqrt(1)) else "Fail") print ("Pass" if (5 == sqrt(27)) else "Fail") print('Test Batch 2') print ("Pass" if (5 == sqrt(25)) else "Fail") print ("Pass" if (0 == sqrt(0)) else "Fail") print ("Pass" if (15 == sqrt(225)) else "Fail") print ("Pass" if (35 == sqrt(1225)) else "Fail") print('Test Batch 3') print ("Pass" if (15 == sqrt(238)) else "Fail") print ("Pass" if (92 == sqrt(8568)) else "Fail") print ("Pass" if (8 == sqrt(66)) else "Fail") print ("Pass" if (81 == sqrt(6561)) else "Fail") print ("Pass" if (None == sqrt(-25)) else "Fail") # References: # https://www.geeksforgeeks.org/find-square-root-number-upto-given-precision-using-binary-search/
true
441378f7b9f3a7ae741c8c13570f2bdf64fa447e
jeffcore/algorithms-udacity
/P2/problem_4.py
1,991
4.28125
4
""" Dutch National Flag Problem Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. You're not allowed to use any sorting function that Python provides. Note: O(n) does not necessarily mean single-traversal. For e.g. if you traverse the array twice, that would still be an O(n) solution but it will not count as single traversal. Here is some boilerplate code and test cases to start with: """ def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ if len(input_list) == 0: return [] if len(input_list) == 1: return input_list start_pos = 0 end_pos = len(input_list) - 1 index = 0 while index <= end_pos: if input_list[index] == 0: input_list[index] = input_list[start_pos] input_list[start_pos] = 0 start_pos += 1 index += 1 elif input_list[index] == 2: input_list[index] = input_list[end_pos] input_list[end_pos] = 2 end_pos -= 1 else: index += 1 return input_list def test_function(test_case): sorted_array = sort_012(test_case) print(sorted_array) if sorted_array == sorted(test_case): print("Pass") else: print("Fail") # Test 1: Various Lists test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2]) test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1]) test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]) test_function([2, 2, 2, 2, 2, 2, 2]) test_function([0, 0, 0, 0, 0]) test_function([1, 1, 1, 1, 1, 1]) test_function([1, 1, 1, 0, 0]) test_function([2, 2, 2, 0, 0]) test_function([1, 1, 1, 2, 2]) # Test 3: Edge Test Cases test_function([2]) test_function([]) # Test 3: Already Sorted Test test_function([0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2])
true
f0c88640c42bd8c6a4fdabd72646437f21dbff9d
nsayara/PythonPaylasimlari
/06OcakWhileIleOrtalama.py
739
4.15625
4
# Program while döngüsü ile kulanacıdan sürekli sayı girmesini isteyecektir. # Eğer kullanıcı 0 girdiyse o ana kadar girlen sayıların toplamını adedini # ve ortalamasını ekrana yazdıracaktır. toplam=0 sayi=45 adet=0 while(sayi!=0): adet=adet+1 sayi=int(input(f"{adet}. Sayıyı Giriniz:")) toplam=toplam+sayi print("Döngü Sonlandı") print(f"{adet} tane sayı girdiniz") ortalama=toplam/adet print(f"Toplam={toplam}") print(f"Ortalam={ortalama}") # Program Çalıştığında Aşağıdaki çıktıyı verir. # 1. Sayıyı Giriniz:95 # 2. Sayıyı Giriniz:45 # 3. Sayıyı Giriniz:26 # 4. Sayıyı Giriniz:85 # 5. Sayıyı Giriniz:0 # Döngü Sonlandı # 5 tane sayı girdiniz # Toplam=251 # Ortalam=50.2
false
e2228b4580103d45835671159deb80f758a11971
lisu1222/Leetcode
/isPalindrome.py
239
4.21875
4
#Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. def isPalindrome(x): if x <0: return False else: if x == int(str(x)[::-1]): return True else: return False
true
3e496c9eec959b6fef4c84a094583c0b95193563
kgalloway2/Project-Euler-stuff
/Exercises 1-20/ex20.py
1,017
4.21875
4
# this loads the argv modules from sys from sys import argv # this defines our argv inputs script, input_file = argv # this defines the print_all function to just print the entire file def print_all(f): print f.read() # this defines the rewind function which takes the text file back to the beginning def rewind(f): f.seek(0) # this defines the print_A_line function which takes the input of # a line number and the file to be viewed def print_a_line(line_count, f): print line_count, f.readline() # this defines current_file as the function that opens the input file current_file = open(input_file) # the rest of this does all the printing stuff print "First let's print the whole file:\n" print_all(current_file) print "Now let's rewind, kind of like a tape." rewind(current_file) print "Let's print three lines:" current_line = 1 print_a_line(current_line, current_file) current_line += 1 print_a_line(current_line, current_file) current_line += 1 print_a_line(current_line, current_file)
true
53dbf3816746381d1a8c9929edc242e97fb8b008
kgalloway2/Project-Euler-stuff
/old project euler/peproject7.py
746
4.125
4
def nthprime(n): composite_list = [] i = 2 count = 0 while count != n: if i not in composite_list: count += 1 for j in range(i * i, n**2, i): composite_list.append(j) i += 1 return i - 1 def nthprime2(n): prime_list = [2] i = 3 count = 1 while count != n: divisible = False for p in prime_list: if i%p == 0: divisible = True break if not divisible: prime_list.append(i) count +=1 i +=1 return prime_list[len(prime_list)-1] def main(): number = input("nth prime, what is n?") print nthprime2(number) if __name__ == '__main__': main()
false
4a078102908d1038415cdfb37c89e64d295b8956
ddu0422/cloud
/Algorithm/Codeup/basic/statement/1067.py
246
4.15625
4
a = int(input()) def minus_or_plus(number): if number > 0: return "plus" return "minus" def even_or_odd(number): if number % 2 == 0: return "even" return "odd" print(minus_or_plus(a)) print(even_or_odd(a))
false
7b7740be47dc7cec49f5b53a7129d000e13fc165
waterFlowin/Python-Projects
/Bike.py
681
4.1875
4
class Bike(object): def __init__(self, price, max_speed, miles = 0): self.price = price self.max_speed = max_speed self.miles = miles def displayInfo(self): print self.price print self.max_speed print self.miles def ride(self): print "Riding" self.miles += 10 return self def reverse(self): print "Reversing" self.miles -= 5 if self.miles < 0: self.miles = 0 bike1 = Bike(200, "25 mph", 0) bike2 = Bike(100, "15 mph", 0) bike3 = Bike(50, "10mph", 0) bike1.ride().ride().ride().reverse().displayInfo() bike2.ride().ride().reverse().reverse().displayInfo() bike2.displayInfo() bike3.reverse() bike3.reverse() bike3.reverse() bike3.displayInfo()
true
c103a7dccdda7ca02d5bd37d1fb0fb73f8f59ed4
igorcapao/calculadora_v1
/calculadora_v1.py
1,076
4.40625
4
# Calculadora em Python def soma(num1, num2): """ Função que soma 2 números """ return num1 + num2 def subtracao(num1, num2): """ Função que subtrai 2 números """ return num1 - num2 def multiplicacao(num1, num2): """ Função que multiplica 2 números """ return num1 * num2 def divisao(num1, num2): """ Função que divide 2 números """ return num1 / num2 print("\n******************* Python Calculator *******************\n\n Selecione o número da operação desejada:\n\n1 - Soma\n2 - Subtração\n3 - Multiplicação\n4 - Divisão\n") option = input('Digite sua opção (1/2/3/4): ') n1 = int(input('\nDigite o primeiro número: ')) n2 = int(input('\nDigite o segundo número: ')) if option == '1': print(f'{n1} + {n2} = {soma(n1, n2)}') elif option == '2': print(f'{n1} - {n2} = {subtracao(n1, n2)}') elif option == '3': print(f'{n1} * {n2} = {multiplicacao(n1, n2)}') elif option == '4': print(f'{n1} / {n2} = {divisao(n1, n2)}') else: print('Opção inválida')
false
ab8e5c4d0b09f1be7824af7996762ed68f1a9f41
damngamerz/python-practice
/practice/regexp.py
666
4.3125
4
#Using Regular Expression in Python import re line = "Cats are smarter than dogs" matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I) if matchObj: print ("matchObj.group() : ", matchObj.group()) print ("matchObj.group(1) : ", matchObj.group(1)) print ("matchObj.group(2) : ", matchObj.group(2)) else: print ("No match!!") #Matching vs Searching matchob=re.match(r'dogs',line,re.M|re.I) if matchob: print("match-->matchob.group():",matchob.group()) else: print("No match Found") searchob=re.search(r'dogs',line,re.M|re.I) if searchob: print("search-->searchob.group():",searchob.group()) else: print("No match found")
false
6dfd06ab46e309218004e0f930e4383be9a3ba63
michaelFavre/cloudio-endpoint-python
/src/cloudio/interface/uuid.py
1,522
4.1875
4
# -*- coding: utf-8 -*- from abc import ABCMeta, abstractmethod class Uuid(object): """Interface to represent an object as a uuid (Universally Unique Identifier). An object implementing the UniqueIdentifiable interface has to return an object implementing the Uuid interface as return value of the method getUuid(). The only mandatory operation such an Uuid has to offer is to allow it to be compared it with other UUIDs for equality. However it is recommended that the standard Object's toString() method return a unique string as well, in order to simplify development and trouble-shooting, but this is not actually required. see UniqueIdentifiable """ __metaclass__ = ABCMeta @abstractmethod def equals(self, other): """Returns true if the UUID is equal to the given one, false otherwise. :param other: The UUID to check equality with. :type other: Uuid :return: True if equal, false otherwise. :rtype: bool """ pass @abstractmethod def toString(self): """Should return a serialisation of the UUID. Note that the serialisation should be unique too! :return: Serialized UUID. :rtype: str """ pass @abstractmethod def isValid(self): """Returns true if the UUID holds a valid UUID or false if the UUID should be considered invalid. :return: True if the UUID is valid, false otherwise. :rtype: bool """ pass
true
458a7bbdc5b147dcb411dc7baa032ac3199e582d
moshekagan/Computational_Thinking_Programming
/frontal_exersices/recitation_solutions_1/ex3.py
273
4.1875
4
distance = float(input("What is the distance from A to B? ")) train_speed = float(input("What is the train speed? ")) time_in_hours = distance / train_speed time_in_minutes = time_in_hours * 60 print("The time from A to B will be: " + str(time_in_minutes) + " minutes.")
false
5860016638f2b63075bcdae494cd83f1e521539e
moshekagan/Computational_Thinking_Programming
/frontal_exersices/recitation_solutions_2/ex2.py
442
4.40625
4
number = int(input("Insert a 3 digits number: ")) first_digit = number // 100 second_digit = number // 10 % 10 third_digit = number % 10 is_middle_greater = second_digit > first_digit and second_digit > third_digit is_middle_smaller = second_digit < first_digit and second_digit < third_digit if is_middle_greater or is_middle_smaller: print(str(number) + " is extreme number.") else: print(str(number) + " is NOT extreme number.")
true
e56caf057b60a5fc5814ca7a03cb3ac6b80b35f5
moshekagan/Computational_Thinking_Programming
/frontal_exersices/recitation_solutions_1/ex6.py
337
4.1875
4
number = int(input("Insert number with 3 digits: ")) first_digit = number // 100 second_digit = (number // 10) % 10 third_digit = number % 10 digits_multiplication = first_digit * second_digit * third_digit digits_sum = first_digit + second_digit + third_digit print(digits_multiplication <= digits_sum and first_digit > third_digit)
false
3e4fe6a7e28055cede6bc54a3874a4438227e3a3
moshekagan/Computational_Thinking_Programming
/homeworks/exersice_solutions_5/Ex5_4_refactor.py
494
4.21875
4
user_input = input("insert: ") number = int(user_input) is_palindrome = True while number // 10 != 0: number_length = 0 temp_number = number while temp_number // 10 != 0: temp_number = temp_number // 10 number_length += 1 last_digit = number % 10 first_digit = number // 10 ** number_length if last_digit != first_digit and first_digit != 0: is_palindrome = False number = number // 10 % 10 ** (number_length - 1) print(is_palindrome)
false
783326ccec31dc7a0ff46c5e4b69806e99aeda57
chrislockard/toyprograms
/CourseraPython/guessnumber.py
2,709
4.25
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import random import math # initialize global variables used in your code range = 100 guesses_made = 0 guesses_remaining = 0 highest_guess = 0 lowest_guess = 0 correct_num = 0 victory_condition = False # define event handlers for control panel def range100(): """Set the range of guessable numbers to [1,100) and restarts""" global range, guesses_made, guesses_remaining, correct_num, victory_condition range = 100 guesses_made = 0 guesses_remaining = 7 #calculate_remaining_guesses(range) correct_num = random.randrange(range) victory_condition = False print "New Game! Guess between 1 and ", range print "Remaining guesses: ", guesses_remaining def range1000(): """Set the range of guessable numbers to [1,1000) and restarts""" global range, guesses_made, guesses_remaining, correct_num, victory_condition range = 1000 guesses_made = 0 guesses_remaining = 10#calculate_remaining_guesses(range) correct_num = random.randrange(range) victory_condition = False print "New Game! Guess between 1 and ", range print "Remaining guesses: ", guesses_remaining # main game logic goes here def get_input(guess): global guesses_made, guesses_remaining, victory_condition guess = int(guess) guesses_remaining -= 1 print "Your guess:" , guess guesses_made += 1 if victory_condition == False: if guess == correct_num: print "Correct!" print "You guessed the number in " , guesses_made , " guesses!" victory_condition = True if guesses_remaining > 0 and victory_condition == False: if guess > correct_num: print "Lower..." print "Remaining guesses:" , guesses_remaining , "\n" else: print "Higher..." print "Remaining guesses:" , guesses_remaining , "\n" elif victory_condition == True: print "You've won! Start a new game." else: print "You've run out of guesses. Game over!" print "The correct number was: " , correct_num else: print "You've won! Start a new game.\n" # create frame frame = simplegui.create_frame("Guess the Number!", 400, 400, 300) # register event handlers for control elements frame.add_button("Range 1..100", range100, 100) frame.add_button("Range 1..1000", range1000, 100) frame.add_input("Enter your guess:", get_input, 100) get_input(0) # start frame frame.start()
true
bea639c7d5f0989b60dcbb827e5dabd9397bcb57
01Eddie/holbertonschool-higher_level_programming
/0x06-python-classes/3-square.py
720
4.625
5
#!/usr/bin/python3 """ define or write class Square""" class Square: """Define the variable or attribute in the principal method""" def __init__(self, size=0): """if type of size if is integer""" if type(size) is not int: """print the error""" raise TypeError("size must be an integer") """if size is number negative""" if size < 0: """print the error""" raise ValueError("size must be >= 0") """The __ define the attribute in private instance""" self.__size = size """Instanced public method for return square area""" def area(self): """Here do the square area""" return self.__size ** 2
true
7a5585a2237bb12dd889604538e86d94e831811f
AlexeiTSV/P1_old
/Module3/homework/m3_t2_hw.py
460
4.25
4
""" Дана последовательность из N чисел. Найти в ней два самых маленьких числа. Последовательность можно сформировать с помощью функции randint() Вариант 1. from random import randint nums = [] for _ in range(10): nums.append(randint(1, 100)) Вариант 2. from random import randint res = [randint(1, 100) for _ in range(10)] """
false
7646debb97f133e988015a558fbaadf8e61f6678
Abhyudaya100/my-projects
/averageusingvarsrgs.py
413
4.40625
4
#program to calculate average of list of values using function def average(arg1, *values): total = arg1 for value in values: total += value return total / (len(values) + 1) def convert(value): return float(value) if value.find(".")!=-1 else int(value) list1 = [convert(element) for element in input("Enter the values:").split()] print("Average(",*list1, ")=", average(*list1))
true
4426d57f4acd4316c14aa28eb40631ffe5aab3e3
calvinhaensel/HuffmanEncoding
/priorityqueue.py
2,968
4.25
4
import linkedlist class PriorityQueue: def __init__(self): self.items = linkedlist.LinkedList() def enqueue(self, item, priority): ''' Enqueues the item, a, on the queue, q; complexity O(1). ''' cursor = self.items crsr = cursor.front crsrnew = crsr crsrnxt = crsr.next #print(cursor.numItems, 'numitems') if cursor.numItems == 1: crsrnxt.priority = crsr.priority #if crsrnxt: # print(crsrnxt.priority) crsr.priority = priority #if crsrnxt: # print(crsrnxt.priority) idx = 0 while cursor is not None: if cursor.numItems == 0: #print('empty') self.items.insert(idx, item, priority) #print(crsr.priority) break elif crsrnxt is None: self.items.insert(idx, item, priority) #print('lastinsert', crsrnew.priority) while crsr: # print(crsr.priority) if crsr.priority == -1000000: crsr.priority = priority crsr = crsr.next break elif crsr.priority >= crsrnxt.priority: # print('priority', crsr.priority, crsrnxt.priority) self.items.insert(idx, item, priority) break else: #print('move') crsrnew = crsrnew.next crsrnxt = crsrnxt.next idx +=1 return self def dequeue(self): ''' Returns the first item enqueued and removes it from queue; complexity O(1). ''' if self.isEmpty(): raise RuntimeError('Attempt to access front of empty queue') item = self.items[0] del self.items[0] return item def isEmpty(self): ''' Returns True if q has not enqueued items; complexity O(1). ''' if len(self.items) != 0: return False else: return True def front(self): # Returns the front item without dequeuing the #item; complexity O(1). if self.isEmpty(): raise RuntimeError('Attempt to access front of empty queue') return self.items[0] def __iter__(self): for item in self.items: yield item def print_queue(pq): for item in pq: print(item, end=' ') print() def main(): q = PriorityQueue() q.enqueue('S', 10) print_queue(q) q.enqueue('t', 2) q.enqueue('T', 9) print_queue(q) q.enqueue('g', 8) print_queue(q) q.enqueue('i', 7) print_queue(q) q.enqueue('n', 6) print_queue(q) q.enqueue('r', 5) q.enqueue('e', 4) q.enqueue('s', 3) print_queue(q) if __name__=="__main__": main()
true
e8ea3f836cfbaff29f01f95610f65cf6310730ee
ParisGharbi/Wave-1
/even or odd.py
286
4.625
5
#Determine and display whether an integer entered by the user is even or odd #Read integer from user num = int(input("Enter an integer: ")) #Determine whether it is even or odd by using the remainder operator if num % 2 == 1: print(num, "is odd.") else: print(num, "is even.")
true
2012c701ecd374474f04345bfd49b248dbd57af5
Rahonam/algorithm-syllabus
/array/duplicate_numbers.py
1,417
4.34375
4
def duplicate_numbers(arr: list): """ Find duplicates in the given array using: iteration, map, time O(n) space O(n) Args: arr: array of integers Returns: array: the duplicate numbers """ number_map = {} duplicate_numbers = [] for i in arr: if i in number_map: if i not in duplicate_numbers: duplicate_numbers.append(i) else: number_map[i] = "" return duplicate_numbers def duplicate_numbers_const_space(arr: list): """ Find duplicates in the given array using: iteration, map, time O(n) space O(1) This solution works only if 1. array has positive integers and 2. all the elements in the array are in range from 0 to n-1, where n is the size of the array. Args: arr: array of integers Returns: array: the duplicate numbers """ number_map = {} duplicate_numbers = [] for i in arr: if arr[i - 1] < 0: if -1 * arr[i - 1] not in duplicate_numbers: duplicate_numbers.append(-1 * arr[i - 1]) else: arr[i - 1] *= -1 return duplicate_numbers print(duplicate_numbers([4, 6, 2, 1, 2, 5])) print(duplicate_numbers([1, 2, 6, 5, 2, 3, 3, 2])) print(duplicate_numbers_const_space([4, 6, 2, 1, 2, 5])) print(duplicate_numbers_const_space([1, 2, 6, 5, 2, 3, 3, 2]))
true
759d066d88dc0c693bfb24ee643a2722656fcd6b
Rahonam/algorithm-syllabus
/array/rearrange_array.py
854
4.34375
4
def rearrange_array(arr:list): """ Rearrange the array such that A[i]=i if A[i] exists, otherwise -1 using: iteration, time O(n) space O(1) Args: arr: array of integers Returns: array: the rearranged array """ for i in range(0, len(arr) - 1): if arr[i] != -1 and arr[i] != i: current_element = arr[i] while arr[current_element] != -1 and arr[current_element] != current_element: arr[current_element], current_element = current_element, arr[current_element] arr[current_element] = current_element if arr[i] != -1: arr[i] = -1 return arr print(rearrange_array([-1, -1, 6, 1, 9, 3, 2, -1, 4, -1])) print(rearrange_array([19, 7, 0, 3, 18, 15, 12, 6, 1, 8, 11, 10, 9, 5, 13, 16, 2, 14, 17, 4]))
true
c45452604287a2e6f68da9734d696b41a58a0491
Rahonam/algorithm-syllabus
/array/count_given_sum_pairs.py
958
4.1875
4
def sum_pairs(arr: list, sum: int): """ Count the number of pairs with a given sum using: iteration, dictionary Args: arr: array of integers sum: target sum of pairs Returns: int: count of possible pairs """ pair_count = 0 count_map = {} for i in arr: if i in count_map: count_map[i] += 1 else: count_map[i] = 1 for key, value in count_map.items(): if (sum - key) in count_map: count1 = value count2 = count_map[sum - key] if count1 == count2 and count1 > 1: pair_count += int(count1 * (count1 - 1) / 2) else: pair_count += count1 * count2 count_map[key] = 0 count_map[sum - key] = 0 return pair_count print(sum_pairs([4, 5, 1, 2, 9, -2, -4],5)) print(sum_pairs([1, 5, 7, 1, -1],6)) print(sum_pairs([3, 3, 3, 3],6))
true
ea164553afee5cc5928fa5eabd2434ca7936ddef
Rahonam/algorithm-syllabus
/array/two_missing_numbers.py
990
4.1875
4
from functools import reduce import math def two_missing_numbers(arr:list): """ Find two missing numbers from unsorted consecutive numbers using: iteration/sum, sum property time O(n) Args: arr: array of unsorted consecutive numbers Returns: array: two missing numbers from given array """ n = max(arr) sum_of_arr = sum(arr) sum_of_n_consecutive_numbers = int(n * (n + 1)/2) product_of_arr = reduce(lambda x,y: x * y, arr) product_of_n_consecutive_numbers = reduce(lambda x,y: x * y, [i for i in range(1, n + 1)]) sum_of_missing_numbers = sum_of_n_consecutive_numbers - sum_of_arr product_of_missing_numbers = product_of_n_consecutive_numbers // product_of_arr d = math.sqrt((sum_of_missing_numbers*sum_of_missing_numbers) - (4*product_of_missing_numbers)) num1 = int(sum_of_missing_numbers + d)//2 return [num1, sum_of_missing_numbers - num1] print(two_missing_numbers([10,2,3,5,7,8,9,1]))
true
9c465c534adac3189d79af4157e35a689cd74971
shirbrosh/Intro-Python-ex10
/asteroid.py
2,159
4.5
4
class Asteroid: TEN = 10 FIVE = 5 def __init__(self, x, y, v_x, v_y, size): """ A constructor for a Asteroid object :param x: A int representing the asteroid's location on the axis x :param y: A int representing the asteroid's location on the axis y :param v_x: A float representing the asteroid's speed on the axis x :param v_y: A float representing the asteroid's speed on the axis y :param size: a int between 1-3 representing the asteroid's size """ self.__x = x self.__y = y self.__v_x = v_x self.__v_y = v_y self.__size = size self.__radius = size*self.TEN-self.FIVE def get_x(self): """A function that returns the x coordinate of this asteroid""" return self.__x def get_y(self): """A function that returns the y coordinate of this asteroid""" return self.__y def get_v_x(self): """A function that returns the speed of the asteroid on the axis x""" return self.__v_x def get_v_y(self): """A function that returns the speed of the asteroid on the axis y""" return self.__v_y def get_size(self): """A function that returns the size of this asteroid""" return self.__size def set_x(self, x): """A function that receives a new x coordinate and sets the x coordinate of the asteroid to the new one""" self.__x = x def set_y(self, y): """A function that receives a new y coordinate and sets the y coordinate of the asteroid to the new one""" self.__y = y def get_radius(self): """A function that returns this asteroid's radius""" return self.__radius def has_intersect(self, obj): """A function that returns True whether an object has intersect with this asteroid and False otherwise""" distance = ((obj.get_x()-self.__x)**2+(obj.get_y()-self.__y)**2)**0.5 if distance <= self.__radius + obj.get_radius(): return True return False
true
d1f3d1d85558e82a98670e52964f390e0e683213
acemodou/dev
/algorithms/bubbleSort.py
621
4.46875
4
""" objective sort the array in increasing order 1. Scan the array and compare A[i] and A[i + 1] 2. If index is out of order we swap 3. Time complexity is O(n^2) since we are comparing everything 4. Space complexity is O(n) """ def swap(a, b): temp = a a = b b = temp def bubbleSort(arr): for i in range(len(arr)): for j in range(0, len(arr) -i- 1): if arr[j] > arr[j+1]: temp = arr[j] arr[j] = arr[j+1] arr[j+1] =temp if __name__ == "__main__": arr = [2, 7, 4, 1, 5, 3] print(arr) bubbleSort(arr) print(arr)
true
11c38bc9dd67fc8148edd675dee31a6eb44c057f
acemodou/dev
/geeksforgeeks/algorithmDataStructure/fibonacci.py
1,008
4.40625
4
"""1 1 2 3 5 8 13 The sum of the previous two values At the end of the nth month, the number of pairs of rabbits is equal to the number of new pairs (which is the number of pairs in month n - 2) plus the number of pairs alive last month (n - 1). This is the nth Fibonacci number. This is the Fibonacci sequence in mathematical terms: """ def fib(n): if n <= 2: return 1 else: return fib(n-2) + fib(n-1) """We can speed up the process by using memoization . Store values for recent function calls so future function calls do not have to repeat the work !!! 1. store values in cache 2. Check if the value is in cache 3. If the number is 1 or 2 return 1 4. If the value is greater than 2 """ cache_value = {} def fibonacci(n): if n in cache_value: return cache_value[n] elif n <=2: value = 1 elif n > 2: value = fibonacci(n-2) + fibonacci(n-1) cache_value[n] = value return value for i in range(1,11): print(i, ":", fibonacci(i))
true
0f5f9dd6cfc082f3d00a4f0457b8cc4413032507
ussherk03/Py
/times_table.py
704
4.625
5
# The multiplication times_table_generator generates a list of the multiples of a particular number, x. # By default, x = 0. def times_table_generator(x=0): a = [] # Null list collects all multiples after being generated by the for-loop n = 0 # Initialises the loop: [n = 0 + x, n = (0 + x) + x, n = (0 + x + x) + x, ...] k = 12 # k simply allows python to loop through the for loop-twelve times to generate twelve multiples: # from 0 - 11 (remember Python is zero-based) for i in range(k): n = n + x a.append(n) return a print(times_table_generator(2)) #You can alter the value of k to increase or decrease the number of multiples.
true
7f688c10b4ac45af3fd1a8f7adb878d106502fa7
lucasffgomes/Python-Intensivo
/seçao_05/exercicio_seçao_05/exercicio_04.py
463
4.21875
4
""" Faça um programa que leia um número e, caso ele seja positivo, calcule e mostre: - O número digitado ao quadrado; - A raiz quadrada do número digitado. """ print() print("Vamos ler um número.") numero = int(input("Digite um número: ")) if numero > 0: expoente = numero ** 2 raiz = int(numero ** (1/2)) print(f"O quadrado do número digitado será {expoente} e sua raiz quadrada será {raiz}.") else: print("Número inválido.")
false
c0be950e830900a8eb29644298415791d178952e
lucasffgomes/Python-Intensivo
/seçao_04/exercicios_seçao_04/exercicio_10.py
367
4.46875
4
""" Leia uma velocidade em Km/h e apresente-a convertida em m/s. A fórmula de conversão é: M = K / 3.6, sendo K a velocidade em Km/h e M em m/s. """ print("Vamos converter de Km/h para m/s!") print() kilometro = float(input("Digite a velocidade em kilômetros: ")) metro = kilometro / 3.6 print(f"Em metros por segundo a velocidade é de {metro} m/s.")
false
100111990268a6cab30a604fbd2fe40c81097db8
lucasffgomes/Python-Intensivo
/seçao_05/exercicio_seçao_05/exercicio_06.py
662
4.125
4
""" Escreva um programa que, dados dois números inteiros, mostre na tela o maior deles, assim como a diferença existente entre ambos. """ print() print("Vamos descobrir a diferença entre dois números inteiros.") numero1 = int(input("Digite o primeiro número: ")) numero2 = int(input("Digite o segundo número: ")) if numero1 > numero2: diferenca = numero1 - numero2 print(f"O maior número será {numero1}, e a diferença entre eles será de {diferenca}.") elif numero2 > numero1: diferenca = numero2 - numero1 print(f"O maior número será {numero2}, e a diferença entre eles será de {diferenca}.") else: print("Números iguais.")
false
98aecfc568566a51a0264d26a6a438274a25e9cb
lucasffgomes/Python-Intensivo
/seçao_06/01_loop_for.py
2,062
4.28125
4
""" Loop for Loop -> Estrutura de repetição. For -> Uma dessas estruturas. C ou Java for(int i = 0; i < 10; i++){ //execução do loop } Python for item in iteravel: //execução do loop Utilizamos loops para iterar sobre sequências ou sobre valores iteráveis Exemplos de iteráveis: - Strings nome = 'Geek University' - Lista lista = [1, 3, 5, 7, 9] - Range numeros = range(1, 10) # Exemplo de for 1 (Iterando em uma String) for letra in nome: print(letra) ----------------------------------------------------------------------------- # Exemplo de for 2 (Iterando sobre uma lista) for numero in lista: print(numero) ----------------------------------------------------------------------------------- # Exemplo de for 3 (Iterando sobre um Range) range(valor_inicial, valor_final) OBS: O valor final não é inclusive. 1 2 3 4 5 6 7 8 9 10 - NÃO! for numero in range(1, 10): print(numero) Enumerate: (0, 'G'), (1, 'e'), (2, 'e'), (3, 'k'), (4, ' '), (5, 'U'), (6, 'n'), (7, 'i'), (8, 'v'), (9, 'r')... for indice, letra in enumerate(nome): print(nome[indice]) for _, letra in enumerate(nome): print(letra) OBS: Quando não precisamos de um valor, podemos descartá-lo utilizando um underline (_) nome = "Geek University" lista = [1, 3, 5, 7, 9] numeros = range(1, 10) # Temos que transformar em uma lista for valor in enumerate(nome): print(valor) -------------------------------------------------------------------------------------------- qtde = int(input("Quantas vezes esse loop deve rodar? ")) soma = 0 for n in range(1, qtde+1): numero = int(input(f"Informe o {n}/{qtde} valor: ")) soma = soma + numero print(f"A soma é {soma}") ------------------------------------------------------------------------------ nome = "Geek University" for letra in nome: print(letra, end='') # Imprimir tudo na mesma linha """ # Original: U+1F60D # Modificado: U0001F60D emoji = 'U0001F60D' for _ in range(2): for numero in range(1, 11): print(f"\U0001F60D" * numero)
false
f179242d2483d78421f6dd09d4220248cb415931
lucasffgomes/Python-Intensivo
/seçao_05/exercicio_seçao_05/exercicio_38.py
1,197
4.3125
4
""" Leia uma data de nascimento de uma pessoa fornecida através de três números inteiros: Dia, Mês e Ano. Teste a validade desta data para saber se está é uma data válida. Teste se o dia fornecido é um dia válido: dia > 0, dia <= 28 para o mês de fevereiro (29 se o ano for bissexto), dia <= 30 em abril, junho, setembro e novembro , dia <= 31 nos outros meses. Teste a validade de mês: mês > 0 e mês < 13. Teste a validade do ano: ano <= ano atual (use uma constante definida com o valor igual a 2008). Imprimir: "data válida" ou "data inválida" no final da execução do programa. """ print() print("Vamos ver se a data é válida.") dia = int(input("Digite o dia: ")) mes = int(input("Digite o mês: ")) ano = int(input("Digite o ano: ")) if 1 <= dia <= 31 and (mes == 1 or mes == 3 or mes == 5 or mes == 7 or mes == 8 or mes == 10 or mes == 12): print("Data válida.") elif 1 <= dia <= 30 and (mes == 4 or mes == 6 or mes == 9 or mes == 11): print("Data válida.") elif mes == 2 and (ano % 4 == 0 and ano % 100 != 0 or ano % 400 == 0): print("Data válida.") elif mes == 2 and (1 <= dia <= 28): print("Data válida.") else: print("Data inválida.")
false
1f5e6b85e868ca906e3f802c62023ace0861a93a
lucasffgomes/Python-Intensivo
/seçao_04/exercicios_seçao_04/exercicio_09.py
394
4.15625
4
""" Leia uma temperatura em graus Celsius e apresente-a convertida em graus Kelvin. A fórmula de conversão é: K = C + 273.15, sendo C a temperatura em Celsius e K a temperatura em Kelvin. """ print("Vamos transformar Celsius em Kelvin!") print("") celsius = float(input("Digite a temperatura em Celsius: ")) kelvin = celsius + 273.15 print(f"A temperatura em Kelvin é {kelvin}.")
false
9c891101bdfe9d69e97ab21cb52bedf5c0fdbd38
lucasffgomes/Python-Intensivo
/seçao_05/exercicio_seçao_05/exercicio_14.py
1,040
4.25
4
""" A nota de um estudante é calculada a partir de três notas atribuídas entre o intervalo de 0 até 10, respectivamente, a um trabalho de laboratório, a uma avaliação semestral e a um exame final. A média das três notas mencionadas anteriormente obedece aos pesos: TRABALHO DE LABORATÓRIO: 2; AVALIAÇÃO SEMESTRAL: 3; EXAME FINAL: 5. De acordo com o resultado, mostre na tela se o aluno está reprovado (média entre 0 e 2,9), de recuperação (entre 3 e 4,9) ou se foi aprovado. Faça todas as verificações necessárias. """ print() print("Vamos descobrir a média de um aluno.") nota1 = float(input("Digite a nota do Trabalho de Laboratório: ")) nota2 = float(input("Digite a nota da Avaliação Semestral: ")) nota3 = float(input("Digite a nota do Exame Final: ")) media_final = ((nota1 * 2) + (nota2 * 3) + (nota3 * 5)) / (2 + 3 + 5) print(media_final) if 0 <= media_final <= 2.9: print("Aluno REPROVADO.") elif 3 <= media_final <= 4.9: print("Aluno de RECUPERAÇÃO.") else: print("Aluno APROVADO.")
false
de0485501843230bdc5590ef6129aa9eb4c7c220
shawnstaggs/Fibonacci-Generator
/Fibonacci Generator/Fibonacci_Generator.py
841
4.375
4
# The generator that produces the fibonacci sequence def genfibon(n): a = 0 # Beginning seed of the sequence b = 1 # First number after the seed for i in range(n): yield a # The output from the generator. is the sum of the previous iteration + the current number a,b = b,a+b # Sets a to the next number in the sequence. Sets b to the sum of a+b prior to the reassignment. # Actual program def main(): while True: input_numbers = int(raw_input('Please enter the quantity of Fibonacci numbers you would like to generate: ')) for num in genfibon(input_numbers): print num continue_run = raw_input('Would you like to generate a different number?').lower() if continue_run <> 'y': break else: continue # Call the actual program main()
true
ecb2066263b021842348c0f8c632c1302ee4bb32
carlosaugus1o/Python-Exercicios
/ex016 - Quebrando um número.py
258
4.125
4
from math import trunc num = float(input('Digite um número real: ')) print('O número digitado é {} e sua porção inteira é {}.'.format(num, trunc(num))) ## o mesmo pode ser feito usando uma função interna da seguinte forma: .format(num, int(num))
false
2e7e1ce6a5bf98cccc4ddd5fc0b7807d92894b8e
wrosko/EXDS
/Week 3/sortingAlgorithms.py
2,482
4.21875
4
''' File: sortingAlgorithms Author: CS 1510 Description: This file gives sample implementations for three sorting algorithms discussed in class: bubble sort, insertion sort, and selection sort. All of these sorting algorithms are big Oh value of n squared ''' # Some lists to play with ordered = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] odd = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39] random = [75, 92, 57, 25, 31, 73, 30, 83, 88, 26, 2, 71, 22, 82, 22, 72, 70, 82, 14, 42] shuffle = [8, 12, 11, 2, 15, 20, 16, 18, 17, 9, 3, 5, 1, 4, 10, 6, 14, 7, 13, 19] doubleshuffle = [20, 22, 10, 32, 1, 4, 5, 14, 23, 13, 3, 31, 19, 7, 18, 40, 33, 25, 36, 35, 9, 11, 37, 6, 12, 38, 34, 26, 15, 21, 28, 8, 27, 17, 30, 24, 16, 29, 39, 2] reverse = [20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] doublereverse = [40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] def bubbleSort(lyst): compare=0 #Number of comparisons made swap=0 #Number of swaps made for aPass in range(len(lyst)): for index in range(len(lyst)-1): compare +=1 if lyst[index]>lyst[index+1]: #Swapping the values at index and index+1 temp = lyst[index] lyst[index] = lyst[index+1] lyst[index+1] = temp swap +=1 #Python also lets you swap this way #lyst[index],lyst[index+1]=lyst[index+1],lyst[index] print ("comparisons "+str(compare)) print ("swaps "+str(swap)) def insertionSort(lyst): compare=0 swap=0 for j in range(1, len(lyst)): key = lyst[j] i = j - 1 compare+=1 while (i >=0) and (lyst[i] > key): lyst[i+1] = lyst[i] i = i - 1 compare+=1 swap+=1 lyst[i+1] = key print ("comparisons "+str(compare)) print ("swaps "+str(swap)) def selectionSort(lyst): compare=0 swap=0 for i in range(0, len(lyst)): min = i for j in range(i + 1, len(lyst)): compare+=1 if lyst[j] < lyst[min]: min = j swap+=1 lyst[i], lyst[min] = lyst[min], lyst[i] # swap print ("comparisons "+str(compare)) print ("swaps "+str(swap))
true
5819d0197de9de3223c959a338c3b1ba5a6f8076
iamrobinhood12345/data-structures
/src/queue_ds.py
1,877
4.25
4
"""This module defines Queue Data Structure. A Queue works based on the FIFO principle which is based in accounting and it describes the method of the first item/person/inventory to enter something to also be the first to leave it. An example would be a line in a bank where the first customer in the line will be the first one served and thus the first to exit the bank.""" from dbl_linked_list import DblLinkedList class Queue(object): """The Queue Data structure is a compoisition of a Double Linked List. Methods: enqueue(val): Add a new node to the end (tail) of the queue. dequeue(): Remove the node at the head of the queue. peek(): Return value at head of queue. size(): Return size of queue. """ def __init__(self, maybe_an_iterable=None): """Initialize Queue as a DblLinkedList-esque object.""" try: self._container = DblLinkedList(maybe_an_iterable[::-1]) except TypeError: self._container = DblLinkedList(maybe_an_iterable) def enqueue(self, value): """Add a new node with given value to the end (tail) of the queue.""" self._container.append(value) def dequeue(self): """Remove the node at the head of the queue and return the value.""" try: return self._container.pop() except IndexError: raise IndexError("Cannot dequeue from empty queue.") def peek(self): """Return the value at the head of the queue. None if empty.""" try: return self._container.head.value except AttributeError: return None def size(self): """Return the size of the queue.""" return self._container._size def __len__(self): """Allow use of len() function.""" return self.size()
true
20582d90f5f78e60fc5aca164ad50c123d296701
greyshell/ds_algorithm
/dynamic_programming/longest_palindrome.py
2,809
4.375
4
#!/usr/bin/env python3 # author: greyshell """ description: Given a string, find the longest substring which is palindrome. For example, if the given string is "forgeeksskeegfor", the output should be "geeksskeeg". reference: https://www.geeksforgeeks.org/longest-palindrome-substring-set-1/ """ def calculate_palindrome(my_string: str, dp_matrix: list, i: int, j: int) -> int: """ :param my_string: :param dp_matrix: :param i: :param j: :return: """ # base case scenarios if i == j: # check for 1 char dp_matrix[i][j] = 1 # consider 1 char is palindrome return 1 if (i + 1) == j: # check for 2 chars if my_string[i] == my_string[j]: dp_matrix[i][j] = 1 # palindrome when both chars are same else: dp_matrix[i][j] = 0 # not palindrome when both chars are not same return dp_matrix[i][j] # top down approach: already calculated cases if dp_matrix[i][j] != -1: return dp_matrix[i][j] # consider all cases where string length > = 3 and not evaluated is_palindrome = calculate_palindrome(my_string, dp_matrix, (i + 1), (j - 1)) # check if the sub_string is palindrome # check if the 1st and the last char is same and sub_string is also palindrome if (my_string[i] == my_string[j]) and is_palindrome: dp_matrix[i][j] = 1 else: dp_matrix[i][j] = 0 return dp_matrix[i][j] def longest_palindrome(my_string: str) -> str: """ time complexity: - O(n^2) -> for the nested loops - calculate_palindrome() -> will be n^2 times as it is inside the nested loops - but due to the memoization matrix after certain call it will give O(1) complexity space complexity: for dp_matrix => O(n^2) stack call => O(1) => constant """ str_len = len(my_string) # initialize a 2d array with -1 w, h = str_len, str_len dp_matrix = [[-1 for y in range(w)] for x in range(h)] # objective is to set 1 if the substring(i, j) is palindrome, else set 0 max_str = "" max_len = -1 for i in range(str_len): for j in range(i, str_len): is_palin = calculate_palindrome(my_string, dp_matrix, i, j) # it returns 1 if # palindrome if is_palin and (j - i + 1) > max_len: # not consider the case 'a' max_len = (j - i) + 1 max_str = my_string[i:j + 1] # returns a new string as python strings are immutable return max_str def main(): # sample test case my_string = "abcbde" my_string = "forgeeksskeegfor" result = longest_palindrome(my_string) print(f"[+] largest palindrome: {result}, length: {len(result)}") if __name__ == '__main__': main()
false
950acf32e9e72977f6f1b771fb2dea9f846c69ff
SofiaSmile/LeetCode
/src/7_ReverseInteger.py
1,008
4.15625
4
""" 7. Reverse Integer Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. """ class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ result = 0 if 0 < x < (2 ** 31) - 1: x = str(x) result = int(x[::-1]) if result >= (2 ** 31) - 1: result = 0 elif 0 > x >= -2 ** 31: x = str(-x) result = -int(x[::-1]) if result < -2 ** 31: result = 0 return result x = 123 x = -123 x = 120 solution = Solution() results = solution.reverse(x) print(results)
true
f57f8a0fb52ceea1a616fe2bc53d0540207a454b
BorisChernigovskiy/GB_HomeWork
/Home_Work/HW01/HW01_Task06.py
1,104
4.15625
4
first_day_result = float(input("Сколько километров Вы пробежали в первый день? ")) planning_result = float(input("Введите целевой показатель в километрах, к которому стремитесь: ")) kilometers = [] days = [] kilometers.append(first_day_result) days.append(1) other_days_counter = 1 while True: if other_days_counter == 1: next_day_result = float(first_day_result + (first_day_result * 0.1)) kilometers.append('{:.2f}'.format(next_day_result)) other_days_counter += 1 days.append(other_days_counter) if next_day_result >= planning_result: break elif other_days_counter > 1: next_day_result = float(next_day_result + (next_day_result * 0.1)) kilometers.append('{:.2f}'.format(next_day_result)) other_days_counter += 1 days.append(other_days_counter) if next_day_result >= planning_result: break print(f"Вы достигли цели на {other_days_counter} день!") print(days, kilometers)
false
ea874d59a2b74ef1c024c9f8cccd1c920f797bfa
Fuerfenf/Basic_things_of_the_Python_language
/python_operators/bitwise_operators.py
1,001
4.40625
4
#-> & # Operator copies a bit to the result if it exists in both operands print(2 & 4) # return 0 (2=0b10, 4=0b100 -> 010 & 100 = 000 (0)) #-> | # It copies a bit if it exists in either operand. print(2 | 4) # return 6 (2=0b10, 4=0b100 -> 010 | 100 = 110 (6)) #-> ~ # It copies the bit if it is set in one operand but not both. print(~3) # return -4 (3=0b11 -> -0b11+1 = -0b100 = -4) print(~4) # return -5 (4=0b100 -> -0b100+1 = -0b101 = -5) #-> ^ # It is unary and has the effect of 'flipping' bits. print(4 ^ 2) # return 6 (2=0b10, 4=0b100 -> 010 ^ 100 = 110 (6)) print(5 ^ 4) # return 1 (2=0b101, 4=0b100 -> 101 ^ 100 = 001 (1)) #-> << # The left operands value is moved left by the number of bits specified by the right operand. print(7 << 2) # return 28 (7=ob0000 0111, move left 2 points = ob0001 1100 (28)) #-> >> # The left operands value is moved right by the number of bits specified by the right operand. print(7 >> 2) # return 1 (7=ob0000 0111, move right 2 points = ob0000 0001 (1))
true
ded5e9702956b2f0cfeba0e631b9b33385af7ecd
Fuerfenf/Basic_things_of_the_Python_language
/oop/encapsulation.py
1,256
4.4375
4
# Protected members -> , just follow the convention by prefixing the name of the member by a single underscore “_” class Base: def __init__(self): # Protected member self._a = 2 # Creating a derived class class Derived(Base): def __init__(self): # Calling constructor of # Base class Base.__init__(self) print("Calling protected member of base class: ") print(self._a) obj1 = Derived() obj2 = Base() print(obj2.a) # Private members # to define a private member prefix the member name with double underscore “__” # Python program to # demonstrate private members # Creating a Base class class Base2: def __init__(self): self.a = "GeeksforGeeks" self.__c = "GeeksforGeeks" # Creating a derived class class Derived2(Base2): def __init__(self): # Calling constructor of # Base class Base.__init__(self) print("Calling private member of base class: ") print(self.__a) # Driver code obj3 = Base2() print(obj3.a) # Uncommenting print(obj1.c) will # raise an AttributeError # Uncommenting obj2 = Derived() will # also raise an AtrributeError as # private member of base class # is called inside derived class
true
158d518da97c26202998ef0344aa32c2e5ddaba6
luizfelipemendes/Phyton-Codes
/funcaoinvert.py
301
4.1875
4
#Imprime inverso# def invert(numero): alg1 = (numero - (numero % 100)) // 100 alg2 = numero % 100 // 10 alg3 = numero % 10 return (alg3*100 + alg2* 10 + alg1) print("Digite um número com 3 algarismos") numero = int(input()) resultado = invert(numero) print(resultado)
false
a7310dae4012063b4fcfc1db01c540fa69df146c
jason-weirather/py-seq-tools
/seqtools/statistics/__init__.py
2,084
4.15625
4
"""This module contains many list-based functions to calculate descriptive statistics.""" from math import sqrt from collections import Counter def mode(arr): """get the most frequent value""" return max(set(arr),key=arr.count) def average(arr): """average of the values, must have more than 0 entries. :param arr: list of numbers :type arr: number[] a number array :return: average :rtype: float """ if len(arr) == 0: sys.stderr.write("ERROR: no content in array to take average\n") sys.exit() if len(arr) == 1: return arr[0] return float(sum(arr))/float(len(arr)) def median(arr): """median of the values, must have more than 0 entries. :param arr: list of numbers :type arr: number[] a number array :return: median :rtype: float """ if len(arr) == 0: sys.stderr.write("ERROR: no content in array to take average\n") sys.exit() if len(arr) == 1: return arr[0] quot = len(arr)/2 rem = len(arr)%2 if rem != 0: return sorted(arr)[quot] return float(sum(sorted(arr)[quot-1:quot+1]))/float(2) def standard_deviation(arr): """standard deviation of the values, must have 2 or more entries. :param arr: list of numbers :type arr: number[] a number array :return: standard deviation :rtype: float """ return sqrt(variance(arr)) def variance(arr): """variance of the values, must have 2 or more entries. :param arr: list of numbers :type arr: number[] a number array :return: variance :rtype: float """ avg = average(arr) return sum([(float(x)-avg)**2 for x in arr])/float(len(arr)-1) def N50(arr): """N50 often used in assessing denovo assembly. :param arr: list of numbers :type arr: number[] a number array :return: N50 :rtype: float """ if len(arr) == 0: sys.stderr.write("ERROR: no content in array to take N50\n") sys.exit() tot = sum(arr) half = float(tot)/float(2) cummulative = 0 for l in sorted(arr): cummulative += l if float(cummulative) > half: return l sys.stderr.write("ERROR: problem finding M50\n") sys.exit()
true
80cb6294c2502d384729234907a5f3890b8b2292
Notesong/Data-Structures
/stack/stack.py
1,477
4.15625
4
""" A stack is a data structure whose primary purpose is to store and return elements in Last In First Out order. 1. Implement the Stack class using an array as the underlying storage structure. Make sure the Stack tests pass. 2. Re-implement the Stack class, this time using the linked list implementation as the underlying storage structure. Make sure the Stack tests pass. 3. What is the difference between using an array vs. a linked list when implementing a Stack? Arrays use indexes to find the head to add or remove an item, whereas a linked list uses the pointers to find it. Arrays also take care of their own lengths so it's not necessary to keep track of them like it is in a stack. """ import sys sys.path.append('../singly_linked_list') from singly_linked_list import SinglyLinkedList class Stack: def __init__(self): self.size = 0 self.storage = SinglyLinkedList() def __len__(self): return self.size def push(self, value): # increase the size of the stack by one self.size += 1 # add an element to the front of the linked list self.storage.add_to_head(value) def pop(self): # check if empty if self.size == 0: return None # decrement the size of the stack by one self.size -= 1 # remove the first element in storage and return the removed head node = self.storage.remove_head() return node
true
197c6da9ae620306ebcc64debe7f8845a17b0888
TomekPk/Python-Crash-Course
/Chapter 7/7.8.Deli/deli.py
731
4.28125
4
''' 7-8. Deli: Make a list called sandwich_orders and fill it with the names of various sandwiches. Then make an empty list called finished_sandwiches. Loop through the list of sandwich orders and print a message for each order, such as I made your tuna sandwich. As each sandwich is made, move it to the list of finished sandwiches. After all the sandwiches have been made, print a message listing each sandwich that was made. ''' sandwich_orders = ["hamburger","vegetarian","with tomatoes and salami"] finished_sandwiches = [] for i in sandwich_orders: print("I made you " + i + " sandwich") finished_sandwiches.append(i) print("\n") for i in finished_sandwiches: print("Sandwich: " + i + " have been made!")
true
75715f01c699c17f4c74e7c5665701c072cd2d6b
TomekPk/Python-Crash-Course
/Chapter 7/7.4.Pizza Toppings/pizza_toppings.py
562
4.1875
4
''' 7-4. Pizza Toppings: Write a loop that prompts the user to enter a series of pizza toppings until they enter a 'quit' value. As they enter each topping, print a message saying you’ll add that topping to their pizza. ''' Question = "\nWhat topping do you want add to your pizza?" Question += "\nPlease write topping or write 'quit' for close: " message = "" while message != "quit": message = input(Question) if message == "quit": print("\nThank you for order. ") else: print("\t"+ message.title() + " - we will add for you.")
true
513234216a77a52c8039281b59652ec77243874f
TomekPk/Python-Crash-Course
/Chapter 6/6.3.Glossary/glossary.py
942
4.53125
5
''' 6-3. Glossary: A Python dictionary can be used to model an actual dictionary. However, to avoid confusion, let’s call it a glossary. • Think of five programming words you’ve learned about in the previous chapters. Use these words as the keys in your glossary, and store their meanings as values. • Print each word and its meaning as neatly formatted output. You might print the word followed by a colon and then its meaning, or print the word on one line and then print its meaning indented on a second line. Use the newline character (\n) to insert a blank line between each word-meaning pair in your output. ''' glossary = { "approach": "podchodzić", "appropriate": "odpowiedni,właściwy", "envolve": "obejmować", "comprehension": "zrozumienie", "particular": "konkretny", "immutable": "niezmienny", } #Sorted glossary by keys for key in sorted(glossary.keys()): print(key +": "+ glossary[key])
true
006f9bc05ab8e04c7806b5c38e416a9277abcfbf
TomekPk/Python-Crash-Course
/Chapter 7/7.2.Restaurant Seating/restaurant_seating.py
475
4.5
4
''' 7-2. Restaurant Seating: Write a program that asks the user how many people are in their dinner group. If the answer is more than eight, print a message saying they’ll have to wait for a table. Otherwise, report that their table is ready. ''' Question = input("Hello. Welcome in our restaurant. How many people are in your dinner group? ") if int(Question) > 8: print("\nSorry but you will have to wait for a table.") else: print("\nYours table is ready.")
true
aef7ac0ea6992cef72ddbc904b0f9ef7bd974ee8
TomekPk/Python-Crash-Course
/Chapter 4/4.8.Cubes/cubes.py
563
4.65625
5
''' 4-8. Cubes: A number raised to the third power is called a cube. For example, the cube of 2 is written as 2**3 in Python. Make a list of the first 10 cubes (that is, the cube of each integer from 1 through 10), and use a for loop to print out the value of each cube. ''' numbers_list=list(range(1,11)) print(numbers_list) for cube in numbers_list: print(cube**3) # with append(): print("\nSolution with append (): ") cube_numbers= [] numbers=list(range(1,11)) for cube in numbers: cube_numbers.append(cube**3) for i in cube_numbers: print(i)
true
80e88bc6cf202201e1c6800073b17bcb1e13bb84
TomekPk/Python-Crash-Course
/Chapter 4/4.10.Slices/slices.py
950
5
5
''' 4-10. Slices: Using one of the programs you wrote in this chapter, add several lines to the end of the program that do the following: 1)• Print the message, The first three items in the list are:. Then use a slice to print the first three items from that program’s list. 2)• Print the message, Three items from the middle of the list are:. Use a slice to print three items from the middle of the list. 3)• Print the message, The last three items in the list are:. Use a slice to print the last three items in the list. ''' cube_list = [value**3 for value in range(1,11)] print(cube_list) print("\nMy list: ") my_list = [value*15 for value in range(1,15)] print(my_list) # 1) print("\n1)") print("The first three items in the cube_list are:", cube_list[:3]) # 2) print("\n1)") print("Three items from the middle in the cube_list are:", cube_list[3:6]) # 3) print("\n1)") print("Last three items in the cube_list are:", cube_list[-3:])
true
cd2ee8b63cde2545b7848e58b320c06fea840776
TomekPk/Python-Crash-Course
/Chapter 7/7.10.Dream Vacation/dream_vacation.py
757
4.28125
4
''' 7-10. Dream Vacation: Write a program that polls users about their dream vacation. Write a prompt similar to If you could visit one place in the world, where would you go? Include a block of code that prints the results of the poll. ''' question = "If you could visit one place in the world, where would you go?" question +="\nPlease enter answer: " answer_list = [] while True: answer = input(question) print("Your answer is: " + answer) answer_list.append(answer) repeat = input("\nWould You like to make another poll? (yes/no): ") if repeat.lower() == "no": break elif repeat.lower() == "yes": continue print("\nPoll end. You can see Your answers below: ") for i in answer_list: print("\t" + i)
true
3fa9a4e81c80bda5d1d50017a89a7f3c6c4a91c0
TomekPk/Python-Crash-Course
/Chapter 10/10.8.Cats and Dogs/cats_and_dogs.py
1,921
4.34375
4
''' 10-8. Cats and Dogs: Make two files, cats.txt and dogs.txt. Store at least three names of cats in the first file and three names of dogs in the second file. Write a program that tries to read these files and print the contents of the file to the screen. Wrap your code in a try-except block to catch the FileNotFound error, and print a friendly message if a file is missing. Move one of the files to a different location on your system, and make sure the code in the except block executes properly. ''' cats_file = "cats.txt" dogs_file = "dogs.txt" # create file cats_file if cats_file == "": with open(cats_file, "w") as store_1: store_1.close() # create file dogs_file if dogs_file != "": with open(dogs_file, "w")as store_2: store_2.close() class Cat(): """ create a cat """ def __init__(self, cat_name): self.cat_name = cat_name print("You create cat name: " + self.cat_name) def store_in_file(self): """ add cat name to cats.txt """ with open(cats_file, "a") as store: store.writelines(self.cat_name + "\n") print("You store " + self.cat_name + " in " + cats_file) class Dog(): def __init__(self, dog_name): """ create a dog """ self.dog_name = dog_name print("\nYou create cat name: " + self.dog_name) def store_in_file(self): """ add dog name to dogs.txt """ with open(dogs_file, "a") as store: store.writelines(self.dog_name + "\n") print("\tYou store " + self.dog_name + " in " + dogs_file) # create cat: animal1 = Cat("Maja") # store cat in a file animal1.store_in_file() animal2 = Cat("Johnson") animal2.store_in_file() animal3 = Cat("Bety") animal3.store_in_file() # create dog dog1 = Dog("HauHau") #store dog in a file dog1.store_in_file() dog2 = Dog("Bronix") dog2.store_in_file() dog3 = Dog("Ron") dog3.store_in_file()
true
f741c0b9bb52fb597b2372f66ce9cf178b17aa97
TomekPk/Python-Crash-Course
/Chapter 10/10.1.Learning Python/learning_python.py
1,421
4.9375
5
''' 10-1. Learning Python: Open a blank file in your text editor and write a few lines summarizing what you’ve learned about Python so far. Start each line with the phrase In Python you can.... Save the file as learning_python.txt in the same directory as your exercises from this chapter. Write a program that reads the file and prints what you wrote three times. Print the contents once by reading in the entire file, once by looping over the file object, and once by storing the lines in a list and then working with them outside the with block. ''' my_text = "learning_python.txt" ############################################ # print by reading entire file ''' with open(my_text) as text_object: content = text_object.read() print(content) print(content) print(content) ''' ############################################ # print by looping over the file object ''' with open(my_text) as text_object: for i in text_object: print(i.strip()) ''' ############################################ # print by by storing the lines in a list and then working with them outside the with block. with open(my_text) as text_object: lines = text_object.readlines() list_lines = [] for line in lines: list_lines.append(line.strip()) # print new list made from lines print(list_lines) # print items from list for item in list_lines: print(item) ############################################
true
4e3dc30d2a53f5156fc62f51583820dfdf5aa30c
TomekPk/Python-Crash-Course
/Chapter 10/10.3.Guest/guest.py
615
4.34375
4
''' 10-3. Guest: Write a program that prompts the user for their name. When they respond, write their name to a file called guest.txt. ''' my_text = "guest.txt" name_message = input("Hello. Please enter Your name below: \n") class User(): def __init__(self,name_message): self.name_message = name_message def add_user_to_txt(self): with open(my_text, "a") as guest_list: guest_list.write(self.name_message + "\n") def clear_guest_list(self): with open(my_text, "w"): pass user1 = User(name_message) user1.add_user_to_txt() user1.clear_guest_list()
true
2c5028ab14a4c1146dd66e83569ddc22daedc3ac
jeanwisotscki/Python-Mundo-3
/ex088.py
918
4.28125
4
''' Exercício Python 088: Faça um programa que ajude um jogador da MEGA SENA a criar palpites. O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta. ''' # Bibliotecas from random import sample from time import sleep # Variáveis e Listas resultados = [] # Cabeçalho print('---'*15) print('{:^45}'.format('>>> JOGAR NA MEGA SENA <<<')) print('---'*15) jogos = int(input('{:^45}'.format('Digite quantos jogos quer sortear: '))) print('---'*15) print('{:^45}'.format(f'>>> SORTEANDO {jogos} JOGOS <<< ')) print('---'*15) sleep(1) # Solução for c in range(jogos): r = sorted(sample(range(0, 61), 6)) resultados.append(r[:]) print('{:<45}'.format(f'Jogo {c+1}: {r}')) sleep(0.5) print('{:^45}'.format(' === BOA SORTE ===')) print('---'*15)
false
ad19766f674dcb106442848aa15fa99a5bd7c7e8
jeanwisotscki/Python-Mundo-3
/ex087.py
1,197
4.15625
4
''' Exercício Python 087: Aprimore o desafio anterior, mostrando no final: A) A soma de todos os valores pares digitados. B) A soma dos valores da terceira coluna. C) O maior valor da segunda linha. ''' # Listas matriz = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] # Variáveis s_pares = s_coluna = maior = 0 # Solução for linha in range(3): for coluna in range(3): matriz[linha][coluna] = int(input(f'Digite um valor para a posição [{linha}, {coluna}]: ')) print('-=-'*13) for linha in range(3): for coluna in range(3): print(f' [{matriz[linha][coluna]:^5}]', end='') if matriz[linha][coluna] % 2 == 0: s_pares += matriz[linha][coluna] print() print('-=-'*13) print(f'A soma dos valores pares é: \033[34m{s_pares}\033[m') for linha in range(3): s_coluna += matriz[linha][2] print(f'A soma dos valores da terceira coluna é: \033[34m{s_coluna}\033[m') for coluna in range(3): if coluna == 0: maior = matriz[1][coluna] elif matriz[1][coluna] > maior: maior = matriz[1][coluna] print(f'O maior valor da segunda linha é: \033[34m{maior}\033[m')
false
bb76b426866c955898a8dcea674826dec1a12831
hasmevask/Python
/Python/Day5/calculator.py
322
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Author:zpp import re def adder_subtractor(x,y): return x + y def multiply_divide(x,y): return x * y def bracket(s): pass def main(): operation = input("Please input operation:").strip() num = re.search("\(+.+\)","(((1 + 3) * (5 - 2)) * 4)/5") print(num) main()
false
b4ebd5389f9b0193e83536ac499a2a1de6af0e90
shalinrox123/Spring-2021-Masters-Project
/top_sort.py
2,577
4.125
4
# This code is contributed by Neelam Yadav # Python program to print topological sorting of a DAG from collections import defaultdict # topolicical sort was implimented from from https://www.geeksforgeeks.org/topological-sorting/ # start of Neelam Yadev's code #Class to represent a graph class Graph: def __init__(self,vertices): self.graph = defaultdict(list) #dictionary containing adjacency List self.V = vertices #No. of vertices # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # A recursive function used by topologicalSort def topologicalSortUtil(self,v,visited,stack): # Mark the current node as visited. visited[v] = True # Recur for all the vertices adjacent to this vertex for i in self.graph[v]: if visited[i] == False: self.topologicalSortUtil(i,visited,stack) # Push current vertex to stack which stores result stack.insert(0,v) # The function to do Topological Sort. It uses recursive # topologicalSortUtil() def topologicalSort(self): # Mark all the vertices as not visited visited = [False]*self.V stack =[] # Call the recursive helper function to store Topological # Sort starting from all vertices one by one for i in range(self.V): if visited[i] == False: self.topologicalSortUtil(i,visited,stack) # Print contents of stack print(stack) # end of Neelam Yadev's code class DAG: def makeEdges(self, dagList): DAG = []#dag list #takes in a list and cleans the input before giving it to the topsort splitList = dagList.replace('[','').replace(']','').replace('(','').replace(')','').split(',') for edge in splitList: if edge[0] == ' ': edge = edge[1:] if edge[len(edge)-1] == ' ': edge = edge[:len(edge)-1] edge = edge.split(' ') DAG.append(edge) #print(edge) return DAG #print(DAG, len(DAG)) def getTopSort(self, DAG): DAG_L = len(DAG) g = Graph(DAG_L) for edge in DAG: g.addEdge(edge[0],edge[1]) print("Following is a Topological Sort of the given graph") g.topologicalSort() # this is the given input, spaces between the numbers are required dag1 = "[ (5 2), (5 0) , (4 0) , (4 1) , (2 3) , (3 1) ]" # this creates a DAG object DAG_OBJ = DAG() # this will take in the string and split it accordingly for the # resulting list to contain an edge which is also a list DAG_LIST = DAG_OBJ.makeEdges(dag1) # with the given edges, the function returns a topologically sorted list DAG_OBJ.getTopSort(DAG_LIST)
true
da0d510cece1ed2017edfcccf1b7343a3709a033
ytatus94/Leetcode
/python3/021_Merge_Two_Sorted_Lists.py
1,875
4.3125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ curr = ListNode(0) root = curr while l1 and l2: if l1.val < l2.val: curr.next = l1 l1 = l1.next else: curr.next = l2 l2 = l2.next curr = curr.next # 離開 while 迴圈時,表示其中一個 linked list 已經跑完了 ==> l? = None # 這時候只需要接上另一個 linked list 剩下的部分 curr.next = l1 or l2 return root.next # 傳回列表的頭 # lintcode 165 """ Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param l1: ListNode l1 is the head of the linked list @param l2: ListNode l2 is the head of the linked list @return: ListNode head of linked list """ def mergeTwoLists(self, l1, l2): # write your code here if l1 is None and l2 is None: return None if l1 is None: return l2 if l2 is None: return l1 dummy = ListNode(0) prev = dummy while l1 and l2: if l1.val < l2.val: prev.next = l1 prev = prev.next l1 = l1.next else: prev.next = l2 prev = prev.next l2 = l2.next if l1 is None: prev.next = l2 else: prev.next = l1 return dummy.next
false
e47309f2fe6a9e315bb03880c3457cd040eddba1
ytatus94/Leetcode
/python3/086_Partition_List.py
2,077
4.15625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def partition(self, head, x): """ :type head: ListNode :type x: int :rtype: ListNode """ ''' 要把 linked list 分成兩組 一組放比 x 小的,另一組放比 x 大的 然後再把兩組接起來 ''' dummy1 = ListNode(0) dummy2 = ListNode(0) prev1 = dummy1 prev2 = dummy2 while head: if head.val < x: prev1.next = head prev1 = head else: prev2.next = head prev2 = head head = head.next # 跑完後 prev1 指向比 x 小的 linked list 的最後一個元素 # prev2 指向比 x 大的 linked list 的最後一個元素 # 所以接起來時 prev1 的下一個是第二個 linked list 的第一個元素 # 還有要注意 prev2 要接上 None prev2.next = None prev1.next = dummy2.next return dummy1.next # lintcode 96 """ Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: The first node of linked list @param x: An integer @return: A ListNode """ def partition(self, head, x): # write your code here if head is None: return head dummy1 = ListNode(0) # < x dummy2 = ListNode(0) # >= x prev1 = dummy1 prev2 = dummy2 curr = head while curr: if curr.val < x: prev1.next = curr prev1 = curr else: prev2.next = curr prev2 = curr curr = curr.next prev1.next = dummy2.next prev2.next = None return dummy1.next
false
a6ff116dc6a33a54ada0664d0d6e06e151636ff5
ytatus94/Leetcode
/python3/143_Reorder_List.py
2,686
4.15625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reorderList(self, head: 'ListNode') -> 'None': """ Do not return anything, modify head in-place instead. """ # 把每個節點塞入 stack 裡面 stack = [] while head: stack.append(head) head = head.next if len(stack) == 0: return head # 把正確的順序放到 reorder 中 reorder = [] while len(stack) > 0: reorder.append(stack.pop(0)) if len(stack) > 0: reorder.append(stack.pop()) # 做成 linked list for i in range(len(reorder) - 1): reorder[i].next = reorder[i+1] # 記得要把最後一個的下一個指向空 reorder[-1].next = None # lintcode 99 """ Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: The head of linked list. @return: nothing """ def reorderList(self, head): # write your code here if head is None: return head mid = self.finde_middle_node(head) # tail 是反轉 linked list 後半段之後的起點 # 也是原本的 linked list 的終點 tail = self.reverse_linked_list(mid.next) # 得到前半段與反轉後的後半段兩個 linked list mid.next = None # 把兩段交叉合併起來 self.merge(head, tail) # 用快慢指針找 linked list 的中點, # 當離開 while 迴圈的時候 slow 就停在中點上 def finde_middle_node(self, head): fast = head slow = head while fast.next and fast.next.next: fast = fast.next.next slow = slow.next return slow # 反轉 linked list def reverse_linked_list(self, head): prev = None while head: temp = head.next head.next = prev prev = head head = temp return prev def merge(self, head1, head2): dummy = ListNode(0) while head1 is not None and head2 is not None: dummy.next = head1 dummy = dummy.next head1 = head1.next dummy.next = head2 dummy = dummy.next head2 = head2.next if head1: dummy.next = head1 if head2: dummy.next = head2
false
54f12930cd86ef6f94123a70fe2df240ce069f0a
monaug5/Data-Science-Coursework-Aaron-Adeniran
/import Task 1.py
209
4.125
4
import random #Gathers the users name and asks the question "What is your name?" user_input = input("What is your name? ") number=random.randint(1,10) print(user_input, "Guess the number between 1 and 10")
true
cd145a5f7d57cc4ee9e039696bf126b4a413c530
deshunin/binder
/week 9-10/fibonacci.py
1,513
4.21875
4
# fibonacci numbers and memoization # standart regursion form (for n = 34 it takes 1.6 sec) def fibonacci(n): if n <= 2: return 1 return fibonacci(n-2) + fibonacci(n-1) # fastest so far mine form using list operations (for n = 34 it takes 43 microsec) def fib(n): fib_lst = [0,1] for k in range(2, n+1): f = fib_lst[k-2] + fib_lst[k-1] fib_lst.append(f) return fib_lst[n] # a litle slower then previous form using numpy operations (for n = 34 it takes 106 microsec) import numpy as np def fibon(n): fibon_arr = np.zeros(n+1, int) fibon_arr[0] = 0 fibon_arr[1] = 1 for k in range(2, n+1): fibon_arr[k] = fibon_arr[k-2] + fibon_arr[k-1] return fibon_arr[n] # the slowest way from MIT open course 6.006 Lecture 19 to demonstrate memoization technique # in spite of the instructor's claim it takes 2.5 times slower that the first standart recursion # (for n = 34 it takes 4 sec) memo = [] def fib_memo(n): if len(memo) == n + 1: return memo[n] if n <= 2: f = 1 else: f = fib_memo(n-2) + fib_memo(n-1) memo.append(f) return f # the fast way to calculate fibonacci number using dictionary and memoization technique # (for n = 34 it takes 30 microsec). coorect implementation of the algorithm from 6.006 Lecture 19 fib_dict = {} def fibb(n): if n in fib_dict: return fib_dict[n] if n <= 2: f = 1 else: f = fibb(n-2) + fibb(n-1) fib_dict[n] = f return f
true
f684e9b9c718f255083759e2cb638d96db623c3e
praveenchs/LPTHW
/ex18.py
1,181
4.5625
5
#First we tell Python we want to make a function using def for ”define”. #On the same line as def we give the function a name called "print_two" #Then we tell it we want *args (asterisk args), which is a lot like your argv parameter but for #functions. This has to go inside () parentheses to work. def print_two(*args): #After the colon all the lines that are indented four spaces will become attached to this name, #print_two. Our first indented line is one that unpacks the arguments, the same as with your #scripts. args1,args2 = args #To demonstrate how it works we print these arguments out, just like we would in a script. print(f"arg1: {args1}, \narg2: {args2}") print_two("praveen","chalamalasetti") def print_two_again(arg1,arg2): print(f"arg1: {arg1}, \narg2: {arg2}") print_two_again("praveen_again","chalamalasetti_again") # def is syntax for creating a function (def = define), followed by function name . #ex: def def_name ==> def_name is the name of the function. def print_one(arg): print(f"Here is the new arg :{arg}") print_one("one_arg") # this one takes no arguments def print_none(): print(f"There is no argument to print") print_none()
true
d9deca92fd1d626938f077f93e617fb821c71996
IsaacLSK/python_simple_algo
/sorting/bulit_in_sort.py
589
4.15625
4
def built_in_sort(): # using the function sorted # the function returns the sorted list listA = [10, 5, 2, 8, 3, 4, 9, 1] newlist = sorted(listA) print(newlist) # using the function sorted # the function returns the sorted list listA = [10, 5, 2, 8, 3, 4, 9, 1] newlist = sorted(listA, reverse=True) print(newlist) # using the sort() method of list object directly # NOTE: the method directly sorts the list object listA = [10, 5, 2, 8, 3, 4, 9, 1] listA.sort() print(listA) if __name__ == "__main__": built_in_sort()
true