blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
1d5e16f1fb41e690b1544362792783ff5124e772
balassit/improved-potato
/microsoft/Day-of-Week.py
392
4.21875
4
""" Days of the week are represented as 3 letter strings Given S, representing day of week, and integer K, between 0-500, return day of the week that is K days later """ def dayOfWeek(s, k): days = {"Mon": 0, "Tue": 1, "Wed": 2, "Thu": 3, "Fri": 4, "Sat": 5, "Sun": 6} integers = {y: x for x, y in days.items()} return days[(integers[s] + k) % 7] print(dayOfWeek("Sat", 23))
true
305bd29e78f502c3529402592e642bcd08946a79
balassit/improved-potato
/sorting-algorithms/selectionSort.py
689
4.21875
4
""" @param items - list of ints @return sorted list of items """ def selection_sort(items: list): for index in range(len(items)): min_idx = index for j in range(index + 1, len(items)): if items[min_idx] > items[j]: min_idx = j # Swap the found minimum element with # the first element items[index], items[min_idx] = items[min_idx], items[index] return items """ Sort a given list and print before and after. Assume list is integers """ if __name__ == "__main__": items: list = [54, 26, 93, 17] print(f"before sorting: {items}") items = selection_sort(items) print(f"after sorting: {items}")
true
11486d9e82b25f806067f8b6269718ca08f5f24f
lqueryvg/dotfiles
/bin/common_letters.py
1,053
4.25
4
#!/usr/bin/env python3 import argparse import collections parser = argparse.ArgumentParser(description=''' Reads list of strings from a file, one per line, and prints a list of characters that are common to all strings. Repeat characters are not condensed, so for example the two strings "abbccc", "abcczz" would have and "abcc" in common. ''') parser.add_argument('filename', nargs=1) args = parser.parse_args() try: file_obj = open(*args.filename) except IOError: print("failed to open file '" + args.filename[0] + "'") exit(-1) def commonLetters(strings): first = strings.pop(0) result = collections.Counter(first) for str in strings: # intersection result = result & collections.Counter(str) strings.insert(0, first) # put first element back return result.elements() strings = file_obj.read().splitlines() print("The following letters are common in all lines of the file:") print("<" + "".join(sorted(commonLetters(strings))) + ">") exit(0)
true
762c9aff9d219d372849808648f8bf7c451fa5ea
william1357chen/Sorting-Algorithms
/Quick-Sort/quick_sort.py
1,372
4.25
4
""" This is the implementation of Quick Sort on an array of integers. The function sorts an input list of integers by mutating it. """ import random def quick_sort(array, low, high): if low >= high: return p_index = random_partition(array, low, high) quick_sort(array, low, p_index - 1) quick_sort(array, p_index + 1, high) # find a random value in array as pivot to maintain average case O(nlogn) def random_partition(array, low, high): p_index = random.randint(low, high) array[high], array[p_index] = array[p_index], array[high] return right_pivot_partition(array, low, high) # choose the element at the low position as the pivot def left_pivot_partition(array, low, high): pivot = array[low] p_index = high for i in range(high, low, -1): if array[i] > pivot: array[i], array[p_index] = array[p_index] = array[i] p_index -= 1 array[high], array[p_index] = array[p_index] = array[high] return p_index # choose the element at the high position as the pivot def right_pivot_partition(array, low, high): pivot = array[high] p_index = low for i in range(low, high): if array[i] <= pivot: array[i], array[p_index] = array[p_index], array[i] p_index += 1 array[high], array[p_index] = array[p_index], array[high] return p_index
true
b75673190a339fbab17d4e3396e4d344bbd6e7f2
lwiecek/advent-of-code
/day02.py
2,218
4.21875
4
#!/usr/bin/env python3 ### # Day 2 - adventofcode.com # Lukasz Wiecek 2015-2016 ### def dimensions(s): return sorted(int(d) for d in s.split('x')) def part_one(lines): ''' The elves are running low on wrapping paper, and so they need to submit an order for more. They have a list of the dimensions (length l, width w, and height h) of each present, and only want to order exactly as much as they need. Fortunately, every present is a box (a perfect right rectangular prism), which makes calculating the required wrapping paper for each gift a little easier: find the surface area of the box, which is 2*l*w + 2*w*h + 2*h*l. The elves also need a little extra paper for each present: the area of the smallest side. All numbers in the elves' list are in feet. How many total square feet of wrapping paper should they order? ''' paper = 0 for line in lines: l, w, h = dimensions(line) paper += (3 * l * w) + (2 * w * h) + (2 * l * h) return paper def part_two(lines): ''' The elves are also running low on ribbon. Ribbon is all the same width, so they only have to worry about the length they need to order, which they would again like to be exact. The ribbon required to wrap a present is the shortest distance around its sides, or the smallest perimeter of any one face. Each present also requires a bow made out of ribbon as well; the feet of ribbon required for the perfect bow is equal to the cubic feet of volume of the present. Don't ask how they tie the bow, though; they'll never tell. How many total feet of ribbon should they order? ''' ribbon = 0 for line in lines: l, w, h = dimensions(line) ribbon += 2 * (l + w) + (l * w * h) return ribbon def main(): assert part_one(['2x3x4']) == 58 assert part_one(['1x1x10']) == 43 assert part_two(['2x3x4']) == 34 assert part_two(['1x1x10']) == 14 with open('input/day02.txt') as f: lines_strip = (line.strip() for line in f) lines = [line for line in lines_strip if line] print(part_one(lines)) print(part_two(lines)) if __name__ == '__main__': main()
true
6ec43ff02d4ac0f8d3a7333674a6d2032885c416
NikhilPrakashrao/PythonProgramming
/CalculateBMI.py
475
4.28125
4
"""SCOPE: 1:Get the input from user 2:use the input to calculate the Body Mass Index """ height=input("Enter the height in Meters\n") weight=input("Enter the weight in kilograms\n") height=float(height) weight=int(weight) bmi=(weight/(height*height)) print(bmi) if(bmi<16): print("The person is underweight") elif(bmi>16 and bmi<25): print("The person is normal") elif(bmi>25 and bmi<40): print("The person is overweight") else: print("The person is obese")
true
e9fa83982d088e1e8b23ae7dc4d6016d3d60e162
tpjh461/password.py
/密碼重試程式.py
933
4.21875
4
#密碼重試程式 #先在程式碼中 設定好密碼 password= 'a123456' #讓使用者重複輸入密碼 #讓使用者【最多輸入3次密碼】 #如果正確 就印出【登入成功!】 #如果不正確,就印出【密碼錯誤!還有_次機會】 #不想要印出 【還有0次機會】 也不用 while True password= 'a123456' i = 3 #剩餘機會 while i > 0: i = i - 1 pwd = input('請輸入密碼:') #不可以存成 password 會覆蓋掉第一行的 password if pwd == password: #很多人會寫成 == 'a123456' 是對的 可是不好 因為如果改數值的話 就要改很多地方 print('登入成功') break #逃出迴圈 else: print('密碼錯誤!') #分割成3塊 i 是變數 if i > 0: print('還有',i ,'幾次機會') #不想要印出 【還有0次機會】 else: print('已沒機會嘗試')
false
31563367017ac4f9d222946b8ffc5f66915800d6
Laura-Neff/Pacman_AI
/listFun.py
235
4.125
4
countries = ["Iran", "United States of America", "Australia", "China", "Burma", "India", "Peru", "United Arab Emirates"] #Lists use brackets lowerList = [country.lower() for country in countries if len(country) > 5]; print(lowerList)
true
7a04f5734b0b74c2e92239fa775fcd37df647ee2
Mahfuz60/Python-programming-code
/C related program/program10.py
221
4.15625
4
#inner /nested if else statement num1=50 num2=40 num3=45 if num1>num2 : if num1>num3: print(num1) else: print(num3) if num2>num1: if num2>num3: print(num2) else: print(num3)
false
861ea8b8b58dd5b3eb7f9393fd22e13739e8933e
Kodhandarama/Rail-Fence-Cipher
/rail_decrypt.py
1,927
4.21875
4
def RailFenceDecrypt(cipher, key): """create the matrix to cipher""" # no of rows = plain text key # no of columns = length(cipher) # filling the rail matrix to distinguish filled spaces #from blank ones rail = [['\n' for i in range(len(cipher))] for j in range(key)] # To find the vertical direction in #which to decrypt the cipher vertical_direction = None row, col = 0, 0 # mark the places with '*' for i in range(len(cipher)): if row == 0: vertical_direction = True if row == key - 1: vertical_direction = False # place the marker because this is a marked space rail[row][col] = '*' col += 1 # find the next row using direction flag if vertical_direction: row += 1 else: row -= 1 """ Now we can construct the rail matrix based on the marked spaces""" index = 0 for i in range(key): for j in range(len(cipher)): if ((rail[i][j] == '*') and (index < len(cipher))): rail[i][j] = cipher[index] index += 1 """ Now, the marked spaces are read to give the decrypted text """ decrypted_text = [] row, col = 0, 0 for i in range(len(cipher)): # check the direction of flow if row == 0: vertical_direction = True if row == key-1: vertical_direction = False # place the marker if (rail[row][col] != '*'): decrypted_text.append(rail[row][col]) col += 1 # find the next row using # direction flag if vertical_direction: row += 1 else: row -= 1 return("".join(decrypted_text))
true
4d88debdc1c31431759770b23e43dca329d23e6c
chauhan0707/Coding
/BMI Calculator.py
867
4.4375
4
print(' BMI CALCULATOR') name = input('What is your name?') weight = float(input('What is your weight (in Kgs)?')) height = float(input('What is your height (in meters)?')) bmi = weight / (height ** 2) if bmi<18.5: print(f"\n{name} is underweight by {bmi} BMI") print('Eat foods containing high portion of fats and carbohydrates') elif 18.5<bmi<24.9: print(f"\n{name} has normal weight by {bmi} BMI") print('You are living a healthy life and !!!KEEP IT UP!!!') elif 25.0<bmi<29.9: print(f"\n{name} is overweight by {bmi} BMI") print('\nEat foods containing less amount of fats and carbohydrates and do regular exercise.') else:print(f"\n{name} is obese by {bmi} BMI.\nRegular exercise is very important for you & consult a dietician to plan your diet.") print('\n |||||||||| THANK YOU ||||||||||')
true
ab7f6d6574d2b3eaad5bfcd8a2f3daa9c4f9b04e
ChHarding/python_ex_2
/ex_2_task_2.py
2,112
4.28125
4
# Python refresher exercises 2 - task 2 # - as part of some app, the user has to create a valid email address # - any address will do as long as it's valid # - your validation will only allow a number of retries if a invalid email is given (default 3) # - once the number of attempts is exhausted (you should show how many retries are left!), set the # variable (flag) gave_up to True and bail out. # # - it's OK to start with my solution from the lecture in flow control, although I # encourage you to try you own solution first (if you can't remember). Any other, working # solution is fine, too! # - when it comes to how to react to an error, your user MUST re-enter a string, but it's up to # you how helpful you want to be: # - you could just list all the rules on error and demand a new input # - you could list the appropriate error message returned from you function and demand a new input # - you could do something fancy and only require re-typing of what's wrong (if that's technically possible): # e.g. if the pre @ is wrong (too long, contains a invalid char) you could demand that # only that incorrect part is re-entered. Warning - this can be complicated and laborious to test! # - Note that the check for a valid email is a bit weird (b/c of how I set it up): # - iff the first return is None (r == None), the email is valid (yes, None doesn't sound like an OK ...) # - if you didn't get None (r != None), then r contains an error code, which you could use in your # flow control for branching, if you want to do something fancy # Once you're solved this, run some tests to show me that it works. # Again, manually copy/paste the console output in a text file (results2.txt) # import your function from the previous .py file as a module (you can abbreviate it) # use ex_2_task_2 here instead once your function works! from ex_2_task_1_solution import is_valid_email_address as is_valid gave_up = False attempts_left = 3 # your code - start # your code - end if not gave_up: print("valid email", email) else: print("invalid email", email)
true
f0e695f40d551af7e28d1082544e8dd41f53fbd9
btv/project_euler
/problem_7/python/problem7.py
417
4.15625
4
#!/usr/bin/python import math def is_prime(divided): divisor = 3 sqrt_divided = math.sqrt(divided) while divisor <= sqrt_divided: if divided % divisor == 0: return False divisor += 2 return True if __name__ == "__main__": prime_list = [2] count = 3 while len(prime_list) < 10001: if is_prime(count) == True: prime_list.append(count) count += 2 print(prime_list[-1])
false
6d77693b1904bdc0ccebd12597b6e8a6ba2ac2bb
wolfrg/Python
/Pythonjichu/gouzao.py
826
4.125
4
#coding:utf8 ''' Created on 2016年5月30日 @author: wolfrg 第九章 构造方法继承的练习 ''' __metaclass__ =type class Bird: #这个类定义鸟都具有的一些最基本的功能:吃。 def __init__(self): self.hungry = True def eat(self): if self.hungry: print 'Aaaaah....' self.hungry =False else: print 'No,thanks!' b = Bird() b.eat() b.eat() #添加子类SongBird class SongBird(Bird): def __init__(self): #Bird.__init__(self) #调用父类的构造函数 super(SongBird,self).__init__() self.sound = 'Squawk!' #构造方法被重写。 def sing(self): print self.sound sb = SongBird() sb.sing() sb.eat()
false
41b2e01a5366e6ef41cf5f90f2b423a25b15a91a
TorrBorr/Coding_challenges
/weekdays/Duplicate_Encoder.py
800
4.15625
4
# The goal of this exercise is to convert a string # to a new string where each character in the new # string is '(' if that character appears only once # in the original string, or ')' if that character # appears more than once in the original string. # Ignore capitalization when determining if a # character is a duplicate. # # Examples: # # "din" => "(((" # # "recede" => "()()()" # # "Success" => ")())())" # # "(( @" => "))((" def duplicate_encoder(word): word_dict = {} for i in word.lower(): if i in word_dict: word_dict[i] += 1 else: word_dict[i] = 1 encoded = [] for letter in word.lower(): if word_dict[letter] > 1: encoded.append(")") else: encoded.append("(") return "".join(encoded) word = "(( @" encoded_word = duplicate_encoder(word) print(encoded_word)
true
f47faec233167fcf0bf3a8448934553b16905f23
tmwpengine/mentoring
/decorators/decorators.py
2,337
4.28125
4
from helper_functions import remove_first_character, get_random_letter # Key Python concept in understanding Decorators # A function can be assigned def print_some_text(s): print(s) f1 = print_some_text f1("Hellooooo") # A function can be passed into a function as an argument def add_two(x): print(x + 2) def function_wrapper(func): func(10) function_wrapper(add_two) # A function can live inside another function def add_one(x): def add_another_one(x): print(x + 1) y = x + 1 add_another_one(y) add_one(5) # A function can return another function def return_function_that_adds_five(): def add_five(i): print(i + 5) return add_five new_func = return_function_that_adds_five() print(new_func) print(type(new_func)) new_func(10) # A nested function has access to enclosing variables scope def demo_nested_function_accessing_parent_scope(s): def nested_function(): print(s) nested_function() demo_nested_function_accessing_parent_scope("some stuff") # Creating a decorator that extends another objects functionality by converting a string to uppercase (The old way) # first decorating function def add_random_letter(func): # import pdb; pdb.set_trace() def wrapper(): original_value = func() decorated_value = f'{original_value} {get_random_letter()}' return decorated_value return wrapper # a function to decorate def return_some_string(): return "abc" decorated_response = add_random_letter(return_some_string) print(decorated_response()) # (The new way) @add_random_letter def return_some_other_string(): return "def" print(return_some_other_string()) # Applying more than one decorator # second decorating function def remove_char(func): def wrapper(): original_value = func() decorated_value = remove_first_character(original_value) return decorated_value return wrapper @add_random_letter @remove_char def return_some_other_string(): return "def" print(return_some_other_string()) # decorating functions that accepts arguments def to_upper(func): def wrapper(t): decorated_value = func(t).upper() return decorated_value return wrapper @to_upper def print_your_string(s): return s print(print_your_string("hello"))
true
4b7b677506c98092294b00fe941f4dd9bca0ed21
tmwpengine/mentoring
/closures/closures.py
1,328
4.1875
4
def print_message(message): # this is the enclosing function def print_message_inside(): # The nested function print(message) print_message_inside() print_message("Hi there") def print_message_with_non_local(msg): print(msg) def print_again(): # Here we are using the nonlocal keyword nonlocal msg msg = "Text has changed !!" print(msg) print_again() print(msg) print_message_with_non_local("original text") # example closure def store_message(message): def data_transmitter(): print(message) return data_transmitter f = store_message("Away we go!") # f() del store_message f() # another example closure def make_multiplier_of(n): def multiplier(x): return x * n return multiplier multiplied_by_five = make_multiplier_of(5) multiplied_by_fifty = make_multiplier_of(50) del make_multiplier_of print(multiplied_by_five(10)) print(multiplied_by_fifty(10)) print(dir(multiplied_by_five)) def do_something(): print("something") f5 = do_something print(f5.__closure__) print(multiplied_by_five.__closure__) print(type(multiplied_by_five.__closure__)) print(len(multiplied_by_five.__closure__)) print(dir(multiplied_by_five.__closure__[0])) print(multiplied_by_five.__closure__[0].cell_contents)
true
965b394580d55f7aedec4ffef3ff1e45e8579c50
Ubaid97/Eng74_python
/python_variables.py
332
4.125
4
# How to create a variable # name = 'Ubaid' # String variable age = 22 # Integer travel_allowance = 2.4 # Float # Type of variables: string, int, float, and boolean # How to take user input name = input("Please enter your name: ") print(name) print(age) print(travel_allowance) # How to find out type of variable print(type(age))
true
9d542f4fa0bec47692481c80b29c96c972788440
Fajrinmk/advancedprogrammingtutorial
/2017/week_2/Tutorial2-FM-Template.py
1,198
4.3125
4
# Mandatory 3: Create a program so it implement Factory Method Pattern. There are a template class to use Factory Method Pattern but you are free to explore your idea in implementing Factory Method Pattern. def main(): board = Board3x3() print (board) class AbstractBoard: def __init__(self, rows, columns): self.board = [[None for _ in range(columns)] for _ in range(rows)] self.populate_board() def populate_board(self): raise NotImplementedError() def __str__(self): squares = [] for x, row in enumerate(self.board): for y, column in enumerate(self.board): squares.append(self.board[x][y]) squares.append("\n") return "".join(squares) class Board3x3(AbstractBoard): def __init__(self): super().__init__(3, 3) def populate_board(self): for row in range(3): for column in range(3): if (column % 2): self.board[row][column] = "o" else: self.board[row][column] = "x" # Mandatory 3: Uncomment the codes below # class Piece(str): # __slots__ = () # class Circle(Piece): # Mandatory 3: Implement the Factory Method in here # class Cross(Piece): # Mandatory 3: Implement the Factory Method in here if __name__ == "__main__": main()
true
318ae6d8ff9a1f205fe4ac36c55874302fb1fb95
sfwarnock/Statistical-Computing
/python/chapter 02/sqrint.py
325
4.21875
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 8 2018 @author: Scott Warnock """ # Square an integer. def main(): x = 3 ans = 0 intersLeft = x while (intersLeft != 0): ans = ans + x intersLeft = intersLeft - 1 print (str(x) + '*' + str(x) + ' = ' + str(ans)) main()
false
08073c99492ba724d191e37ec764ec523632a647
PlumpMath/MyCoroutine
/testGenerator.py
454
4.15625
4
#!/usr/bin/env python # encoding: utf-8 def permutations(li): if len(li) == 0: yield li else: for i in range(len(li)): li[0], li[i] = li[i], li[0] for item in permutations(li[1:]): print "item is :" print item yield [li[0]] + item for item in permutations(range(3)): print ">>>>>>>>>>>>>>>>>>>>>>>>" print item print ">>>>>>>>>>>>>>>>>>>>>>>>"
false
75cf4291fabb5d95d17b98d199b0b4505081844a
elaris6/PythonPildoras
/cred_crud/temp/crear_tabla_tkinter.py
856
4.40625
4
# Python program to create a table # https://www.geeksforgeeks.org/create-table-using-tkinter/ from tkinter import * class Table: def __init__(self, root): # code for creating table for i in range(total_rows): for j in range(total_columns): self.e = Entry(root, width=20, fg='blue', font=('Arial', 16, 'bold')) self.e.grid(row=i, column=j) self.e.insert(END, lst[i][j]) # take the data lst = [(1, 'Raj', 'Mumbai', 19), (2, 'Aaryan', 'Pune', 18), (3, 'Vaishnavi', 'Mumbai', 20), (4, 'Rachna', 'Mumbai', 21), (5, 'Shubham', 'Delhi', 21)] # find total number of rows and # columns in list total_rows = len(lst) total_columns = len(lst[0]) # create root window root = Tk() t = Table(root) root.mainloop()
true
1a2a8312de48b139e96f2fd3172414225f2307c6
cahyamida/training
/Exercise1solution.py
671
4.21875
4
numbers = [] strings = [] names = ["Anakin Skywalker", "Padme Amidala", "Han Solo", "Qui-Gon Jinn", "Luke Skywalker", "Obi-Wan Kenobi"] # write second_name = 1 numbers.append(1) numbers.append(2) numbers.append(3) strings.append('Satu'); strings.append('Dua'); strings.append('Tiga'); # this code should write out the filled arrays and the second name in the names list (Padme Amidala). print(numbers) print(strings) print("The Second name on the names list is %s" % names[second_name]) #print the list variable use for for i in names: print(i) #print the list without name "Han Solo" for x in names: if x!="Han Solo" print(x) or for x in names: if x == "Han Solo": continue print(x)
true
cae62bac462a23cc1bd21168b99af6163581333a
marisoarsan/Teste-de-performance-3
/exercicio_1.py
782
4.1875
4
"""Usando Python, faça o que se pede (código e printscreen): Crie uma lista vazia; Adicione os elementos: 1, 2, 3, 4 e 5, usando append(); Imprima a lista; Agora, remova os elementos 3 e 6 (não esqueça de checar se eles estão na lista); Imprima a lista modificada; Imprima também o tamanho da lista usando a função len(); Altere o valor do último elemento para 6 e imprima a lista modificada.""" lista = [] lista.extend((1,2,3,4,5)) #Fiz com extend porque achei masi fácil do que fazer um for print("Lista preenchida: ", lista) lista.remove(5) if 6 in lista: lista.remove(6) print("Lista modificada pela 2ª vez: ", lista) print("Tamanho da Lista: ", len(lista)) lista.append(6) print("Lista com o último Elemento sendo o 6: ", lista)
false
abf5e9c07ca5d07f0603a218b3f4731d55c21634
Suparoopan/python_HM
/combined.py
455
4.1875
4
from itertools import permutations def combined(list): output = [] for i in permutations(list, len(list)): output.append("".join(map(str,i))) return max(output) list = [] n = int(input("Enter how many ELEMENTS you want in the LIST : ")) for i in range(0, n): element = int(input("Enter the number into list : ")) list.append(element) print("The largest possible combined number is : ", combined(list))
true
8c436d290d5dd1842fca9a17987c305ba0821d2f
anniehe/calculator-2
/multi_arithmetic.py
1,414
4.25
4
def add(num_list): """Returns the sum of the input integers.""" result = 0 for num in num_list: result += num return result def subtract(num_list): """Takes first number, subtracts second, subtracts next until end of list, returns result.""" result = num_list[0] for num in range(1, len(num_list)): result -= num_list[num] return result def multiply(num_list): """Multiplies the inputs together.""" result = 1 for num in num_list: result *= num return result def divide(num_list): """Takes first number, divides by second, divides by next until end of list, returns a floating point result.""" result = float(num_list[0]) for num in range(1, len(num_list)): result /= num_list[num] return result def square(num_list): """Returns a list of the squares of the input.""" result = [] for num in num_list: result.append(num**2) return result def cube(num_list): """Returns a list of the cubes of the inputs.""" result = [] for num in num_list: result.append(num**3) return result def power(num1, num2): """Raises the first integer to the power of the second integer and returns the value.""" return num1 ** num2 def mod(num1, num2): """Returns the remainder when the first integer is divided by the second integer.""" return num1 % num2
true
95c419a33421d5b77877a26a876508731372c7e4
AlanaRosen/my-python-programs
/Wagon Wheel practice.py
1,921
4.4375
4
import turtle #import necessary module wn = turtle.Screen() #set up screen on which to run your turtles wn.bgcolor("gray") #set up the aesthetics of your window jess = turtle.Turtle() #name your turtles tray = turtle.Turtle() jess.shape("classic") #define your turtles' line shapes tray.shape("classic") jess.pensize(2) #define how thick your lines will be tray.pensize(2) def draw_circle(t): #define a function to draw the circle with the equidistant lines inside tray.up() #make sure tray doesn't make any marks tray.goto(0,-100) #send tray to his starting destination tray.down() #allow tray to draw again tray.circle(100) #tell tray you want him to make a circle with a radius of 100 tray.goto(0,0) #send tray back to the center of the circle, drawing your first inside line for x in range(20): #there are 20 lines needed inside the circle tray.forward(100) #send tray forward to draw the line tray.forward(-100) #send tray back to the center tray.left(18) #rotate tray (360 degrees divided by 20) draw_circle(tray) #execute tray's circle program def rotate_squares(t): jess. def draw_square(x): #define a function for drawing five squares, each one 72 degrees left of the previous one for x in range (4): jess.forward(200) jess.left(90) jess.up() jess.goto(-100,-100) jess.down() draw_square(jess) rotate_squares(jess) draw_square(jess) draw_square(jess) wn.exitonclick()
true
c7f79d39d0f0e3cc23e4b7eed1b3af62f86a8cad
Mutembeijoe/Password-Locker-1
/user.py
1,568
4.21875
4
class User: """ class that generates new user """ user_details = [] def __init__(self, first_name, second_name, password): self.first_name = first_name self.second_name = second_name self.password = password # This saves a new user registration def save_user(self): """ this save method adds and stores our user """ User.user_details.append(self) # deleting the user account def delete_account(self): """ delete account method to remove user account """ User.user_details.remove(self) # finding user by first_name @classmethod def find_by_fname(cls, first_name): """ find user by their first name Args: first_name: first name of the user to search for returns: user searched for """ for user in cls.user_details: if user.first_name == first_name: return user # confirm user exist @classmethod def user_exist(cls, first_name): """ method that checks if the user exists by name Args: first_name checks if the name exists returns a boolean depending if the name exists """ for user in cls.user_details: if user.first_name == first_name: return True return False # display user @classmethod def display_user(cls): """ Function that displays users """ return cls.user_details()
true
900a4e2e4c9bbbdd9aaab523d4d27d2ba3eab0cd
acid9reen/Artezio
/Lesson_3/task1.py
945
4.21875
4
'''Task 1 module''' def quad(list_): '''Return list of quads of the numbers from given list''' return [x * x for x in list_] def even_positions_elements(list_): '''Rerurn list of even positions elements from given list''' res = [] for i in range(1, len(list_), 2): res.append(list_[i]) return res def cube_odd_positions_even_elements(list_): '''Return list of cubes of the odd position even numbers from given list ''' res = [] for i in range(0, len(list_), 2): if (value := list_[i]) % 2 == 0: res.append(value ** 3) return res def main(): '''Run all functions from this module with user input''' list_ = list(map(int, input("Enter elements of " "the list divided by space: ").split())) print(quad(list_)) print(even_positions_elements(list_)) print(cube_odd_positions_even_elements(list_)) main()
true
ddee806ea3b86f97b1df3b38de528c6b7560f77d
acid9reen/Artezio
/Lesson_1/task05.py
553
4.25
4
'''Check if 3rd set is a subset of 1st and 2nd''' def subset_of_two(set_1, set_2, set_3): '''Return true if 3rd set is a subset of 1st and 2nd and false in other cases''' return set_3.issubset(set_1) and set_3.issubset(set_2) def main(): '''Run subset_of_two function with user input''' set_1 = set(map(int, input("Enter the 1st set: ").split())) set_2 = set(map(int, input("Enter the 2nd set: ").split())) set_3 = set(map(int, input("Enter the 3rd set: ").split())) print(subset_of_two(set_1, set_2, set_3)) main()
true
b07ce6dfa7c43143c647c4debd8b75017594b7cc
acid9reen/Artezio
/Lesson_1/task10.py
416
4.34375
4
'''Find difference between two lists''' def get_diff(list_1, list_2): '''Return list that contain difference between two given ones''' return list(set(list_1).symmetric_difference(set(list_2))) def main(): '''Run get_diff function with user input''' list_1 = input("Enter the 1st list: ").split() list_2 = input("Enter the 2nd list: ").split() print(get_diff(list_1, list_2)) main()
true
fe07620f0062ea709bcfb1e11799f67af300d424
acid9reen/Artezio
/Lesson_8_http_regexp/task5.py
405
4.125
4
'''Password regexp''' import re def main(): '''Password regexp''' password = input("Enter the password: ") reg = r"^(?=.*[a-z])(?=.*[_*%&])(?=.*\d)(?=.*[A-Z])[A-Za-z\d_*%&]{8,12}$" pattern = re.compile(reg) match = re.search(pattern, password) if match: print("Password is valid.") else: print("Invalid password.") if __name__ == '__main__': main()
false
07c74531cef345329785a80dcdd87af37552be25
acid9reen/Artezio
/Lesson_3/task4.py
1,122
4.21875
4
'''Convert given xml string to dictionary and calculate its depth''' from xml.etree import ElementTree as ET def dict_depth(dict_): '''Return depth of given dictionary''' max_level = 0 level = 0 for i in str(dict_): if i == '{': level += 1 elif i == '}': max_level = level if level > max_level else max_level level = 0 return max_level def tree_to_dict(tree): '''Convert given eTree object to dict and return it''' dict_ = {'name': tree.tag, 'children': []} if children := list(tree): for child_dict in map(tree_to_dict, children): dict_['children'].append(child_dict) return dict_ def xml_string_to_dict(str_): '''Run tree_to_dict() and dict_depth() functions with given xml string''' dict_ = tree_to_dict(ET.XML(str_)) return dict_, dict_depth(dict_) def main(): '''Run xml_string_to_dict() function''' str_ = "<root><element1 /><element2 />" \ "<element3><element4 /></element3></root>" print(xml_string_to_dict(str_)) if __name__ == '__main__': main()
true
f1757075edfb0a665b07e7b4f6c655fcd046a9a2
teammeredith/sam-homework
/number_sorting.py
525
4.1875
4
# Tell the user what they need to do print("Enter some single digits with commas inbetween") # Get the input from the user string = input() # Turn the string into a list of numbers numbers = string.split(',') # Sort the numbers from lowest to highest numbers.sort() # Print the lowest number print("The lowest number using those digits is", ''.join(numbers)) # Sort the numbers from highest to lowest numbers.sort(reverse=True) # Print the highest number print("The highest number using those digits is", ''.join(numbers))
true
767a30c999eb705488d6d19d8307fdd35c809941
neerajp99/algorithms
/randomised_selection.py
1,463
4.28125
4
# Implementation of Randomised Selection """ Naive Approach --------- Parameters --------- An arry with n distinct numbers --------- Returns --------- i(th) order statistic, i.e: i(th) smallest element of the input array --------- Time Complexity --------- O(n.logn) --------- Test Cases --------- [1, 20, 6, 4, 5] => [1, 4, 5, 6, 20] """ import random def randomised_selection(unsorted_array, length_of_array, i_order_statistic): if length_of_array == 1: return unsorted_array else: # pivot = random.choice(unsorted_array) pivot_range = random.randrange(length_of_array) pivot = unsorted_array[pivot_range] pivot_left = [] pivot_right = [] for value in unsorted_array: if pivot_range == i_order_statistic: return pivot if pivot_range > i_order_statistic: return randomised_selection(unsorted_array[:pivot_range], pivot_range - 1, i_order_statistic) if pivot_range < i_order_statistic: return randomised_selection(unsorted_array[pivot_range + 1:], length_of_array - pivot_range, i_order_statistic - pivot_range) if __name__ == "__main__": # user_input = input("Enter the list of numbers: \n").strip() # unsorted_array = [int(item) for item in user_input.split(",")] print(randomised_selection([1, 23, 3, 43, 5], 5, 3))
true
e6a7af2062920ffd1b4e6320f2052f6c4e9f67d7
neerajp99/algorithms
/strings_py/palindrome_permutation.py
964
4.21875
4
""" Determine if a string is a palindrome permutation. Input: "picaoacip" Output: True """ def palindrome_permutation(input): input = input.replace(" ", "").lower() check_dict = dict() # Create the dictionary for the characters of the input string for i in input: if i not in check_dict: check_dict[i] = 1 else: check_dict[i] += 1 # A string that has an even length must have all even counts of characters, # while strings that have an odd length must have exactly one character with an odd count. # An even-length-ed string can’t have an odd number of exactly one character; otherwise, it wouldn’t # be even. This is true since an odd number plus any set of even numbers will yield an odd number. odd_count = 0 for key, value in check_dict.items(): if value % 2 != 0 and odd_count == 0: odd_count = 1 elif value % 2 != 0 and odd_count != 0: return False return True print(palindrome_permutation('This is lame string'))
true
83a28849d102942f9e1ac7e1b35bf2057373d3f3
neerajp99/algorithms
/recursion/reverse_array.py
896
4.3125
4
# Reverse an array using recursion using O(1) space def reverse_insert(values, k): # Base condition to check for empty array if len(values) == 0: values.append(k) return # Pop out the last element and store it temp = values[-1] values.pop() # Recursive call with the updated function reverse_insert(values, k) # Append the remaining left out value values.append(temp) return def reverse_array(values): # Base condition when array has just 1 value left if len(values) == 1: return values # Pop out the last element and store it k = values[-1] values.pop() # Recursive call with the updated array reverse_array(values) # Induction step to make another call to the recursive function to insert the left out value reverse_insert(values, k) values = [5,4,3,2,1] reverse_array(values) print(values)
true
b2a60db5b027b07d0f06bfb5b87f8a9ec0be7f32
neerajp99/algorithms
/graphs/dijkstra.py
1,904
4.5
4
# Implementation of Dijkstra Algorithm """ Using a queue --------- Parameters --------- An object of vertices and edges and their respective weights --------- Returns --------- Shortest distances to all the nodes from the initial node (s) --------- Time Complexity --------- O(V+E) as we are doing a BFS --------- Test Cases --------- # Graph = {'U': {'X': 1, 'W': 5, 'V': 2}, 'W': {'Y': 1, 'X': 3, 'Z': 5, 'U': 5, 'V': 3}, 'V': {'X': 2, 'U': 2, 'W': 3}, 'Y': {'X': 1, 'Z': 1, 'W': 1}, 'X': {'Y': 1, 'U': 1, 'W': 3, 'V': 2}, 'Z': {'Y': 1, 'W': 5}} # Starting Node: 'X' => {'U': 1, 'W': 2, 'V': 2, 'Y': 1, 'X': 0, 'Z': 2} """ def dijkstra(graph, visited, queue, values, starting_node): # Set initial node as 0 and rest of the node as infinity for i in graph: if i == starting_node: values[i] = 0 else: values[i] = float('inf') visited.append(starting_node) queue.append(starting_node) while(len(queue) != 0): element = queue.pop(0) print(element) for i in graph[element]: # print(graph[element][i]) if values[element] + graph[element][i] < values[i]: values[i] = values[element] + graph[element][i] if i not in visited: visited.append(i) queue.append(i) # graph = { # 'U': {'V': 2, 'W': 5, 'X': 1}, # 'V': {'U': 2, 'X': 2, 'W': 3}, # 'W': {'V': 3, 'U': 5, 'X': 3, 'Y': 1, 'Z': 5}, # 'X': {'U': 1, 'V': 2, 'W': 3, 'Y': 1}, # 'Y': {'X': 1, 'W': 1, 'Z': 1}, # 'Z': {'W': 5, 'Y': 1}, # } graph = { 'start': {'A': 5, 'B': 2}, 'A': {'start': 1, 'C': 4, 'D': 2}, 'B': {'A': 8, 'D': 7}, 'C': {'D': 6, 'finish': 3}, 'D': {'finish': 1}, 'finish': {} } visited = [] queue = [] # Dictionary to keep the distances to all the nodes values = {} starting_node = str(input()) dijkstra(graph, visited, queue, values, starting_node) print(values)
true
cbfb47e40fc552d16fbd6ee6627ccc3d52b1e42b
neerajp99/algorithms
/binary_trees/size_binary_tree.py
608
4.25
4
""" The size of the tree is the total number of nodes in a tree. You are required to return the size of a binary tree given the root node of the tree. """ # Iterative approach def size_tree(self, start): count = 0 if start is None: return count queue = Queue() queue.enqueue(node) while len(queue) > 0: count += 1 node = queue.dequeue() if node.left: queue.enqueue(node.left) if node.right: queue.enqueue(node.right) return count # Recursive approach def size_tree(self, node): if node is None: return 0 return 1 + self.size_tree(node.left) + self.size_tree(node.right)
true
6f38032bbbd20fc4c7d47cb7af0be6cbf8262c10
neerajp99/algorithms
/problems/leetcode/lt-23.py
2,719
4.125
4
# 23. Merge k Sorted Lists """ You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it. Input: lists = [[1,4,5],[1,3,4],[2,6]] Output: [1,1,2,3,4,4,5,6] """ # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: # METHOD 1: Using Merge sort # Time Complexity: O(n logn) # Space Complexity: O(n) # Method to merge sort def merge_sort(unsorted_list): def merge_list(leftSide, rightSide): sorted_array = [] while leftSide and rightSide: sorted_array.append((leftSide if leftSide[0] <= rightSide[0] else rightSide).pop(0)) return sorted_array + leftSide + rightSide if len(unsorted_list) <= 1: return unsorted_list mid_term = len(unsorted_list) // 2 return merge_list(merge_sort(unsorted_list[:mid_term]), merge_sort(unsorted_list[mid_term:])) # Create a new list with all the items new_list = list() # Getting the values from the linked lists for i in range(len(lists)): current = lists[i] while current: new_list.append(current.val) current = current.next new_list = merge_sort(new_list) if len(new_list) > 0: final_list = ListNode(val=new_list[0], next=None) current = final_list for i in range(1, len(new_list)): current.next = ListNode(val=new_list[i], next=None) current = current.next return final_list else: return ListNode(val="") # METHOD 2: Using a priority queue # Time Complexity: O(n log k) # Space complexity: O(n) # Iterate over each list and add it to the priority queue new_list = list() for i in lists: current = i while current: heapq.heappush(new_list, current.val) current = current.next if len(new_list) > 0: final_list = ListNode(heapq.heappop(new_list)) current = final_list for i in range(len(new_list)): temp = heapq.heappop(new_list) current.next = ListNode(temp) current = current.next return final_list else: return ListNode("")
true
be97e930363c7a62532f3b42351388690688a1f4
neerajp99/algorithms
/recursion/sort_array.py
974
4.1875
4
# Sorting an array using recursion def sort_insert(values, k): if len(values) == 0 or values[-1] <= k: values.append(k) return # Load the last element in a temporary variable temp = values[-1] # Pop the last element values.pop() # Recursively call the sort_insert method until induction is met sort_insert(values, k) # Add the temporary variable back to the next position values.append(temp) return def sort_array(values): if len(values) == 1: return values k = values[-1] # Store the last index value in a temporary variable # sort_array(values[:-1]) # Pop the last element from the value list values.pop() # Recursively call the sort_array function with the updated value to sort the remaining array sort_array(values) # Insert the temporary variable into the array sort_insert(values, k) values = [10, 19, 110, 1, 3, 189, 10] sort_array(values) print(values)
true
0fe5afe9f0bca6098adfd5e056e0e5da2aec594c
neerajp99/algorithms
/graphs/dfs.py
970
4.15625
4
# Implementation of Depth First search """ Using a stack --------- Parameters --------- An adjacency list --------- Returns --------- The traversed graph from the starting node --------- Time Complexity --------- O(V+E) --------- Test Cases --------- starting_node = "A" => ['A', 'B', 'D', 'G', 'E', 'F', 'C'] """ def dfs(graph, visited, starting_node): if starting_node not in visited: visited.append(starting_node) stack.append(starting_node) while(len(stack) != 0): stack.pop() for i in graph[starting_node]: dfs(graph, visited, i) graph = { 'A' : ['B','C'], 'B' : ['D', 'E'], 'C' : ['F'], 'D' : ['G'], 'E' : ['F'], 'F' : [], 'G': ['A'] } # Create an empty list to mark the visited nodes visited = list() # Create an empty stack for keeping a check stack = list() dfs(graph, visited, 'A') print(visited)
true
6b778235715dfefb7244884bc55c3643723a3e55
abhisek08/Data-Structure
/create array.py
219
4.125
4
''' Write a Python program to create an array contains six integers. Also print all the members of the array. Expected Output: 10 20 30 40 50 ''' import array c=array.array('i',[10,20,30,40,50]) for i in c: print(i)
true
6bb733b24e35df04dfb70a7f5341e8ef30fb6d3d
mangodayup/month01-resource
/day07/exercise09.py
396
4.21875
4
# 练习1: 定义函数,在终端中打印一维列表. # list01 = [5, 546, 6, 56, 76, ] # for item in list01: # print(item) # list02 = [7,6,879,9,909,] # for item in list02: # print(item) def print_list(list_target): for item in list_target: print(f"元素是:{item}") list01 = [5, 546, 6, 56, 76, ] list02 = [7, 6, 879, 9, 909, ] print_list(list01) print_list(list02)
false
0012c86973f4280d86e0a1de1b334c4c61ff0655
mrybakina/beginner_py
/average_height.py
311
4.1875
4
# 31.07.2021 # A program which calculates the average of values in a list. student_heights = [156, 178, 165, 171, 187] heights = 0 for i in student_heights: heights += i string_sum = 0 for a in student_heights: string_sum += 1 average_height = round(heights / string_sum) print(average_height)
true
51dc570c6feb2927e7ea6ec8c3d08e4e847fee38
xxxTroyaNxxx/PythonLearn
/gcd.py
421
4.15625
4
""" This function takes two variable and returns greatest common divisior """ def find_gcd(x, y): while (y): x, y = y, x % y return x # Input from user print("For computing gcd of two numbers") a, b = map(int, input("Enter the number by comma separating :-", end=" ").split(",")) # Map typecast the input in 'int' type print("Gcd of {} & {} is {}", format(a, b, find_gcd(a, b)))
true
ca320d6b6cf7ff303843c4315bdba0d8a0dd4798
martindrumev/Learning-Python
/01pythonsyntax/10forloops.py
333
4.3125
4
numbers = [1, 2, 3] for element in numbers: print(element) name = "John" for char in name: print(char) print() for letter in "Giraffe Academy": print(letter) print() for numb in range (3, 10): print(numb) print() friends = ["Jim", "Caytlin", "Mark"] for index in range(len(friends)): print(friends[index])
true
b55f043bfea2e7bfaa09f3a82a6b0c33fa3e410d
PatrickBoyn/GradeCalculator
/grade_calc.py
1,008
4.125
4
import math num_questions = int(input("Please enter the number of questions: \n")) num_right = int(input("Please enter the number you got right: \n")) # Calculates the percent of a grade for a test. # Math.floor is similar to if not the same as math.floor in JavaScript. # It kicks off all the decimal places and makes the final result a whole number. grade = math.floor(round((num_right/num_questions * 100), 0)) # I have no idea if this is Python 3 or 2 code. # It works either way and I think it's easy to understand. if (100 <= grade >= 90): print("Your score was {}% which is an A".format(str(grade))) elif (80 < grade > 70): print("Your score was a {}% which is a B".format(str(grade))) elif (70 <= grade > 60): print("Your score was a {}% which is a C".format(str(grade))) elif (60 <= grade > 50): print("Your score was a {}% which is a D".format(str(grade))) print("You did not pass.") else: print("Your score was a {} F".format(str(grade))) print("You did not pass.")
true
76bc254aa274c6f8b964f91d1c25f5cf94e7fc7a
Loliloltrop/YouTube
/Tutorial 45/nested_functions.py
360
4.125
4
def outer_function(text): def inner_function(): print(text) inner_function() outer_function("Hello world") def pop(list1): def get_last_element(list2): return list1[len(list2)-1] list1.remove(get_last_element(list1)) print (list1) return (list1) list_of_numbers = [1,2,3,4,5,6] pop(list_of_numbers) pop(list_of_numbers)
false
8948be369262244397ab3d7b4e51a96b49dd65fe
chandrikakurla/stack-implementation
/stack_implementation.py
681
4.125
4
#initialising stack using list def Stackimplement(): stack=[] return stack def isEmpty(stack): return len(stack)==0 def push(stack,data): stack.append(data) print("%d is pushed into stack"%data) def pop(stack): if(isEmpty(stack)): print("stack is empty pop is not possible") return return stack.pop() def peek(stack): if(isEmpty(stack)): print("stack is empty") return return stack[len(stack)-1] stack=Stackimplement() print(pop(stack)) push(stack,1) push(stack,2) push(stack,3) print("top element of stack is %d"%peek(stack)) print("%d is popped from satck"%pop(stack))
true
1994124ca6c522ec130d017aa6c5119fa9477066
MohitWayde/Python-tutorials-CWH
/Python tuts CWH/file IO basics.py
1,334
4.15625
4
# 10-10-2020 # Will cause error as no file not found so create a txt file and give it to this program ''' File IO Basics 'r' - open file for reading 'w' - open file for writing 'x'- (exclusive) create file if not exist 'a' - (append) add more content to a file 't' - text mode 'b' - binary mode '+' - read and write both ''' f=open("mohit.txt", "rt")#read + text mode content=f.read() print(content) f.close() for line in content: print(line) for line in f: print(line) # print(f.readline())#used to print single line at a time print(f.readlines()) # 11-10-2020 # File writing f= open("mohit.txt","a") f.write("I love to play tabla\n") f.close() f= open("mohit.txt","a") f.write("I want to create projects\n") f.close() f= open("mohit.txt","r+") f.write("Thank you\n") f.close() # 12-10-2020 f=open("mohit.txt") print(f.readline()) print(f.tell()) #tell() used to tell new line's number(File pointer) print(f.readline()) print("Tell from where to start reading or to seek",f.seek(20)) #seek() used for read the file from given input print(f.readline()) print(f.readline()) f.close() # 13-10-2020 #In with block we dont needs to type close() for closing the file it automatically closes file with open("mohit.txt") as f: a=f.readline(16) print(a)
true
6817f60d2c396079a2122c69f61b7a355b35115a
MohitWayde/Python-tutorials-CWH
/Python tuts CWH/string slicing.py
604
4.25
4
mystr = "My name is MOHIT" print(mystr[6]) print(mystr[0:6]) print(mystr[11:16]) print(mystr[11:]) print(mystr[:16]) print(mystr[:]) print(mystr[::]) print(mystr[::2]) print(mystr[::3]) print(mystr[::-1]) print(mystr[::-2]) print(mystr[:16:-2]) # len print(len(mystr)) # isalnum print(mystr.isalnum()) # isalpha print(mystr.isalpha()) # endswith print(mystr.endswith("MOHIT")) print(mystr.endswith("mohit")) # count print(mystr.count("M")) # capitalize print(mystr.capitalize()) # find print(mystr.find("MOHIT")) # lower print(mystr.lower()) # upper print(mystr.upper())
false
280aeccaffd26848dbb72abee41f7a908a4536af
MohitWayde/Python-tutorials-CWH
/Python tuts CWH/class&oopconcepts.py
939
4.21875
4
# 9-11-2020 # class and object oriented programming class Student: print("this is student class") def function_name(self): print("Function") return "method inside class \"Student\" printed successfully " m = Student() print(m.function_name()) # 9-11-2020 and 12-11-2020 # self and __init__ constructor # self is used for identifying from which instance you are accessing particular method # in above example "mohit" is went in "self" class Collage_data: '''THis is docstring of class''' def __init__(self,abr,arn): self.br = abr self.rn = arn def print_data(): return f"Branch is {br} & roll number is {rn}" mohit = Collage_data("computer", 94) rohit = Collage_data("mechatronics", 10) print(mohit.br) print(mohit.rn) print(rohit.br) print(rohit.rn) print(mohit.__dict__) #dictionary for class information print(mohit.__doc__) #docstring
true
0ddf1a29f62b5048ef4b8073ba40523e13224865
J2Tuner/python-katas
/python/isogram/isogram.py
472
4.1875
4
def is_isogram(string): # Format Input String string = string.lower() ok_tokens = "abcdefghijklmnopqrstuvwxyz" # Remove non-alphabetic characters from string for c in string: if c not in ok_tokens: string = string.replace(c, "") # Check if string is an isogram for i in range(len(string)): for j in range(i + 1, len(string)): if string[i] == string[j]: return False return True
false
9d47622aa6781eacf94c18c43650a1a6adee2075
JMill/stat101-2013fa
/code/exam2-infinitemonkeys.py
783
4.15625
4
import random targetWord='h' characters="abcdefghijklmnopqrstuvwxyz" targetLength = len(targetWord) guess = "" numGuesses = 0 def monkeyGuess(characters, targetLength): """ Generates a random permutation of specified length, composed of the specified letters. Returns: a random string, such as "jadf" if 4 characters were specified, or "nusil" if 5 characters were specified. """ randomGuess = "" for character in range(targetLength): randomGuess = randomGuess + random.choice(characters) return randomGuess while guess != targetWord: guess = monkeyGuess(characters, targetLength) numGuesses = numGuesses + 1 print "The monkeys discovered '%s'" % (guess ) print "after " + str(numGuesses) + " random guesses."
true
5045a3bf01e74cb9b1e10aefc6054c1f99c82720
jrog20/nimm
/nimm.py
1,012
4.28125
4
""" File: nimm.py ------------------------- The ancient game of Nimm. Two players start with a pile of 20 stones in the center. The players alternate turns, each deciding to take 1 or 2 stones on their turn until all the stones are gone. The last player to take a stone looses. """ def main(): player = 1 stones = 20 while stones > 0: stones_remove = get_num_stones(stones, player) player = change_player(player) while stones_remove > 2 or stones_remove < 1: stones_remove = int(input('Please enter 1 or 2: ')) print() stones -= stones_remove print(f'Player {player} wins!') def get_num_stones(stones, player): print(f'There are {stones} stones left') stones_remove = int(input(f'Player {player} would you like to remove 1 or 2 stones? ')) print() return stones_remove def change_player(player): if player == 1: player = 2 else: player = 1 return player if __name__ == '__main__': main()
true
bad9ddae8e59ed27823113196eb286765cb93fed
homeah/git
/prime_generator_iter.py
695
4.15625
4
import math def is_prime(number): if number > 1: if number == 2: return True if number % 2 == 0: return False for current in range(3,int(math.sqrt(number)+1),2): if number % current == 0: return False return True return False def get_primes(number): while True: if is_prime(number): number = yield number #首次none,再次需要send才能赋值? number += 1 def print_successive_primes(iteration,base = 10): prime_generator = get_primes(base) prime_generator.send(None) for power in range(iteration): print(prime_generator.send(base **power))
true
2277de9de2369caa009a8189c8d3c41257eaf534
alvaroserrrano/codingInterviewQuestions
/linkedLists/revSingly.py
564
4.25
4
""" Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? """ class Node(self, val = 0, next = None): self.val = val self.next = next class Solution: def reverseList(self, head): prev = None cur = head while cur != None: temp = cur.next cur.next = prev prev=cur cur=temp return prev """ input [1,2,3,4,5] output[5,4,3,2,1] """
true
8b0f30e98a145f567a9aa29c7d64e5dcd629b140
alvaroserrrano/codingInterviewQuestions
/utils/digital_root.py
563
4.1875
4
""" We're provided a positive integer num. Can you write a method to repeatedly add all of its digits until the result has only one digit? Here's an example: if the input was 49, we'd go through the following steps: SNIPPET 1 // start with 49 2 4 + 9 = 13 3 ​ 4 // move onto 13 5 1 + 3 = 4 We would then return 4. """ class Solution: def addDigits(self, num): root=0 while num>0: root += num%10 num = num //10 if num==0 and root > 9: num=root root=0 return root
true
75fb853300cbf121aa7b939dda397d3fd26833e4
iajalil/tkinter-demo
/mini-calculator.py
2,542
4.21875
4
""" THIS IS A MINI - CALCULATOR APP THAT IS MEANT TO REGISTER MOUSE CLICKS AND KEYBOARD HITS """ # Importing the tkinter module from tkinter import * class OurWindow: def __init__(self, win): # Setting up our labels self.lblFnum = Label( win, text = "First Number") self.lblFnum.place(x = 100, y = 50) # setting the position for First number label self.lblFSnum = Label( win, text = "Second Number") self.lblFSnum.place(x = 100 , y =100) # setting the position for Second number label self.lblResult = Label( win, text = "Result") self.lblResult.place(x = 100, y= 200) # setting the position for Result label # Setting up our Textboxes (Entry Fields) self.txtFnum = Entry() self.txtFnum.place (x = 200, y = 50) # Setting the position for the First Number entry field self.txtSnum = Entry() self.txtSnum.place (x = 200, y = 50) # Setting the position for the Second Number entry field self.txtSnum.place (x= 200, y= 100) self.txtResult = Entry(bd = 3) # Giving the result textbox a border of width 3 self.txtResult.place (x=200, y =200) # Setting the position for the result entry field # Setting up our Buttons self.btnAdd = Button( win, text = "Add", command = self.add ) self.btnAdd.place (x = 100, y = 150) #Setting th eposition for the Add button self.btnSubtract = Button ( win, text = "Subtract", command = self.subtract) self.btnSubtract.place(x=200,y = 150) # Setting the position for the subtract #Defining our addition event def add (self): self.txtResult.delete( 0, 'end') FirstNumber = int(self.txtFnum.get()) #Grabbing the input from the first number SecondNumber = int(self.txtSnum.get()) #Grabbing the input from the Second number Result = FirstNumber + SecondNumber #Performing the addition self.txtResult.insert (END, str( Result)) #Defining our subtraction event def subtract (self): self.txtResult.delete( 0, 'end') FirstNumber = int(self.txtFnum.get())#Grabbing the input from the first number SecondNumber = int(self.txtSnum.get())#Grabbing the input from the Second number result = FirstNumber - SecondNumber #Performing the subtraction self.txtResult.insert (END, str( result)) # Setting up the window container = Tk() myContainer = OurWindow(container) container.title("Mini-Calculator") container.geometry("400x300+10+10") container.mainloop()
true
0429b3b6bed73ba979ae3557b9e25d80d8b1799a
gcifuentess/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/3-say_my_name.py
649
4.1875
4
#!/usr/bin/python3 """say_my_name module""" def say_my_name(first_name, last_name=""): """prints first and last name Args: first_name: string for first name last_name: string for last name Raises: TypeError: when first_name or last_name are not strings. """ if not isinstance(first_name, str): raise TypeError("first_name must be a string") if not isinstance(last_name, str): raise TypeError("last_name must be a string") print("My name is {:s} {:s}".format(first_name, last_name)) if __name__ == "__main__": import doctest doctest.testfile("tests/3-say_my_name.txt")
true
6ffa4207f547c377d082e0e7cf9efb26722ca918
storans/as91896-virtual-pet-mbonsey
/string_check.py
607
4.125
4
# Create a universal string checking function # Question and error allow it to be used in a range of situations def check_string(question, error): valid = False while not valid: # Any question that needs a number input word = input("{}: ".format(question)) try: word = input(word) if int in word: print(error) else: return word # If an invalid input is made, the prompt is made again except ValueError: # The error that prints is customised to the question print(error)
true
d1012372e2679dbfe45e77b78e903b370f2323ed
Galocodes/Hello_world
/DiceGuess.py
961
4.375
4
"""This program rolls a pair of dice and asks the user to guess a number. If the user's guess is greater than or equal to the total value of the roll, they win! Otherwise, the computer wins.""" from random import randint from time import sleep def get_user_guess(): guess = int(raw_input('Guess a number: ')) return guess def roll_dice(number_of_sides): first_roll = randint(1, number_of_sides) second_roll = randint(1, number_of_sides) max_val = number_of_sides * 2 print 'Max possible roll is %d' % max_val guess = get_user_guess() if guess > max_val: print 'Invalid guess.' else: print 'Rolling...' sleep(2) print 'First roll is %d.' % first_roll print 'Second roll is %d.' % second_roll sleep(1) total_roll = first_roll + second_roll print 'Total roll is %d.' % total_roll print 'Result...' sleep(1) if guess > total_roll: print 'You Win!' else: print 'You Lose.' roll_dice(6)
true
41a490c2364a978022f8f924405390926172c6c9
Sanich11/QAP-6
/PycharmProjects/Mod14/Task14_1_5.py
570
4.25
4
# Напишите функцию, которая будет возвращать количество делителей числа а. # Пример ввода: 5 # Пример вывода программы: 2 def divider(a): count = 0 for i in range(1, a + 1): if a % i == 0: print(f'Число {i} является делителем числа {a}') count += 1 else: print(f'Число {i} не является делителем числа {a}') return print(f' У числа {a} делителей {count}') divider(5)
false
dec1515e863d29a61f842d5fa38469ea3c204c35
Sanich11/QAP-6
/PycharmProjects/Mod13/Task13_4_5.py
710
4.1875
4
""" Записать условие, которое является истинным, когда только одно из чисел А, В и С меньше 45. Иногда проще записать все условия и не пытаться упростить их. """ A = int(input('Введите значение A: ')) B = int(input('Введите значение B: ')) C = int(input('Введите значение C: ')) if (((A < 45) and (B >= 45) and (C >= 45)) or ((A >= 45) and (B < 45) and (C >= 45)) or ((A >= 45) and (B >= 45) and (C < 45))): print('Только одно из чисел А, В и С меньше 45') else: print(False)
false
0ba698acfd4470dc9284c4dacb2e1379ff80a188
Sanich11/QAP-6
/PycharmProjects/Mod14/Task14_1_4.py
350
4.375
4
# Напишите функцию, которая печатает “обратную лесенку” следующего типа: # n = 3 n = 4 # *** **** # ** *** # * ** # * def ladder_print(n): print(f'n = {n}') for i in range(n, 0, -1): print('*' * i) ladder_print(4) ladder_print(9)
false
75f3b22c152393ca75b7cf3c202c5d21a238abf0
lukasmvv/pythonProjects
/coin_flip.py
834
4.1875
4
import random # Function to flip a coin a certain number of times and determine heads or tails # Returns a list of 2 values with number of heads and number of tails def flip(n): maxRand = 100; ls = [] heads = 0 tails = 0 for i in range(n): # The random.randint(1,N) returns a random integer between 1 and N if ((random.randint(1,maxRand)) > maxRand/2): heads += 1 else: tails += 1 ls.append(heads) ls.append(tails) return ls ## -- Start of coin flip -- ## -- Assuming positive integer input print("-- Start of coin flip --") print("-- Assuming positive integer input") # Getting input n = input("How many flips?: ") # Flipping coin rs = flip(int(n)) # Printing results print("Heads: " + str(rs[0]) + " - " + str(100*rs[0]/int(n)) + "%") print("Tails: " + str(rs[1]) + " - " + str(100*rs[1]/int(n)) + "%")
true
55f315af8b6f41cf8a574591908ae2a036826ca1
willpiam/pythonProblemsAndSolutions
/problemSetTwo/P2Q2.py
463
4.40625
4
""" Name: william File Name:P2Q2 Date: march 5th 2018 description: Ask the user for a number and print that many '*' characters in a horizontal line. You are going to have to override the default function of print(). Here's how to avoid the newline character from printing: print('*', end='' """ num = int(input("enter a number"))#gets number as int for i in range(0,num): print ("*", end="")#this line prints * but doesnt make it a new line
true
ec17ce712b14234f146b4560d73c81de53a5c115
stygianlgdonic/PythonRefresher
/datetime and calender/timedeltas.py
1,177
4.25
4
from datetime import date from datetime import time from datetime import datetime from datetime import timedelta # construct a basic timedelta and print it print(timedelta(days=365, hours=2, minutes=12)) # print today's date today = datetime.now() print("Today is: ", today) # print today's date one year from now print("1 year later: " + str(today + timedelta(days=365))) # create a timedelta that uses more than one argument print("1 year and 2 weeks later: " + str(today + timedelta(days=365, weeks=2))) # calculate the date 1 week ago, formatted as a string t = datetime.now() - timedelta(weeks=1) s = t.strftime("%A, %d, %B, %Y") print("one week ago, it was ", s) ### How many days until April Fools' Day? today = date.today() afd = date(today.year, 4, 1) # use date comparison to see if April Fool's has already gone for this year # if it has, use the replace() function to get the date for next year if afd < today: print("Already went by %d days ago" % ((today - afd).days)) afd = afd.replace(year=today.year + 1) # Now calculate the amount of time until April Fool's Day days_left = afd - today print("its just", days_left.days, "days away now!")
true
ac55b15468a4c578c077eeeb3fc442cde1d13a2f
neerajgupta37/cprograms
/Sol_Class1.py
614
4.3125
4
# -*- coding: utf-8 -*- """ Created on Sun Oct 18 17:33:29 2020 @author: dell """ class Cat: species = 'mammal' def __init__(self, name, age): self.name = name self.age = age # 1 Instantiate the Cat object with 3 cats Cat1 = Cat('Jenifer',4) Cat2 = Cat('Jelly',7) Cat3 = Cat('Marget',5) # 2 Create a function that finds the oldest cat def oldest_cat(*args): return max(args) # 3 Print out: "The oldest cat is x years old.". x will be the oldest cat age by using the function in #2 print(f'the oldest cat is {oldest_cat(Cat1.age,Cat2.age, Cat3.age)} years old')
true
d5ef9a4dbeee0ebcefc3d9b53149f3de84d8bdad
ChrisMCodes/Python_Practice
/csv_writer.py
1,464
4.5625
5
#!/usr/bin/env python3 ''' This is just a practice script so that I can remember how to create and read CSV files. Feel free to use it to make your own CSV files! ''' import os import csv # Create a file with data in it def create_file(filename): cont_adding = 'yes' with open(filename, "w") as file: headers = input("Please enter the column headers for your data, separated by commas (example: 'Name, DOB, Department'): ") file.write(headers + "\n") while cont_adding == 'yes': # prompt user for data new_data = input("Please input your data, separated by commas: ") answer = input("Would you like to keep adding data? yes/no ") if answer.lower() == "yes" or answer.lower() == "y": file.write(new_data + "\n") cont_adding = "yes" else: file.write(new_data) cont_adding = "no" # Read the file contents and format the information about each row def contents_of_file(filename): return_string = "" # Call the function to create the file create_file(filename) # Open the file with open(filename) as file: # Read the rows of the file into a dictionary reader = csv.reader(file) # Process each item of the dictionary for row in reader: for item in row: return_string += item return_string += "\n" return return_string # test call. Comment this out once you're ready to use this code! print(contents_of_file("sample_data.csv"))
true
17a5fa6e62bbd04ac467f2ac65c298a9a689785c
ChrisMCodes/Python_Practice
/coin_counter.py
2,126
4.3125
4
#This program allows you to weigh your coins by type and outputs an estimate of the number of coin you have (by type), how many coin rollers you will need for them, what the value of the [type of coin] is, and what the total value of all coins comes out to #This is a good example of why functional programming can sometimes get sticky. #I instead used logical blocks offset by whitespace and comments so that variables were re-usable without complicating iterations coins = ['pennies', 'nickels', 'dimes', 'quarters', 'half dollars', 'dollar coins'] total_vals = [] total_val = 0 #Iterates through coins for coin in coins: #Nums function; determines the number of each type of coin by weight coin_weight = {'pennies': 2.5, 'nickels': 5, 'dimes': 2.268, 'quarters': 5.67, 'half dollars': 11.34, 'dollar coins': 8.1} weight_divisor = coin_weight[coin] weight = float(input('Please enter the weight of {} in grams: '.format(coin))) num_coins = int(weight//(weight_divisor)) print('You have approximately {} {}.'.format(num_coins, coin)) nums = num_coins #Vals function; determines the value of each type of coin using the number in the nums function coin_values = {'pennies': 0.01, 'nickels': 0.05, 'dimes': 0.10, 'quarters': 0.25, 'half dollars': 0.50, 'dollar coins': 1} coin_val = round((nums * coin_values[coin]),2) print('The value of your {} is approximately ${}.'.format(coin, coin_val)) vals = coin_val #Determines how many wrappers are needed based on the vals wrapper_vals = {'pennies': 0.5, 'nickels': 2, 'dimes': 5, 'quarters': 10, 'half dollars': 10, 'dollar coins': 25} wrappers = int(vals/wrapper_vals[coin]) print('You are going to need approximately {} wrappers for your {}.'.format(wrappers, coin)) #Adds val to the total_vals list total_vals = total_vals + [vals] #Calculates values of all coins for val in total_vals: total_val = total_val + val #Prints the satisfying statement you were waiting for: print('The total value of your change is ${}.'.format(total_val))
true
44133fa3eb45c262e890854a31f028c8c36ca3dd
ChrisMCodes/Python_Practice
/Find_the_num.py
2,479
4.125
4
''' Between 1 and 1000, there is only 1 number that meets the following criteria. While it could be manually figured out with pen and paper, it would be much more efficient to write a program that would do this for you. With that being said, your goal is to find out which number meets these criteria. To find out if you have the correct number, click the link at the bottom of this main post. The number has two or more digits. The number is prime. The number does NOT contain a 1 or 7 in it. The sum of all of the digits is less than or equal to 10. The first two digits add up to be odd. The second to last digit is even. The last digit is equal to how many digits are in the number. ''' #Has two or more digits, creating list of integers between 10 and 1000 nums = [] for num in range(10, 1001): nums.append(num) #The number is prime def is_prime(nums): primes = [] for num in nums: for i in range(2, num): if num % i == 0: break else: primes.append(str(num)) return primes #The number does not contain 1 or 7 in it def no_one_or_seven(nums): new_nums = [] for num in nums: if '1' not in num and '7' not in num: new_nums = new_nums + [num] return new_nums #The sum of all of the digits is less than or equal to 10. def less_than_11(nums): final_list = [] for num in nums: new_list = [] num_sum = 0 for digit in num: new_list = new_list + [digit] for i in new_list: num_sum = num_sum + int(i) if num_sum < 11: final_list = final_list + [num] return final_list #The first two digits add up to be odd. def first_two_odd(nums): final_list = [] for num in nums: if (int(num[0]) + int(num[1])) % 2 == 1: final_list = final_list + [num] return final_list #The second to last digit is even. def penultimate_even(nums): final_list = [] for num in nums: if int(num[-2]) % 2 == 0 and int(num[-2]) != 0: final_list = final_list + [num] return final_list #The last digit is equal to how many digits are in the number. def num_digits(nums): for num in nums: if int(num[-1]) == len(num): winner = 'The magic number is...' + num + '!' return winner print(num_digits(penultimate_even(first_two_odd(less_than_11(no_one_or_seven(is_prime(nums))))))) #TEST
true
653ac8eb39544d8bf4a7585e8b46931fd2f09c75
ChrisMCodes/Python_Practice
/halloween_mad_libs.py
1,503
4.25
4
animal = input('Type of animal: ').upper() name = input('Name for a boy: ').upper() activity = input('After-school activity: ').upper() weather = input('Word to describe the weather: ').upper() monster = input('Type of monster: ').upper() motion = input('Action word for a type of movement: ').upper() decoration = input('Halloween decoration: ').upper() last_name = input('Last name: ').upper() print('\n') print('Once upon a time, there was a young {} who lived with his parents.'.format(animal)) print('One day, when the {}, whose name was {}, was walking home from {}, the weather suddenly changed!'.format(animal, name, activity)) print('The sky turned dark.') print("'Where did this {} weather come from?' wondered {}.".format(weather, name)) print('As he approached his house, it started to seem farther and farther away. The sidewalk felt like it was pulling him back to school!') print('He turned around to see what was happening, and he saw a {} trying to catch up with him.'.format(monster)) print('He began to {}, but no matter how much he did, he could feel the {} getting closer!'.format(motion, monster)) print("The {} at the house he was passing suddenly stood up and pushed him into the {}'s arms.".format(decoration, monster)) print('He yelled and cried. This was no {}! It was much, much worse! It was Mrs. {}, his teacher, who had come to tell him that his homework was late!'.format(monster, last_name)) print('{} wished he had never left {}...'.format(name, activity))
true
006c50985cc9965626f5d1aa7dcaffa38157d642
debdutgoswami/python-semester-practical
/Question 51 - 60/Q52.py
249
4.28125
4
def power(n: int, p: int)->float: if(p == 0): return 1 elif(p<0): return (1/n)*power(n, p+1) else: return n*power(n,p-1) n = int(input("enter the number: ")) p = int(input("enter the power: ")) print(power(n,p))
true
bdff7c4dcd1c7288610b061e69ffd13892a62316
Takayoshi-Matsuyama/study-of-deep-learning
/01_Python入門.py
2,478
4.21875
4
# 算術計算 print(1 - 2) print(4 * 5) print(7 / 5) print(3 ** 2) # データ型 print(type(10)) print(type(2.718)) print(type("hello")) # 変数 x = 10 print(x) x = 100 print(x) y = 3.14 print(x * y) print(type(x * y)) # リスト a = [1, 2, 3, 4, 5] print(a) print(a[0]) print(a[4]) a[4] = 99 print(a) print(a[0:2]) print(a[1]) print(a[:3]) print(a[:-1]) print(a[:-2]) # ディクショナリ me = {'height' : 180} print(me['height']) me['weight'] = 70 print(me) # ブーリアン hungry = True sleepy = False print(type(hungry)) print(not hungry) print(hungry and sleepy) print(hungry or sleepy) # if文 hungry = True if hungry: print("I'm hungry") # for文 for i in [1,2,3]: print(i) # 関数 def hello(): print("Hello World!") def hello(object): print("Hello " + object + "!") hello("cat") # クラス class Man: def __init__(self, name): self.name = name print("Initialized!") def hello(self): print("Hello " + self.name + "!") def goodbye(self): print("Good-bye " + self.name + "!") m = Man("David") m.hello() m.goodbye() # NumPy import numpy as np x = np.array([1.0, 2.0, 3.0]) y = np.array([2.0, 4.0, 6.0]) print(x + y) print(x - y) print(x * y) print(x / y) print(x/2.0) # ブロードキャスト: NumPy配列の各要素とスカラ値との間で計算が行われる。 # NumPyのN次元配列 A = np.array([[1, 2], [3, 4]]) print(A) print(A.shape) print(A.dtype) B = np.array([[3, 0], [0, 6]]) print(A + B) print(A * B) print(A) print(A * 10) #ブロードキャスト # NumPy ブロードキャスト A = np.array([[1, 2], [3, 4]]) B = np.array([10, 20]) print(A * B) # NumPy 要素へのアクセス X = np.array([[51, 55], [14, 19], [0, 4]]) print(X) print(X[0]) print(X[0][1]) for row in X: print(row) X = X.flatten() # Xを1次元の配列へ変換 print(X) print(X[np.array([0, 2, 4])]) # インデックスが0, 2, 4番目の要素を取得 print(X > 15) print(X[X > 15]) # Matplotlib # 単純なグラフの描画 import matplotlib.pyplot as plt x = np.arange(0, 6, 0.1) y = np.sin(x) plt.plot(x, y) plt.show() # pyplotの機能 x = np.arange(0, 6, 0.1) y1 = np.sin(x) y2 = np.cos(x) plt.plot(x, y1, label="sin") plt.plot(x, y2, linestyle="--", label="cos") plt.xlabel("x") plt.ylabel("y") plt.title('sin & cos') plt.legend() plt.show() # 画像の表示 from matplotlib.image import imread img = imread('./dataset/lena.png') plt.imshow(img) plt.show()
false
18e0d7f448347df78dd2e57115260ea2a6d79242
Aaryan-R/Py-Practice
/Rev String.py
208
4.40625
4
def reverse(str): string = " " for i in str: string = i + string return string str = "Hello World" print("The original string is:",str) print("The reverse string is:", reverse(str))
true
f336f0e206de2fd24c2d9427840d2d534a64b47b
batoolmalkawii/data-structures-and-algorithms-python
/tests/test_merge_sort.py
857
4.15625
4
from data_structures_and_algorithms_python.challenges.merge_sort.merge_sort import merge_sort """ Test Cases: 1. Apply merge sort on an empty list. 2. Apply merge sort on a sorted list. 3. Apply merge sort on a reversed list. 4. Apply merge sort on a nearly-sorted list. 5. Apply merge sort on a non-sorted list. 5. Apply merge sort on a list that includes unique cases. """ def test_merge_empty(): assert merge_sort([]) == [] def test_merge_sorted(): assert merge_sort([1,2,3,4,5]) == [1,2,3,4,5] def test_merge_reversed(): assert merge_sort([5,4,3,2,1]) == [1,2,3,4,5] def test_merge_nearly_sorted(): assert merge_sort([2,3,5,7,13,11]) == [2,3,5,7,11,13] def test_merge_non_sorted(): assert merge_sort([8,4,23,42,16,15]) == [4, 8, 15, 16, 23, 42] def test_merge_unique(): assert merge_sort([5,12,7,5,5,7]) == [5,5,5,7,7,12]
true
266819fb1f91fd6a676c3388ba4f6daf06fc5e71
astrxtmtz21/CYPRamonTM
/listas2.py
1,307
4.28125
4
# arreglos # lectura # escritura / asignacion # actualizacion # ordenamiento # busqueda # Escritura frutas = ["Zapote", "Manzana", "Pera", "Aguacate", " Durazno", "Uva", "Sandia"] # Lectura print(frutas[2]) #Lectura con for # For opcion 1 for indice in range(0, 7, 1): print(frutas[indice]) print("-----") #For opcion2 - por un iterador for each for fr in frutas: print(fr) #Asignacion frutas[2]="Melon" print(frutas) #Insercion al final frutas.append("Naranja") print(frutas) print(len(frutas)) frutas.insert(2, "Limon") print(frutas) print(len(frutas)) frutas.insert(0,"Mamey") print(frutas) #Eliminacion con pop print(frutas.pop()) print(frutas) print(frutas.pop(1)) print(frutas) frutas[2]="Limon" frutas.append("Limon") print(frutas) frutas.remove("Limon") print(frutas) #Ordenamiento frutas.sort() print(frutas) frutas.reverse() print(frutas) #Busqueda print(f"La Uva esta en la pos. { frutas.index('Uva') } ") print(f"El limon esta { frutas.count('Limon') } veces en la lista") #Concatenar print(frutas) otras_frutas = ["Rambutan", "Platano", "Fresa", "Toronja"] frutas.append(otras_frutas) print(frutas) #Copiar copia = frutas copia.append("Naranja") print(frutas) print(copia) otra_copia = frutas.copy() otra_copia.append("Fresa") otra_copia.append("Fresa") print(otra_copia)
false
e8a6b32c9e8b4db6b21de0fac5de2c7889261439
carlos-baraldi/python
/EstruturaSequencial/exercício11.py
689
4.375
4
'''Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre: o produto do dobro do primeiro com metade do segundo . a soma do triplo do primeiro com o terceiro. o terceiro elevado ao cubo.''' int1 = int(input('Digite um número inteiro: ')) int2 = int(input('Digite outro número inteiro: ')) real1 = float(input('Digite um número real: ')) resultado1 = (2 * int1) * (int2 / 2) resultado2 = (3*int1) + real1 resultado3 = real1 ** 3 print(f'o produto do dobro do primeiro com metade do segundo é igual a {resultado1}') print(f'a soma do triplo do primeiro com o terceiro é igual a {resultado2}') print(f'o terceiro elevado ao cubo é igual a {resultado3}')
false
9cc11f60ce5aa6e0ffcfbf92a5e7c3700227c008
djtoohey/Python-UniSA
/dice-poker/dice.py
1,995
4.15625
4
# # Dice Poker # Dice module - Assignment 1, sp2, 2019. # # Function display_hand to display the face value of dice to the screen. # This function takes a list of integers as a parameter (i.e. the values of the # five die to display) and displays the dice to the screen. # Parameters: List storing five die face values. # Returns: Nothing is returned from the function. def display_hand(hand, max_dice): # Display die number to the screen. print(format("", '<15s'), end='') for i in range(max_dice): print(format("Die " + str(i+1), '<10s'), end='') print() # Display face value of die to the screen. print(format("", '<16s'), end='') for i in range(max_dice): print(format("[" + str(hand[i]) + "]", '<10s'), end='') print() # Display the top row of face value to the screen. print(format("", '<16s'), end='') for i in range(max_dice): if hand[i] == 1: print(format(" ", '<10s'), end='') elif hand[i] == 2 or hand[i] == 3: print(format("*", '<10s'), end='') elif hand[i] == 4 or hand[i] == 5 or hand[i] == 6: print(format("* *", '<10s'), end='') print() # Display the middle row of face value to the screen. print(format("", '<16s'), end='') for i in range(max_dice): if hand[i] == 1 or hand[i] == 3 or hand[i] == 5: print(format(" *", '<10s'), end='') elif hand[i] == 6: print(format("* *", '<10s'), end='') else: print(format(" ", '<10s'), end='') print() # Display the bottom row of face value to the screen. print(format("", '<16s'), end='') for i in range(max_dice): if hand[i] == 1: print(format(" ", '<10s'), end='') elif hand[i] == 2 or hand[i] == 3: print(format(" *", '<10s'), end='') elif hand[i] == 4 or hand[i] == 5 or hand[i] == 6: print(format("* *", '<10s'), end='') print()
true
6bd804c66ccb6af058ac03be6eec0a41adc2d243
jccherry/Data-Structures-And-Algorithms
/04-Stacks, Heaps, Queues/Frank/r6_5.py
743
4.21875
4
''' R-6.5 Implement a function that reverses a list of elements by pushing them onto a stack in one order, and writing them back to the list in reversed order. ''' # STACK: LIFO class MyStack: def __init__(self): self._data = [] def push(self, item): self._data.append(item) def pop(self): return self._data.pop() def top(self): self._data[len(self._data) - 1] def __len__(self): return len(self._data) # ----------------------------------------- first_list = ['hello', ',', ' ', 'world', '!'] print("Starting list:", first_list) S = MyStack() for val in first_list: S.push(val) reversed_list = [S.pop() for _ in range(len(S))] print("Reversed list:", reversed_list)
true
2a3b32f248158f44455205864c8791ab0b117a94
jccherry/Data-Structures-And-Algorithms
/03-Dynamic Arrays, Linked Lists, Python List Implementation/Frank/c5_22.py
1,193
4.15625
4
''' C-5.22 Develop an experiment to compare the relative efficiency of the extend method of Python’s list class versus using repeated calls to append to accomplish the equivalent task. ''' # list.append(item) adds an object to the end of a list; if given a list it will add the list itself as an item # list.extend([items]) similarly adds objects to the end of a list but when passed an list unpacks it and adds each one import matplotlib.pyplot as plt import random import timeit # Items that will be added to empty list to_add = [None for _ in range(1000)] a = [] e = [] append_times = [] extend_times = [] def run(): start = timeit.default_timer() for val in to_add: a.append(val) append_times.append(timeit.default_timer() - start) start = timeit.default_timer() e.extend(to_add) extend_times.append(timeit.default_timer() - start) for _ in range(500): print("Run") run() plt.plot(append_times, color = 'orange', label = 'Append') plt.plot(extend_times, color = 'purple', label = 'Extend') plt.ylabel('Time') plt.xlabel('Run #') plt.legend() plt.show() ''' Extend clear performs much better than appending each item individually. '''
true
d06cd19ebe3e5a2b2f76f1f5b6cc3ae89c6f16a0
jccherry/Data-Structures-And-Algorithms
/07-Dictionaries/John/dict.py
929
4.4375
4
latin_dict = { "hello": "salve", "yes": "ita", "on": "in", "under": "sub", "father": "pater" } #this is the extent of my latin knowledge print(latin_dict["hello"]) for key in latin_dict: print(latin_dict[key]) #source for excercise: https://www.w3resource.com/python-exercises/dictionary/ ''' 3. Write a Python script to concatenate following dictionaries to create a new one. Go to the editor Sample Dictionary : dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60} Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} ''' dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60} new_dic = {} for entry in (dic1, dic2, dic3): new_dic.update(entry) print(str(new_dic)) #dict to store squares #theoretically good for much larger numbers where calculating the square could be resource intensive square_dict = {} for i in range(0,20000): square_dict[i] = i*i print(str(square_dict))
true
7abc6630e9d5f2d79b3f15c850aece0027a639be
msdepugh/test
/combinatorics.py
578
4.3125
4
''' Factorial Function Returns an integer value representing the factorial of a given positive integer input value. ''' def factorial(n): if (n <= 0 or n % 1 != 0): print "Incorrect input value" return -1 elif (n == 1): return 1 else: return (n * factorial(n - 1)) ''' Permutation - ordered, repititions Returns an integer value representing the total permutations of a set of 'N' elements with 'n' selections ''' def perm1 (N, n): if (N <= 0 or n <= 0 or n % 1 != 0 or N % 1 != 0):): print "Incorrect input value" return -1 else: return (N ** n)
true
12ee69728c8362190167efce4d200eebffb1973e
devangi2000/Data_Structures_and_Algorithms
/Coding Questions with Solutions/arrayAsHill.py
1,144
4.40625
4
/* Array of integers is a hill, if: it is strictly increasing in the beginning; after that it is constant; after that it is strictly decreasing. The first block (increasing) and the last block (decreasing) may be absent. It is allowed that both of this blocks are absent. For example, the following three arrays are a hill: [5, 7, 11, 11, 2, 1], [4, 4, 2], [7], but the following three are not unimodal: [5, 5, 6, 6, 1], [1, 2, 1, 2], [4, 5, 5, 6]. Write a program that checks if an array is a hill. Input Format The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000) — the elements of the array. Output Format Print "yes" if the given array is a hill. Otherwise, print "no". */ num = int(input()) arr = list(map(int, input().split())) i=0 while i<num-1 and arr[i]<arr[i+1]: i+=1 while i<num-1 and arr[i]==arr[i+1]: i+=1 while i<num-1 and arr[i]>arr[i+1]: i+=1 if(i==num-1): print('yes') else: print('no')
true
4d621a1bc20479feed847a714d48b6fd8eb42a6c
hankerbiao/python-Demo
/初学python Demo/数据结构_!.py
1,032
4.125
4
# -*- coding: cp936 -*- #ݽṹ: ջ #ʲôջݽṹϵͳԴģ ջ൱һο һηյ #pythonջʵ 洢ʽe """ class Stack(): def __init__(st,size): #__init__ʼ st.stack=[]; #st. ջ б st.size=size; #涨ջ ֵ st.size st.top=-1; #ʼջλ #ջ def push(st,content): if st.Full(): print "zhan man le " else: st.stack.append(content) st.top=st.top+1 def out(st): #ջ if st.Empty(): print "zhan kong le" else: st.top=st.top-1 def Full(st): if st.top ==st.size: return True else: return False def Empty(st): if st.top==-1: return True else: return False #ջ """ #
false
5949124f9273ad430d50f684b8d6ba6e9a0eec9c
cvasani/SparkLearning
/Input/Notes/python_course/booleans_and_conditionals/practice_exercises/solution_01.py
457
4.6875
5
#!/usr/bin/env python3 # Ask for the distance. distance = input('How far would you like to travel in miles? ') # Convert the distance to an integer. distance = int(distance) # Determine what mode of transport to use. if distance < 3: mode_of_transport = 'walking' elif distance < 300: mode_of_transport = 'driving' else: mode_of_transport = 'flying' # Display the result. print('I suggest {} to your destination.'.format(mode_of_transport))
true
65c42525a44c5fadda2e72d8e2ed2ccce8fb9121
Deeps-01/DSA
/algorithms/Python/recursion/recursive_insertion_sort.py
749
4.34375
4
""" Base Case: If array size is 1 or smaller, return. Recursively sort first n-1 elements. Insert last element at its correct position in sorted array. """ def insertionSort_rec(array, n): # base case if n <= 1: return # Sort first n-1 elements insertionSort_rec(array, n-1) '''Insert last element at its correct position in sorted array.''' end = array[n-1] j = n-2 # Move elements of arr[0..i-1], that are # greater than key, to one position ahead # of their current position while (j >= 0 and array[j] > end): array[j+1] = array[j] j -= 1 array[j+1] = end arr = [6, 5, 2, 7, 12, 9, 1, 4] insertionSort_rec(arr, len(arr)) print("Sorted array is:") print(arr)
true
50edfc5352d7bb14b5f49cf249fcdee7ad0ae2d7
pranavsnair2000/lecture-3-response
/5.py
201
4.625
5
#5. Write a Python program to check if a string is numeric string=input("Enter string to check if it's numeric : ") if(string.isnumeric()): print("It is numeric") else: print("not numeric")
true
9da7b92c21e291f431e006147c0243d651cea959
BethMwangi/bc-9-tdd
/TDD/super_sum/super_sum.py
739
4.40625
4
def super_sum(*args): ''' Takes in elements in a list and returns total sum ''' total = 0 #initialize the total for elements in a list float_num = 0.0 for element in args: # loops through each element passed if isinstance(element,list): #test if the element is a list for i in element: if isinstance(i, int): total = i + total # adds the elements in an individual list elif isinstance(i, float): float_num = i + float_num else: return ' You have entered a non integer' else: if type(element) is int: #test if the element passed is an integer total += element else: return 'you entered a non integer item' super_sum = float_num + total return super_sum
true
821fb239a95779c61521885e854ddddb90824653
fKEpro/demo
/demoxx/demo3.py
1,081
4.53125
5
import sys # Used for the sys.exit function target_int = input("How many integers? ") try: target_int = int(target_int) except ValueError: sys.exit("You must enter an integer") ints = list() count = 0 # Keep asking for an integer until we have the required number while count < target_int: new_int = input("Please enter integer {0}: ".format(count + 1)) isint = False try: new_int = int(new_int) except: print("You must enter an integer") # Only carry on if we have an integer. If not, we’ll loop again # Notice below I use ==, which is diff erent from =. The single equals is an # assignment operator whereas the double equals is a comparison operator. if isint == True: # Add the integer to the collection ints.append(new_int) # Increment the count by 1 count += 1 print("Using a for loop") for value in ints: print(str(value)) # Or with a while loop: print("Using a while loop") # We already have the total above, but knowing the len function is very # useful. total = len(ints) count = 0 while count < total: print(str(ints[count])) count += 1
true
08e81ee6a186f96505e50037938e46716d5eb254
helarctos/python
/travillian-challenge.py
1,182
4.34375
4
# helper function: summation def summation(array1): # summation receives an array passed to it by another function sum = 0 # initialize sum for i in range(len(array1)): # go through all the elements of the array one by one sum = sum + array1[i] # add current element to sum for comulative total return sum # when the loop through the array is finished, the function returns the cumulative total # main routine numbers = [0,0,0,0,0,0,0,0,0,0] # create array, initialize all elements in array to 0 element = 0 # initialize element for i in range(10): # loop through array one element at a time element = element + 1 # increment element numbers[i] = element # set current element of array equal to current value of element # print(numbers) # testing step to check that array is set correctly print "The sum of the numbers in the array is ",summation(numbers), "." # pass array to summation function to get cumulative sum of its elements
true
9094ba83af0b8b01e85ca4f4453f76d49ecd6bb4
bradleyshawkins/PythonLinkedList
/LinkedList.py
1,466
4.21875
4
class LinkedList(object): """LinkedList""" root = None nodelist = {} def addnode(self, node): """Adds a node to the linked list""" if self.root is None: self.root = node elif self.root.value_ > node.value_: node.setnextnode(self.root) self.root = node else: curnode = self.root while curnode.getnextnode() is not None and node.value_ > curnode.getnextnode().value_: curnode = curnode.getnextnode() curnode.setnextnode(node) self.nodelist[node.id_] = node def removenode(self, nodeid): """Removes a node from the linked list""" if self.root.id_ == nodeid: self.root = self.root.getnextnode() else: curnode = self.root while curnode.getnextnode().id_ != nodeid: curnode = curnode.getnextnode() curnode.removenextnode() del self.nodelist[nodeid] def getnode(self, nodeid): """Retrives the node based on the id""" return self.nodelist[nodeid] def getroot(self): """Returns the root of the list""" return self.root def printallnodes(self): """Prints all of the nodes in the linked list""" curnode = self.root while curnode != None: print "Value: {} Id: {}".format(curnode.value_, curnode.id_) curnode = curnode.getnextnode()
true
f68ca8d79795cb59768f1075697e4ad4bbf3dc0f
fernandochimi/Intro_Python
/Exercícios/103_Pesquisa_String_4.py
249
4.34375
4
string1 = "CTA" string2 = "ABC" string3 = "" for letra in string1: if letra not in string2 and letra not in string3: string3+=letra for letra in string2: if letra not in string1 and letra not in string3: string3+=letra print("%s" % string3)
true
bf2c511af6e6597c58f0c5acf8fd8e76a8b2972f
diegoshakan/curso-em-video-python
/Desafio08.py
410
4.15625
4
'''Escreva um programa que leia um valor em metros e mostre em centímetros e milímetros.''' m = float(input('Digite o valor em metros: ')) #km = m * 0.001 #hm = m * 0.01 #dam = m * 0.1 #dm = m * 10 cm = m * 100 mm = m * 1000 #print('{:.0f}km'.format(km)) #print('{:.0f}hm'.format(hm)) #print('{:.0f}dam'.format(dam)) #print('{:.0f}dm'.format(dm)) print('{:.0f}cm'.format(cm)) print('{:.0f}mm'.format(mm))
false
5d272ceb8ca9add6c3c65b123d543ab9fcd771c6
diegoshakan/curso-em-video-python
/Desafio37M02.py
491
4.15625
4
'''Escreva um programa que leia um número inteiro e peça para o usuário escolher qual será a base de conversão. 1 - Binário 2 - Octal 3 - Hexadecimal''' cod = int(input('Escolha um número para realizar a conversão: 1 - Binário, 2 - Octal ou 3 - Hexadecimal: ')) num = int(input('Qual número inteiro você quer converter: ')) if cod == 1: print(bin(num)[2:]) elif cod == 2: print(oct(num)[2:]) elif cod == 3: print(hex(num)[2:]) else: print('Código inexistente!')
false
f99a151a59d7b88c6f91864af8fb553655c3d286
diegoshakan/curso-em-video-python
/Desafio22.py
1,132
4.46875
4
#Desafio 22 - Gustavo Guanabara '''Crie um programa que leia o nome completo de uma pessoa e mostre: a) O nome com todas as letras maiúsculas: b) O nome com todas minúsculas: c) Quantas letras ao todo sem considerar o espaço: d) Quantas letras tem o primeiro nome:''' #a) nome = input('Escreva seu nome: ') nome = nome.upper() #Aqui ele deixa tudo maiúsculo print(nome) #b) nome = input('Escreva seu nome: ') nome = nome.lower() #Aqui ele deixa tudo minúsculo. print(nome) #c) nome = input('Escreva seu nome: ').strip() #.strip serve para retirar todos os espaços antes e/ou após a string. nome1 = nome.count(' ') #aqui ele conta qnts espaços há na frase em outra variável. nome = len(nome) - nome1 #Aqui ele calcula a qntd de caracteres e diminui pela qntd de espaços, dando o total de letras apenas. print('Seu nome completo tem {} letras'.format(nome)) #aqui ele imprime o nome formatado com o cálculo. #d) nome = input('Escreva seu nome: ') nome = nome.split() #aqui separa o nome completo nome = len(nome[0]) #aqui confere quantas letras há no primeiro nome somente. print('Seu primeiro nome tem {} letras'.format(nome))
false
e6309205fd27ec59a8d800fbf2a7bcca12000be4
UCBAIR/decaf-release
/decaf/util/timer.py
2,260
4.34375
4
"""Implement a timer that can be used to easily record time.""" import time class Timer(object): """Timer implements some sugar functions that works like a stopwatch. timer.reset() resets the watch timer.lap() returns the time elapsed since the last lap() call timer.total() returns the total time elapsed since the last reset """ def __init__(self, template = '{0}h{1}m{2:.2f}s'): """Initializes a timer. Input: template: (optional) a template string that can be used to format the timer. Inside the string, use {0} to denote the hour, {1} to denote the minute, and {2} to denote the seconds. Default '{0}h{1}m{2:.2f}s' """ self._total = time.time() self._lap = time.time() if template: self._template = template def _format(self, timeval): """format the time value according to the template """ hour = int(timeval / 3600.0) timeval = timeval % 3600.0 minute = int (timeval / 60) timeval = timeval % 60 return self._template.format(hour, minute, timeval) def reset(self): """Press the reset button on the timer """ self._total = time.time() self._lap = time.time() def lap(self, use_template = True): """Report the elapsed time of the current lap, and start counting the next lap. Input: use_template: (optional) if True, returns the time as a formatted string. Otherwise, return the real-valued time. Default True. """ diff = time.time() - self._lap self._lap = time.time() if use_template: return self._format(diff) else: return diff def total(self, use_template = True): """Report the total elapsed time of the timer. Input: use_template: (optional) if True, returns the time as a formatted string. Otherwise, return the real-valued time. Default True. """ if use_template: return self._format(time.time() - self._total) else: return time.time() - self._total
true
d693535d141ebb399f755a9484bda2fce0d48e3a
megrao/Binary-Search-1
/Binary search1_Exercise_2.py
1,669
4.125
4
# Binary search - 1 // Time Complexity : O(log N) ?? // Space Complexity : O(1) constant time complexity? // Did this code successfully run on Leetcode : No link. NOT giving result in jupyter notebook. // Any problem you faced while coding this : Not sure of time and space complexity // Your code here along with comments explaining your approach - 1. Define a function for binary search with start index, end index. 2. Use a while loop. Calculate the middle index (ensure it doesn't go beyond the bounds). 3. If middle is the target, return the same. 4. If number in left of middle, shift bounds to left-hand side (end is shifted). Else, shift it to right-hand side (start to middle +1). 5. To determine bounds with an array of size def binarySearch_function(nums,start,end,target): while start <= end: middle = start+(end-start)//2 if nums[middle] == target: return middle elif nums[middle] > target: #return binarySearch_function(nums,start,middle-1,target) end = middle-1 continue else: #return binarySearch_function(nums,middle+1,end, target) start = middle+1 continue return -1 def locate(nums, target): size, initial_value = 1, nums[0] while initial_value < target: left = size # store previous cycle's right right = 2*size # consider double size return binarySearch_function(nums, left, right,target) initial_value = arr[left] # update value and size for next cycle size = right locate([1,2,3,4,5,6,6,7,8], 1)
true