blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
1c53c34020a44ea95474c71168179987913b4bcd
lvncnt/Leetcode-OJ
/Dynamic-Programming/python/Unique-Paths.py
1,069
4.1875
4
""" Problem: A robot is located at the top-left corner of a m x n grid. The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? Note: m and n will be at most 100. """ # 1. No obstacles def uniquePaths(m, n): # Bottom-up DP matrix = [[0]*(n + 1) for i in range(m + 1)] matrix[m - 1][n] = 1 for i in range(m-1,-1,-1): for j in range(n-1,-1,-1): matrix[i][j] = matrix[i+1][j]+matrix[i][j+1] return matrix[0][0] # 2. Some obstacles are added to the grids. # An obstacle and empty space is marked as 1 and 0 respectively in the grid. def uniquePathsWithObstacles(obstacleGrid): # Bottom-up DP m = len(obstacleGrid) n = len(obstacleGrid[0]) matrix = [[n+1] for i in range(m+1)] matrix[m-1][n] = 1 for i in range(m-1,-1,-1): for j in range(n-1,-1,-1): matrix[i][j]=0 if obstacleGrid[i][j] == 1 else matrix[i+1][j]+matrix[i][j+1] return matrix[0][0]
true
782bd10d6cad1e6f4893e311078968e191bc236b
dktlee/university_projects
/intro_to_comp_sci_in_python/bar_chart.py
2,705
4.53125
5
## ## Dylan Lee ## Introduction to Computer Science (2015) ## # bar_label_length(data, max_label_length, index) produces the length # of the largest bar label that will be created from data, which is # max_bar_length, by checking to see if the label in data at index is bigger # than the max_bar_length so far # requires: the format of data will always have an even number of elements # where a bar label string is followed by a natural number for the # bar length # first call of index is 0 def bar_label_length(data, max_label_length, index): if index >= len(data): return max_label_length elif len(data[index]) > max_label_length: return bar_label_length(data, len(data[index]), index+2) else: return bar_label_length(data, max_label_length, index+2) # chart_acc(data, label_index, length_index, max_bar_label) prints # out a bar chart horizontally with bar labels named from the string in data # at label_index with a bar length of the integer at length_index in data # formated so that the bar label is right alinged according to the # max_bar_label # requires: the format of data will always have an even number of elements # where a bar label string is followed by a natural number for the # bar length # first call of label_index is 0 # first call of length_index is 1 def chart_acc(data, label_index, length_index, max_bar_label): if not(label_index >= len(data)): label = "|" + " "*(max_bar_label - len(data[label_index])-1) \ + data[label_index] + " |" print(label + "#"*data[length_index]) chart_acc(data, label_index + 2, length_index+2, max_bar_label) # chart(data) consumes a list called data and prints out a bar chart # horizontally using text and symbols to draw the display # effects: prints the data labels from data along with #'s representing # the bars bars # requires: the format of data will always have an even number of elements # where a bar label string is followed by a natural number for the # bar length # Examples # calling chart(["VW", 20, "Ford", 18, "Subaru", 3, # "Mercedes", 7, "Fiat", 2]) prints: #| VW |#################### #| Ford |################## #| Subaru |### #| Mercedes |####### #| Fiat |## # calling chart(["Rose", 1, "Lebron", 6, "Lowry", 7, "Kobe", 24, "Durant", 35]) prints: #| Rose |# #| Lebron |###### #| Lowry |####### #| Kobe |######################## #| Durant |################################### def chart(data): max_bar_label = bar_label_length(data, len(data[0]), 0) + 2 chart_acc(data, 0, 1, max_bar_label)
true
e7953f05fcd5ee001e04a473e1ed6b315c9a304e
akhitab-acharya/Mchine-learning
/Python.py
1,981
4.34375
4
ERROR: type should be string, got "https://cs231n.github.io/python-numpy-tutorial/\nPython & Numpy Tutorial by Stanford - It's really great and covers things from the ground up.\n\n#Quicksort\n\ndef quicksort(arr):\n if len(arr) <= 1:\n return arr\n pivot = arr[len(arr) // 2]\n left = [x for x in arr if x < pivot]\n middle = [x for x in arr if x == pivot]\n right = [x for x in arr if x > pivot]\n return quicksort(left) + middle + quicksort(right)\n\nprint(quicksort([3,6,8,10,1,2,1]))\n\n\n# Prints \"[1, 1, 2, 3, 6, 8, 10]\"\n\n-----------------------------------------\n\n#LIST COMPREHENSION:\n\nnums = [1, 2, 3, 4]\nnum_squares = [x**2 for x in nums]\nprint(num_squares)\n\n\n# list comprehension with conditions:\n\nnum_even_square = [x**2 for x in nums if x % 2 == 0]\nprint(num_even_square)\n\n------------------------------------------------------------\n\n# DICTIONARY COMPREHENSION:\n\nnums = [0, 1, 2, 3, 4]\neven_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}\nprint(even_num_to_square) # Prints \"{0: 0, 2: 4, 4: 16}\"\n\n--------------------------------------------------------------------------------------\ns = \"hello\"\nprint(s.capitalize()) # Capitalize a string; prints \"Hello\"\nprint(s.upper()) # Convert a string to uppercase; prints \"HELLO\"\nprint(s.rjust(7)) # Right-justify a string, padding with spaces; prints \" hello\"\nprint(s.center(7)) # Center a string, padding with spaces; prints \" hello \"\nprint(s.replace('l', '(ell)')) # Replace all instances of one substring with another;\n # prints \"he(ell)(ell)o\"\nprint(' world '.strip()) # Strip leading and trailing whitespace; prints \"world\"\n------------------------------------------------------------------------------------------\n\n# EX. OF ENUMERATE:\n\nanimals = {'cat', 'dog', 'cow'}\nfor idx, animal in enumerate(animals):\n print('#%d %s' % (idx + 1, animal))\n\n# Prints \"#1: cat\", \"#2: dog\", \"#3: monkey\", each on its own line\n\n-------------------------------------------------------------------\n\n\n"
true
320fec5ea73f27447974d41dbcf7b80251e4bc88
Viheershah12/python-
/Practice_Projects/odd-even.py
656
4.21875
4
num = int(input("Enter a number of your choice: ")) check = 2 dev = num % 2 if dev > 0: print("The number ",num," is a odd number") else: print("The number ",num," is a even number") # more complex function to see if the number is divisible by 4 num = int(input("give me a number to check: ")) check = int(input("give me a number to divide by: ")) if num % 4 == 0: print(num, "is a multiple of 4") elif num % 2 == 0: print(num, "is an even number") else: print(num, "is an odd number") if num % check == 0: print(num, "divides evenly by", check) else: print(num, "does not divide evenly by", check) input("Enter to exit")
true
9cbbed20321eab76d4f326fc164df529b8b64b88
Viheershah12/python-
/FutureLearn/conditional/IFSTATEMENTS.py
295
4.34375
4
x = 5 if x == 5: print("this number is ",x) else: print("this number is not",x) if x > 5 : print("this number is greater than ",x) else: print("this number is less than or equal to ",x) if x != 5: print("this number is not equal to ",x) else: print("this number is ",x)
true
a88fa735ad3cccfca126e03b4005848c88fd569d
Viheershah12/python-
/Lessons/calculatorfunc.py
371
4.25
4
#define a function to return the square of a given number #define anathor function to add up the numbers #use the functions created to solve the equation # x = a + b^2 def add(x,y): return x + y def square(x): return x * x num1 = int(input("Enter number 1: ")) num2 = int(input("Enter number 2: ")) x = add(num1 , square(num2)) print(x) input("Enter to exit")
true
a1342fca4f28ec604cc73abfc1e7372ed1eb86c9
vamotest/yandex_algorithms
/12_01_typical_interview_tasks/E. Convert to binary system.py
273
4.1875
4
def binary_convert(number): binary_number = '' while number > 0: binary_number = str(number % 2) + binary_number number = number // 2 return binary_number if __name__ == '__main__': binary = binary_convert(int(input())) print(binary)
false
54af20a4223a7fce77f976c6063056318656c59a
vamotest/yandex_algorithms
/12_01_typical_interview_tasks/L. Extra letter.py
427
4.125
4
from itertools import zip_longest def define_anagrams(first, second): li = list(zip_longest(first, second)) for letter in li: if letter[0] != letter[1]: return letter[1] if __name__ == '__main__': first_word = ''.join(sorted(list(str(input())))) second_word = ''.join(sorted(list(str(input())))) result = define_anagrams(first_word, second_word) print(result)
true
414441654abcc71a08ba8a04f1d38f17f5c26184
mtavecchio/Other_Primer
/Python/lab4/circle.py
1,075
4.40625
4
#!/usr/local/bin/python3 #FILE: circle.py #DESC: A circle class that subclasses Shape, with is_collision(), distance(), and __str__() methods from shape import Shape from math import sqrt class Circle(Shape): """Circle Class: inherits from Shape and has method area""" pi = 3.14159 def __init__(self, r = 1, x = 0, y = 0): Shape.__init__(self, x, y) self.radius = r def area(self): """Circle area method: returns the area of the circle.""" return self.radius * self.radius * self.pi def __str__(self): return "Circle of radius {:.0f} at coordinate ({:.0f}, {:.0f})"\ .format(self.radius, self.x, self.y) @classmethod def distance(Circle, c1, c2): '''calculate distance between two circle''' circ_distance = sqrt(c1.x**2 + c2.x**2) return circ_distance @classmethod def is_collision(Circle, c1, c2): '''Return True or None''' if c2.radius > (c2.distance(c1, c2) - c1.radius): return True else: return None
true
1a468b1e78271d168daf89fadb04ea212bd91b50
foobar167/junkyard
/simple_scripts/longest_increasing_subsequence.py
2,000
4.25
4
l = [3,4,5,9,8,1,2,7,7,7,7,7,7,7,6,0,1] empty = [] one = [1] two = [2,1] three = [1,0,2,3] tricky = [1,2,3,0,-2,-1] ring = [3,4,5,0,1,2] internal = [9,1,2,3,4,5,0] # consider your list as a ring, continuous and infinite def longest_increasing_subsequence(l): length = len(l) if length == 0: return 0 # list is empty i, tmp, longest = [0, 1, 1] # 1 < tmp means that ring is finished, but the sequence continue to increase while i < length or 1 < tmp: # compare elements on the ring if l[i%length] < l[(i+1)%length]: tmp += 1 else: if longest < tmp: longest = tmp tmp = 1 i += 1 return longest print("0 == " + str(longest_increasing_subsequence(empty))) print("1 == " + str(longest_increasing_subsequence(one))) print("2 == " + str(longest_increasing_subsequence(two))) print("3 == " + str(longest_increasing_subsequence(three))) print("5 == " + str(longest_increasing_subsequence(tricky))) print("5 == " + str(longest_increasing_subsequence(internal))) print("6 == " + str(longest_increasing_subsequence(ring))) print("6 == " + str(longest_increasing_subsequence(l))) def longest_increasing_subsequence2(l): if len(l) == 0: return 0 # list is empty lst = l + l length = len(lst) #print(lst) i, tmp, longest = [0, 1, 1] for i in range(length-1): if lst[i] < lst[i+1]: tmp += 1 else: if longest < tmp: longest = tmp tmp = 1 return longest print("0 == " + str(longest_increasing_subsequence2(empty))) print("1 == " + str(longest_increasing_subsequence2(one))) print("2 == " + str(longest_increasing_subsequence2(two))) print("3 == " + str(longest_increasing_subsequence2(three))) print("5 == " + str(longest_increasing_subsequence2(tricky))) print("5 == " + str(longest_increasing_subsequence2(internal))) print("6 == " + str(longest_increasing_subsequence2(ring))) print("6 == " + str(longest_increasing_subsequence2(l)))
true
7554a545e73e15f55208072f9e28dc3d10bb53ee
MaxwellGBrown/tom_swift
/tom_swift.py
1,895
4.1875
4
"""Trigrams application to mutate text into new, surreal, forms. http://codekata.com/kata/kata14-tom-swift-under-the-milkwood/ """ from collections import defaultdict import random def read_trigrams(text): """Return a trigrams dictionary from text.""" trigrams = defaultdict(list) split_text = text.split(" ") while len(split_text) >= 3: first, second, third, *rest = split_text trigrams[(first, second)].append(third) split_text = split_text[1:] return trigrams def _same_order(trigram): """Yield items in the same order they were read from. This should create a result equal to the original text. """ keys = [k for k in trigram.keys()] # keys are ordered since 3.6 seed = [*keys[0]] yield from (item for item in seed) while any(v for v in trigram.values()): value = trigram[(seed[-2], seed[-1])].pop(0) yield value seed = [seed[-1], value] def _random(trigram): """Compose a trigram in the random order.""" keys = [k for k in trigram.keys()] # keys are ordered since 3.6 seed = [*random.choice(keys)] yield from (item for item in seed) while any(v for v in trigram.values()): key = (seed[-2], seed[-1]) upper_bound = len(trigram[key]) if upper_bound < 1: break elif upper_bound == 1: index = 0 else: index = random.randint(0, upper_bound - 1) value = trigram[key].pop(index) yield value seed = [seed[-1], value] def compose_text(trigram, algorithm=_random): """Compose text given a trigram.""" items = [i for i in algorithm(trigram)] return " ".join(items) def main(text="I wish I may I wish I might"): """Execute the trigram.""" trigrams = read_trigrams(text) print(compose_text(trigrams)) if __name__ == "__main__": main()
true
b96368a791ee9de9a605eee3634de0482ad08643
ashwani99/dgplug-python-exercises
/4-pick-fruits-from-basket/solution.py
315
4.1875
4
"""Given a list basket = ["apple", "banana", "pineapple", "mango"] pick out the fruits whose name starts with a vowel.""" basket = ["apple", "banana", "pineapple", "mango"] print('Fruits whose name start with a vowel are:') for fruit in basket: if fruit[0] in ('a', 'e', 'i', 'o', 'u'): print(fruit)
false
a672c36493d46e20be291214640e0fbe11f2162f
Devfasttt/Tkinker
/Positioning With Tkinter's Grid System.py
469
4.375
4
#import tkinter from tkinter import * #main window root=Tk() #create a label widget myLabel1=Label(root, text="hello i am a good, really good person")#.grid(row=0, column=0) myLabel2=Label(root, text="Who are you?")#.grid(row=3, column=7) myLabel3=Label(root, text=" ")#.grid(row=8, column=5) #shoving it on the screen myLabel1.grid(row=0, column=0) myLabel2.grid(row=1, column=7) myLabel3.grid(row=3, column=5) #Call the main loop root.mainloop()
true
527fc33c42c57314783a3c73ba753bc37cde9a36
vishaltanwar96/DSA
/problems/mathematics/integer_to_roman.py
1,698
4.375
4
def int_to_roman(num: int) -> str: """ number is represented as its place value i.e. 5469 = 5000 + 400 + 60 + 9 Conversion is supported till 9999. A helper hashmap is needed to map values to a string representation of that number in roman. For converting a number to roman number we follow a simple stategy. We extract each digit from the number and mulitply with its 10^multiplier. if the number is directly present in map we return it otherwise we check if the extracted digit lies between 9 and 5 if so we simply subtract 5 from it and if anything is remaining (1, 2, 3) we simply prepend multiplier * number_string_roman else we append multiplier * number_string_roman. """ number_roman_string_map = { 1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L', 90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M' } multiplier = 0 roman_number = '' while num > 0: face_value = num % 10 place_value = face_value * (10 ** multiplier) if place_value in number_roman_string_map: roman_number = number_roman_string_map[place_value] + roman_number elif 5 < face_value < 9: leftover = face_value - 5 roman_number = number_roman_string_map[10 ** multiplier] * leftover + roman_number roman_number = number_roman_string_map[5 * (10 ** multiplier)] + roman_number else: roman_number = number_roman_string_map[10 ** multiplier] * face_value + roman_number num //= 10 multiplier += 1 return roman_number
true
872fa237b31821e8cc70700017314d2273a9ea9f
jaejun1679-cmis/jaejun1679-cmis-cs2
/startotend.py
946
4.15625
4
import time def find(start, end, attempt): if start > end: countdownfrom(start, end, attempt) elif end > start: countupfrom(start, end, attempt) def countdownfrom(start, end, attempt): if start == end: print "We made it to " + str(end) + "!" else: time.sleep(1) if attempt == 0: print start print start - 1 attempt = attempt + 1 countdownfrom((start - 1), end, attempt) def countupfrom(start, end, attempt): if start == end: print "We made it to " + str(start) + "!" else: time.sleep(1) if attempt == 0: print start print start + 1 attempt = attempt + 1 countupfrom((start + 1), end, attempt) def main(): start = float(raw_input("Insert the starting number: ")) end = float(raw_input("Insert the ending number: ")) attempt = 0 find(start, end, attempt) main()
true
f93622696104e20e2079975a9cd6b98ce5a75a2d
gk90731/100-questions-practice
/16.py
234
4.25
4
#Please complete the script so that it prints out the value of key b . #d = {"a": 1, "b": 2} #Expected output: 2 d = {"a": 1, "b": 2} print(d["b"]) # lists have indexes, while dictionaries have keys which you create by yourself.
true
07d6bdf68d139c030ecb46a0a789146621671217
matttu120/Python
/HackerRank/WhatsYourName.py
724
4.1875
4
''' Problem Statement Let's learn the basics of Python! You are given the first name and the last name of a person. Your task is to read them and print the following: Hello firstname lastname! You just delved into python. It's that simple! In Python you can read a line as a string using s = raw_input() #here s reads the whole line. Input Format The first line contains the first name, and the second line contains the last name. Constraints The length of the first and last name ≤ 10. Output Format Print the output as mentioned above. '''# Enter your code here. Read input from STDIN. Print output to STDOUT s1 = raw_input() s2 = raw_input() print "Hello " + s1 + " " + s2 + "! You just delved into python."
true
ff0ffeeacbb85ffa4b38a14951aa7856a8baba1c
jmizquierdovaldes/hwtest
/Basico2.py
2,203
4.53125
5
# Se utiliza para comentarios #Crear un string #Se puede crear sting con comillas dobles o simples. El programa es sensible a #el uso de mayusculas "Hello Word" 'Hola Mundo' print("Hello Word") print('Hola Mundo') #Para saber que tipo de dato se utiliza el comando type #Va a entregar como salida class string ya qie se trata de un codigo en string print(type('Tipo de escritura')) #Como lograr unir 2 string #Se utiliza el comando + para producir la concatenacion pero lo va a pegar junto print("Bye"+"World") #Utilizacion de numeros print(30) #tipo de dato entero int print(type(30)) #Los decimales se les conoce como los floats print(type(30.8)) #Variables de estado, logico Boolean a = True b = False #El resultado del tipo de variable es bool print(type(a)) print(type(b)) #Datos de tipo de listas de datos List #El separador de coma es para que entienda los datos como independientes #dentro de la lista, se definien entre parentesis c = [10, 20, 30, 55] #En la lista se puede incluir cualquier tipo de variables d = ["Hola", 20, True, 30.5] #El resultado por tupo de lista es un list print(type(d)) #Agrupacion de datos en tuplas, datos que no cambian Tuples #Las tuplas no pueden cambiarse asi se definieron para siempre #Se utilizan como variables parentesis en vez de corchetes de la lista e = (10, 20, 30, 55) #El tipo de variable de las tuplas es tuple print(type(e)) #Variables de tipo diccionario. Agrupar datos de la misma identidad #Se utilizan en formato entre llaves, se separan las unidades de informacion #por comas f = { "Jose", "Izquierdo", "Jote" } print(f) #Para identificar que tipo de informacion se anade los 2 puntos #Concepto de clave/key =nombre, valor/value=Jose g = { "nombre": "Jose", "apellido": "Izquierdo", "apodo": "Jote" } print(g) #Ejemplo de diccionario mezclando tipos de variables h = { "latitud": 123.45, "longitud": 35.78 } print(h) #Tipo de variable diccionario dict print(type(h)) #Definicion de variables #Se pueden definir un grupo de variables en una sola linea de codigo si se #separan entre comas i, j = "Jose", 1979 #La impresion se puede dejar en una sola linea print(i, j)
false
eb9f909b5f7c13edf72d05b8554dd8608f21acd7
Eliacim/Checkio.org
/Python/Home/Sun-angle.py
1,503
4.46875
4
''' https://py.checkio.org/en/mission/sun-angle/ Every true traveler must know how to do 3 things: fix the fire, find the water and extract useful information from the nature around him. Programming won't help you with the fire and water, but when it comes to the information extraction - it might be just the thing you need. Your task is to find the angle of the sun above the horizon knowing the time of the day. Input data: the sun rises in the East at 6:00 AM, which corresponds to the angle of 0 degrees. At 12:00 PM the sun reaches its zenith, which means that the angle equals 90 degrees. 6:00 PM is the time of the sunset so the angle is 180 degrees. If the input will be the time of the night (before 6:00 AM or after 6:00 PM), your function should return - "I don't see the sun!". example Input: The time of the day. Output: The angle of the sun, rounded to 2 decimal places. Precondition: 00:00 <= time <= 23:59 ''' def sun_angle(time): h, m = time.split(':') angle = ((int(h) - 6) * 60 + int(m)) * (180 / 720) return "I don't see the sun!" if angle < 0 or angle > 180 else angle if __name__ == '__main__': print("Example:") print(sun_angle("07:00")) print(sun_angle("01:23")) print(sun_angle("18:01")) # These "asserts" using only for self-checking and not necessary for # auto-testing assert sun_angle("07:00") == 15 assert sun_angle("01:23") == "I don't see the sun!" print("Coding complete? Click 'Check' to earn cool rewards!")
true
3baebfc0fe2aa3a56263a967dcb288b2fd88b6da
Eliacim/Checkio.org
/Python/Electronic-Station/All-upper-ii.py
769
4.5
4
''' https://py.checkio.org/en/mission/all-upper-ii/ Check if a given string has all symbols in upper case. If the string is empty or doesn't have any letter in it - function should return False. Input: A string. Output: a boolean. Precondition: a-z, A-Z, 1-9 and spaces ''' def is_all_upper(text: str) -> bool: return True if text.strip() and text == text.upper()\ and not text.isdigit() else False if __name__ == '__main__': print("Example:") print(is_all_upper('ALL UPPER')) # These "asserts" are used for self-checking and not for an auto-testing assert is_all_upper('ALL UPPER') is True assert is_all_upper('all lower') is False assert is_all_upper('mixed UPPER and lower') is False assert is_all_upper('') is False
true
59c8a0575f9a59348cfcb6a0fb8029f9c3b32366
Eliacim/Checkio.org
/Python/Mine/Fizz-buzz.py
1,125
4.46875
4
''' https://py.checkio.org/en/mission/fizz-buzz/ Fizz Buzz Elementary "Fizz buzz" is a word game we will use to teach the robots about division. Let's learn computers. You should write a function that will receive a positive integer and return: "Fizz Buzz" if the number is divisible by 3 and by 5; "Fizz" if the number is divisible by 3; "Buzz" if the number is divisible by 5; The number as a string for other cases. Input: A number as an integer. Output: The answer as a string. Example: checkio(15) == "Fizz Buzz" checkio(6) == "Fizz" checkio(5) == "Buzz" checkio(7) == "7" Precondition: 0 < number ≤ 1000 ''' def checkio(number: int) -> str: return 'Fizz Buzz' if number % 15 == 0 else 'Buzz' if number % 5 == 0\ else 'Fizz' if number % 3 == 0 else str(number) if __name__ == '__main__': print('Example:') print(checkio(15)) print(checkio(7)) assert checkio(15) == "Fizz Buzz", "15 is divisible by 3 and 5" assert checkio(6) == "Fizz", "6 is divisible by 3" assert checkio(5) == "Buzz", "5 is divisible by 5" assert checkio(7) == "7", "7 is not divisible by 3 or 5"
true
b8b26c1d753a8c1511d2243bb31a373790e6ce0a
ITorres20/week2-hello-world
/helloworld.py
626
4.46875
4
#Ivetteliz Torres # this program is suppose to display the hello world greeting in three different languages language1= 'Hola Mundo!' language2= 'Ola Mundo!' language3= 'Bonjour le monde!' print 'Hello World!' # greeting print 'Please select one of the following languages.' # ask the user for language selection #language selections print '1.Spanish' print '2.Portuguese' print '3.French' lang =input() # from here on is where im having difficulty I dont know what im doing wrong,Please advise if lang='1' ans=language1 print(language1) if lang='2' ans=language2 print(language2) if lang='3' ans=language3 print(language3)
true
ee36f0aec25efa6feee970b78f9abc5195d15f68
zsx29/python
/Ch04/4_3_Set.py
543
4.1875
4
""" 날짜 : 2021/04/27 이름 : 박재형 내용 : 파이썬 자료구조 Set 실습 교재 p96 """ # Set = 집합주머니, 순서X, 중복X # Set 생성 # set1 = {1, 2, 3, 4, 5, 3} print(type(set1)) print(set1) # 3은 중복값이라 출력되지 않음. set2 = set("hello world!") print(type(set1)) print(set2) # 개별적인 문자로 출력, 스페이스도 문자로 취급 = " ", 순서도 없음 # Set 출력 = List 변환 후 출력 # list1 = list(set1) print(list1) list2 = list(set2) print(list2)
false
95386897bf9f6d390f26631923c86c1feef34507
zsx29/python
/Book/Exam_2/ex2_7.py
893
4.40625
4
""" 날짜 : 2021-05-13 이름 : 박재형 내용 : 파이썬 클래스 상속 연습문제. """ class Person: def __init__(self, name, age): self.name = name self.age = age def hello(self): print("~~~~~~~~~~~~~") print("이름 :", self.name) print("나이 :", self.age) class Student(Person): def __init__(self, name, age, school, major): super().__init__(name, age) self.school = school self.major = major def hello(self): super().hello() print("학교 :", self.school) print("전공 :", self.major) class SalaryStudent(Student): def __init__(self, name, age, school, major, company): super().__init__(name, age, school, major) self.company = company def hello(self): super().hello() print(super)
false
167b769fa204a94e3d31747b0bee0962c13f6c68
Speg937/python-practice
/madlibs.py
1,024
4.28125
4
# #for example # someone = "Harry" # #few ways to do ===> # print("Say hi to " + someone) # print("Say hi to {}".format(someone)) # print(f"Say hi to {someone}") Season = input("Enter a Season: ") auxiliary_verb = input("Enter a auxiliary verb: ") print(auxiliary_verb + " I compare thee to a " + Season +"'s day?\n Thou art more lovely and more temperate: \n") print("Rough winds do shake the darling buds of May,\n And " + Season +"'s lease hath all too short a date: \n") print("Sometime too hot the eye of heaven shines,\n And often is his gold complexion dimm'd;\n") print("And every fair from fair sometime declines,\n By chance or nature's changing course untrimm'd \n") print("But thy eternal " + Season + auxiliary_verb +" not fade\n Nor lose possession of that fair thou owest;\n") print("Nor "+ auxiliary_verb + " Death brag thou wander'st in his shade,\n When in eternal lines to time thou growest: \n") print("So long as men can breathe or eyes can see,\n So long lives this and this gives life to thee.")
false
5b0002f4992b9cd73d114d3cc2fe02735a473e36
anchaubey/pythonscripts
/file_read_write_operations/file1.py
2,790
4.71875
5
There are three ways to read data from a text file. read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file. File_object.read([n]) readline() : Reads a line of the file and returns in form of a string.For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line. File_object.readline([n]) readlines() : Reads all the lines and return them as each line a string element in a list. File_object.readlines() with open("C:\\Users\\ankit\\Desktop\\test.txt","w+") as f: f.write("We are learning python\nWe are learning python\nWe are learning python") f.seek(0) print(f.read()) print("Is readable:",f.readable()) print("Is writeable:",f.writable()) f.truncate(5) f.flush() f.seek(0) print(f.read()) f.close() ========================================================== if f.mode == 'r': ========================== Note: ‘\n’ is treated as a special character of two bytes # Program to show various ways to read and # write data in a file. file1 = open("C:\\Users\\ankit\\Desktop\\falcon.txt","w") L = ["This is Delhi \n","This is Paris \n","This is London \n"] # \n is placed to indicate EOL (End of Line) file1.write("Hello \n") file1.writelines(L) file1.close() #to change file access modes file1 = open("myfile.txt","r+") print("Output of Read function is ") print(file1.read()) print() # seek(n) takes the file handle to the nth # bite from the beginning. file1.seek(0) print "Output of Readline function is " print(file1.readline()) print file1.seek(0) # To show difference between read and readline print("Output of Read(9) function is ") print(file1.read(9)) print() file1.seek(0) print("Output of Readline(9) function is ") print(file1.readline(9)) file1.seek(0) # readlines function print("Output of Readlines function is ") print(file1.readlines()) print() file1.close() =============================================== Apending to a file # Python program to illustrate # Append vs write mode file1 = open("C:\\Users\\ankit\\Desktop\\falcon.txt","w") L = ["This is Delhi \n","This is Paris \n","This is London \n"] file1.close() # Append-adds at last file1 = open("C:\\Users\\ankit\\Desktop\\falcon.txt","a")#append mode file1.write("Today \n") file1.close() file1 = open("C:\\Users\\ankit\\Desktop\\falcon.txt","r") print("Output of Readlines after appending") print(file1.readlines()) print() file1.close() # Write-Overwrites file1 = open("C:\\Users\\ankit\\Desktop\\falcon.txt","w")#write mode file1.write("Tomorrow \n") file1.close() file1 = open("C:\\Users\\ankit\\Desktop\\falcon.txt","r") print("Output of Readlines after writing") print(file1.readlines()) print() file1.close()
true
7fb04b986773cf7a002ceb8078dc11f6b3f9b6b5
learnMyHobby/list_HW
/sets.py
586
4.5625
5
# A = [‘a’,’b’,’c’,’d’] B = [‘1’,’a’,’2’,’b’] # Find a intersection b and a union b import math # declaring the function def Union(A,B): result = list(set(A) | set(B)) # | it is or operator it adds the list since we cannot return result # add the sets # finding the intersection of list a and b def Intersection(A,B): result_1 = list(set(A) & set(B)) return result_1 A = ['a','b','c','d'] B = ['1','a','2','b'] print("Union is : ",Union(A,B)) print("Intersection between A and B is: ", Intersection(A,B))
true
b2358665ea9f13f35c00143fdb19b89cb52959cb
jhhalls/machine_learning_templates
/Clustering/k-means.py
1,926
4.34375
4
""" @author : jhhalls K - MEANS 1. Import the libraries 2. Import the data 3. Find Optimal number of clusters 4. Build K-means Clustering model with optimal number of clusters 5. Predict the Result 6. Visualize the clusters """ import numpy as np import matplotlib.pyplot as plt import pandas as pd #import mall dataset with pandas dataset = pd.read_csv('Mall_Customers.csv') X = dataset.iloc[:,[3,4]].values #find the optimal number of cluster with the elbow method from sklearn.cluster import KMeans wcss = [] for i in range(1,11): kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter= 300, n_init = 10, random_state = 0) kmeans.fit(X) wcss.append(kmeans.inertia_) #plot plt.plot(range(1,11),wcss) plt.title('The elbow method for K-means') plt.xlabel('Number of clusters') plt.ylabel('WCSS') plt.show() #apply k-mean with the optimal #of clusters kmeans = KMeans(n_clusters = 5, init = 'k-means++', max_iter= 300, n_init = 10, random_state = 0) #get a list of data points with the correspondent cluster y_kmeans = kmeans.fit_predict(X) #plot the cluster results plt.scatter(X[y_kmeans==0,0], X[y_kmeans==0,1], s=100, c='red', label ='Careful') plt.scatter(X[y_kmeans==1,0], X[y_kmeans==1,1], s=100, c='blue', label ='Standard') plt.scatter(X[y_kmeans==2,0], X[y_kmeans==2,1], s=100, c='green', label ='Target') plt.scatter(X[y_kmeans==3,0], X[y_kmeans==3,1], s=100, c='magenta', label ='Careless') plt.scatter(X[y_kmeans==4,0], X[y_kmeans==4,1], s=100, c='cyan', label ='Sensible') plt.scatter(kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1], s= 300, c='yellow', label = 'centroid') plt.title('Cluster of clients') plt.xlabel('Annual salary K$') plt.ylabel('Spending score') plt.legend() plt.show()
true
f13f34892527aea07186b8785b0d083bb9fed5ef
SJChou88/dsp
/python/q8_parsing.py
915
4.3125
4
# The football.csv file contains the results from the English Premier League. # The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of # goals scored for and against each team in that season (so Arsenal scored 79 goals # against opponents, and had 36 goals scored against them). Write a program to read the file, # then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals. import csv with open('/Users/stephenchou/ds/metis/metisgh/prework/dsp/python/football.csv') as f: reader = csv.DictReader(f) smallestgd = None for row in reader: absgd = abs(int(row['Goals'])-int(row['Goals Allowed'])) if smallestgd == None: smallestgd = absgd smallestname = row['Team'] elif smallestgd > absgd: smallestgd = absgd smallestname = row['Team'] print(smallestname)
true
9a12200c5d3af09cc03550fb4f3449cd5be6dfdd
susunini/leetcode
/110_Balanced_Binary_Tree.py
2,508
4.15625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): """ Wrong. Different fromt this problem, another definition of height balanced tree. -> max depth of leaf node - min depth of leaf node <= 1 For example 1 2 3 """ pass class Solution(object): """ Wrong. """ def getDepth(self, root): if not root: return 0 left_dep = self.getDepth(root.left) if left_dep == -1: return -1 right_dep = self.getDepth(root.right) if right_dep == -1: return -1 return max(left_dep, right_dep) if abs(left_dep - right_dep) <= 1 else -1 def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ left_dep = self.getDepth(root.left) right_dep = self.getDepth(root.right) return left_dep != -1 and right_dep != -1 and abs(left_dep - right_dep) <= 1 class Solution(object): """ Tree. Divide and Conquer. 75ms. Definition of height balanced tree""" def getDepth(self, root): if not root: return 0 left_dep = self.getDepth(root.left) if left_dep == -1: return -1 right_dep = self.getDepth(root.right) if right_dep == -1: return -1 return max(left_dep, right_dep) + 1 if abs(left_dep - right_dep) <= 1 else -1 def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True left_dep = self.getDepth(root.left) right_dep = self.getDepth(root.right) return left_dep != -1 and right_dep != -1 and abs(left_dep - right_dep) <= 1 UNBAL = -1 class Solution(object): """ 88ms. """ def getDepth(self, root): if not root: return 0 left_dep = self.getDepth(root.left) if left_dep == UNBAL: return UNBAL right_dep = self.getDepth(root.right) if right_dep == UNBAL: return UNBAL return max(left_dep, right_dep) + 1 if abs(left_dep - right_dep) <= 1 else UNBAL def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ return self.getDepth(root) != UNBAL
true
fc81d349674608957642b6ef0663e1a1c6433370
susunini/leetcode
/143_Reorder_List.py
1,109
4.125
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): """ Linked List. Classic problem. It is composed of three steps which are commonly used for different linked list problems. step 1: find middle node and split into two halves step 2: reverse the second half step 3: merge two lists """ def reorderList(self, head): """ :type head: ListNode :rtype: void Do not return anything, modify head in-place instead. """ if not head: return head slow = head; fast = head.next while fast and fast.next: slow = slow.next fast = fast.next.next h1 = head; h2 = slow.next slow.next = None prev = None; cur = h2 while cur: cur.next, prev, cur = prev, cur, cur.next h2 = prev p1 = h1 p2 = h2 while p2: p1.next, p2.next, p1, p2 = p2, p1.next, p1.next, p2.next
true
b98bd948a6cf84a855a21a9912242964ff285ea3
RonKang1994/Practicals_CP1404
/Practical 4/Lecture 4.py
779
4.21875
4
VOWELS_CHECK = 'aeiou' def check_vowel(): name = str(input("Name: ")) letter = 0 vowel = 0 for char in name: letter += 1 for v_check in VOWELS_CHECK: if char.lower() == v_check.lower(): vowel += 1 print("Out of {} letters {} has {} vowels".format(letter, name, vowel)) def long_list(text): text_list = text.split() final_list = list() for i in range(0, len(text_list)): if len(text_list[i]) > 3: final_list.append(text_list[i]) print(final_list) def main(): # Give a name and check how many vowels there are in it # check_vowel() # Convert a string into a list and give ones which have 3> characters text = "This is a sentence" long_list(text) main()
true
d7fe636964234deb552b42b3ee84fd2e5e67d486
scorp6969/Python-Tutorial
/math/indexing.py
462
4.28125
4
# slicing = create substring by extracting elements from another string # indexing[] or slice() # [start:stop:step] name = 'Rocky Rambo' first_name = name[0:5] last_name = name[6:11] print('method 1') print(first_name) print(last_name) f_name = name[:5] l_name = name[6:] print('') print('method 2') print(f_name) print(l_name) funky_name = name[::2] print('') print(funky_name) reversed_name = name[::-1] print('') print(reversed_name)
false
cea319acb2704979a43663448216e9cc322e3feb
LizhangX/DojoAssignments
/PythonFun/pyFun/Multiples_Sum_Average.py
690
4.4375
4
# Multiples # Part I - Write code that prints all the odd numbers from 1 to 1000. Use the for loop and don't use a list to do this exercise. for i in range(0,1000): if i % 2 != 0: print i # Part II - Create another program that prints all the multiples of 5 from 5 to 1,000,000. for i in range(5,1000000): if i % 5 == 0: print i # Sum List # Create a program that prints the sum of all the values in the list: a = [1, 2, 5, 10, 255, 3] a = [1, 2, 5, 10, 255, 3] sum = 0 for i in range(0,len(a)): sum += a[i] print sum # Average List # Create a program that prints the average of the values in the list: a = [1, 2, 5, 10, 255, 3] avg = sum/len(a) print avg
true
180f640a3db8b9ba5ec1dba6d8c0605968ac0fa1
xdisna2/4FunctCalc
/test.py
876
4.4375
4
# Testing type conversions # Entering an int x = float(input("Number 1:")) # Convert to float # So matter its a string it will include the .0 to make it a float print(x) # Change from float to int x = 11.0 print(type(x)) x = round(11.0) print(type(x)) # Test out is_integer function # Note to self you must declare it as a float to try it out x = float(input("Enter a number:")) # Convert to int if x.is_integer(): x = round(x) print(x) # Lets try adding two numbers of different types x = 11 y = 11.5 z = x + y # Of course this will output a float print(z) # What if it was 2 floats but they add to become an integer? x = 11.0 y = 11.0 z = x + y # It will output a float but truly its an even whole number print(z) # Now if the total adds up to become an integer then it will make it an integer (whole number) if z.is_integer(): z = round(z) print(z)
true
757e96688c44e4f4994e151c5b664878d2a2c8d7
RAMYA-CP/PESU-IO-SUMMER
/coding_assignment_module1/one.py
348
4.3125
4
#Write a Python program which accepts a sequence of comma-separated numbers from the user and generate a list and a tuple with those numbers. l=input().split(',') list_n=[] for i in l: list_n.append(int(i)) tuple_n=tuple(list_n) print("THIS IS A LIST OF ELEMENTS:") print(list_n) print("THIS IS A TUPLE OF ELEMENTS:") print(tuple_n)
true
2b47157048a4e30580e6c7f12626c69902421128
biomathcode/Rosalind_solutions
/Variables_and_some_arithmetic.py
415
4.21875
4
a = int(input('this is the a length of triangle : ')) b = int(input('this is the b length of triangle : ')) def square_hypotenuse(a = 3, b = 5): a_square = a * a b_square = b * b hypotenuse = a_square + b_square return print("The hypotenuse is ", hypotenuse) square_hypotenuse(a ,b) """ this is the a length of triangle : 966 this is the b length of triangle : 971 The hypotenuse is 1875997 """
false
c063891b5f3f8ad713ca6a22416235e38553b7e4
biomathcode/Rosalind_solutions
/Bioinformatics Stronghold/IEN.py
1,081
4.15625
4
## Calculating Expected offspring """ Given: Six nonnegative integers, each of which does not exceed 20,000. The integers correspond to the number of couples in a population possessing each genotype pairing for a given factor. In order, the six given integers represent the number of couples having the following genotypes: AA-AA AA-Aa AA-aa Aa-Aa Aa-aa aa-aa Return: The expected number of offspring displaying the dominant phenotype in the next generation, under the assumption that every couple has exactly two offspring. """ def file_parser(file_name): with open("docs/" + file_name) as f: f = f.readline() ##number of offspring list offList = f.split(' ') offList = [int(x) for x in offList] print(offList) return offList def expected_offspring(a): sum = (a[0] * 1 + a[1] * 1 + a[2] * 1 + a[3] *0.75 + a[4] *0.5 + a[5] * 0) * 2 return sum if __name__ == "__main__": file_name = input('Please type the filename here') offspring_list = file_parser(file_name) print(expected_offspring(offspring_list))
true
f180736db7b68d0c12b796a04106660f5ed1a28b
PurityControl/uchi-komi-python
/problems/euler/0008-largest-product-in-series/ichi/largest_product_in_series.py
893
4.40625
4
def largest_product(length, str_of_digits): """ returns the largest product of contiguous digits of length length in a string of digits args: length: the length of contiguous digits to be calculated str_of_digits: the string of digits to calculate the products from """ return max(product(nums) for nums in succesive_seqs(length, str_of_digits)) def product(lodigits): return reduce(lambda x,y: x*y, lodigits) def succesive_seqs(length, str_of_digits): """Generator takes a string of digits and returns succesive lists of contiguous digits of length length Args: length: number of contiguous digits to take from list str_of_digits: the string of digits to split up """ digit_list = [int(x) for x in list(str_of_digits)] for index in range(len(str_of_digits) - length): yield digit_list[index:index+length]
true
702d0eea27aa14c1d522ac6c06673dc0cecd0778
PurityControl/uchi-komi-python
/problems/euler/0009-special-pythagorean-triplet/ichi/pythagorean_triplet.py
596
4.25
4
def pythagorean_triplet(sum): """ returns the first pythagorean triplet whose lengths total sums args: sum: the amount the lengths of the triangle must total """ return first(a * b * c for (a, b, c) in triplets_summing(sum)) def triplet_p(a, b, c): return (a * a) + (b * b) == (c * c) def first(seq): return next(seq) def triplets_summing(total): for a in range(total+1): for b in range(total+1): for c in range(total+1): if (a + b + c == total) and (a < b < c) and triplet_p(a, b, c): yield (a, b, c)
true
0f0e9e32d6e713aee7024dfd4f1e94eac8ee1f34
DheerajKN/Python-with-pygame
/SolAssignment1.py
1,109
4.1875
4
def Multiply(x,y): z = x * y print("Answer: ",z) def Divide(x,y): if y != 0: z = x / y print("Answer: ",z) else: print("Division by 0 is not defined") def Add(x,y): z = x + y print("Answer: ",z) def Subtract(x,y): z = x - y print("Answer: ",z) ch = "y" while ch == "Y" or ch == "y": operation = input("What would you like to do?\n1.Add\n2.Subtract\n3.Multiply\n4.Divide ") if operation == "1": x = float(input("First number: ")) y = float(input("Second number: ")) Add(x,y) elif operation == "2": x = float(input("First number: ")) y = float(input("Second number: ")) Subtract(x,y) elif operation == "3": x = float(input("First number: ")) y = float(input("Second number: ")) Multiply(x,y) elif operation == "4": x = float(input("First number: ")) y = float(input("Second number: ")) Divide(x,y) else: print("Wrong Input") ch = input("Would you like to continue ? y/n")
false
0f76d1582d68ace6e5b7d92e07ec84805220ae92
ktops/SI-206-HW04-ktops
/magic_eight.py
843
4.125
4
def user_question(): user_input = input("What is your quesiton? ") return user_input user_input = "" while user_input is not "quit": user_input = user_question() if user_input[-1] is not "?": print("I'm sorry, I can only answer questions.") else: break import random possible_answers = ["It is certain", "It is decidedly so", "Without a doubt", "Yes definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good","Yes", "Signs point to yes", "Ask again later", "Better not to tell you now", "Cannot predict now", "Concentrate and ask again", "Don't count on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful"] answer_to_question = random.choice(possible_answers) print(answer_to_question)
true
e3487062e8ae883c7c7e77df308fef5291821f2f
kedarjk44/basic_python
/lambda_map_filter_reduce.py
485
4.21875
4
# lambda can be used instead of writing a function add_two_inputs = lambda x, y: x + y print(add_two_inputs(8, 5)) print(add_two_inputs("this", " that")) # map can be used to apply a function to each element of a list list1 = [1, 2, 3, 4] print(*list(map(lambda x: x**2, list1))) # or can be done as print(*[x**2 for x in list1]) # filter can be used to apply a condition to list print(*list(filter(lambda x: x > 2, list1))) # or can be done as print(*[x for x in list1 if x > 2])
true
053d241010b90a67fecff40454dc3e178b4b9aba
marsel1323/Python-Fast-start
/ДЗ№1.py
421
4.25
4
#1 - Установить Python #2 - Выполнить в интерактивном режиме действия: # 1. 10/3 (деление); 10//3 (целая часть от деления); 10%3 (остаток от деления); 10**3 (возведение в квадрат) # 2. 10*3+1 и 10*(3+1) - объяснить почему разные ответы (лол, потому что математика)
false
f1e43c1f7195269a40c8b2e4e9c721f062c5f617
canadian-coding/posts
/2019/August/21st - Basic Logging in python/logging_demo.py
1,777
4.21875
4
import logging # Module that allows you to create logs; Logs are very helpful for down the road debugging import datetime # Used in formatting strings to identify date and time def print_num(): """Takes user input, and if it's an int or float prints it.""" logging.debug("Starting print_int") # Only gets logged if loggers level is DEBUG (10) or below try: logging.info("Prompting for input") # Only gets logged if loggers level is INFO (20) or below user_input = input("Enter a number:") user_input = eval(user_input) # Convert input to an int or float except: # If the user enters something other than an int or float logging.warning(f"User didn't enter a number, they entered {user_input}") # Only gets logged if loggers level is WARNING (30) or below logging.info(f"User entered int or float: {user_input}") print(f"User entered int or float: {user_input}") if __name__ == "__main__": # For backwards compatability the logging module forces % formatting for predefined values # SEE: For a full list of variables visit: https://docs.python.org/3/library/logging.html#logrecord-attributes LOG_FORMAT = "{0} | %(levelname)s | %(module)s | : %(message)s".format(datetime.datetime.now().time()) # Instantiate a logger in the simplest way possible logging.basicConfig(format=LOG_FORMAT, # Pass the log format defined above to the logger filename='example.log', # Specifying a filename automatically puts all logs in the filename path filemode='w', # Allows you to specify filemode; SEE: https://docs.python.org/3.7/library/functions.html#open level=logging.DEBUG) # Defines what type of logs should show up; SEE: https://docs.python.org/3/howto/logging.html#logging-levels print_num()
true
0f7e7f6a8fd56a5a5e7c50ae78a0662050735c7e
canadian-coding/posts
/2019/July/8th - Optional boolean arguments in argparse/optional_boolean_arguments.py
949
4.3125
4
"""A demo of optional boolean arguments using argparse.""" import argparse # Module used to set up argument parser # Setting up Main Argument Parser main_parser = argparse.ArgumentParser(description="A demo of optional boolean arguments") # Adding optional boolean argument main_parser.add_argument("-r", '--run', help="If argument is present run 'print('hello')'", action='store_true', # If -r is present, the argument is True default=False, # If -r is not present the argument is False required=False, # Makes argument optional dest="run") # Makes variable accessible as 'run', see lines 19-26 def function_to_run(): """Function intended to run if the -r or --run command is used""" print("-r or --run was called") # Argument parsing args = main_parser.parse_args() if args.run: # If -r or --run is specified, run function_to_run() function_to_run() else: # If -r or --run was not present print("-r or --run was not called")
true
1d3124d8e22793e7cb0a9abc4d1e4a9005e2bad4
lastcanti/learnPython
/review2.py
555
4.15625
4
# python variables and collections print("I am a print statement") # use input to get data from console #someData = input("Enter some data: ") #print(someData) # lists are used to store data a = [] a.append(1) a.append("a") a.pop() b = [2] print a print a + b c = (1,"a",True) print(type(c)) print(len(c)) # tuples assigned to variables guitar3,guitar4,guitar5 = ("fender","gibson","ibanez") print(guitar3,guitar4,guitar5) # dictionary creation dict1 = {"one": 1, "two": 2, "three": 3} print(dict1["one"]) print(dict1.keys()) print(dict1.values())
true
5a55f549fc08b77283d8bfc80204219839ddd237
erdemirbehiye/ceng391-comp-graphics
/BehiyeErdemir_assignment1/BehiyeErdemir/vec3d.py
1,819
4.34375
4
# CENG 487 Assignment1 by # Erdem Taylan # StudentId: 240206013 # 11 2020 import math #Vector class for initializing vector and vector operations class Vec3d: #initialization of a vector, and its element def __init__(self, x: float, y: float, z: float, w: float = 0): #w is 0 to be ineffective self.x = x self.y = y self.z = z self.w = w #adding operation for 2 vector def __add__(self, other): return Vec3d(self.x + other.x, self.y + other.y, self.z + other.z) #subtraction operation for 2 vector def __sub__(self, other): return Vec3d(self.x - other.x, self.y - other.y, self.z - other.z) #product of a scalar and vector def __mul__(self, other: float): return Vec3d(self.x * other, self.y * other, self.z * other) #division of vector by a scalar def __truediv__(self, other: float): return self * other ** -1 #magnitude of a vector def abs(self): return math.sqrt(self.dot(self)) #string representation of a matrix def __str__(self): return f"({self.x}, {self.y}, {self.z}, {self.w})" #printable representation of the object def __repr__(self): return f"{str(self)}" #dot product def dot(self, other): return self.x * other.x + self.y * other.y + self.z * other.z + self.w * other.w #cross Product def cross(self, vector): return Vec3d(self.y * vector.z - self.z * vector.y, self.z * vector.x - self.x * vector.z, self.x * vector.y - self.y * vector.x) #projection of a vector def projection(self, other): return other * (self.dot(other) / other.dot(other)) #angle between two vectors def angle(self, other): return math.acos(self.dot(other) / (self.abs * other.abs))
false
85527d167d7805f2f402da1c2f59e03178e3043a
Todai88/me
/kmom01/plane/plane1.py
445
4.5
4
""" Height converter """ height = format(1100 * 3.28084, '.2f') speed = format(1000 * 0.62137, '.2f') temperature = format(-50 * (9/5) + 32, '.2f') print("""\r\n########### OUTPUT ###########\r\n\r\nThe elevation is {feet} above the sea level, \r\n you are going {miles} miles/h, \r\n finally the temperature outside is {temp} degrees fahrenheit \r\n ########### OUTPUT ###########""".format(feet=height, miles=speed, temp=temperature))
true
d6a5422996f26970b11e5a756af66c7e0d33ca0e
Todai88/me
/kmom01/hello/hello.py
681
4.4375
4
""" Height converter """ height = float(input("What is the plane's elevation in metres? \r\n")) height = format(height * 3.28084, '.2f') speed = float(input("What is the plane's speed in km/h? \r\n")) speed = format(speed * 0.62137, '.2f') temperature = float(input("Finally, what is the temperature (in celsius) outside? \r\n")) temperature = format(temperature * (9/5) + 32, '.2f') print("""\r\n########### OUTPUT ########### \r\n \r\n The elevation is {feet} above the sea level, \r\n you are going {miles} miles/h, \r\n finally the temperature outside is {temp} degrees fahrenheit \r\n ########### OUTPUT ###########""".format(feet=height, miles=speed, temp=temperature))
true
b0b67c197c66734915eef38b4d00787eda45e06c
cabbageGG/play_with_algorithm
/LeetCode/125_isPalindrome.py
1,034
4.25
4
#-*- coding: utf-8 -*- ''' Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome. Note: Have you consider that the string might be empty? This is a good question to ask during an interview. For the purpose of this problem, we define empty string as valid palindrome. ''' class Solution: def isPalindrome(self, s): """ :type s: str :rtype: bool """ l = len(s) i = 0 j = l - 1 while i<j: while i<j and not s[i].isalnum(): i += 1 while i<j and not s[j].isalnum(): j -= 1 if s[i].upper() == s[j].upper(): i += 1 j -= 1 else: return False return True if __name__ == '__main__': s = Solution() ss = "a.b,." ss[0].isalnum() tt = s.isPalindrome(ss) print (tt)
true
9949c12df71be1f193ee8de7427701ec75d6b4b7
DoneWithWork/Number-Guessing-Game
/Number Guessing Game.py
1,547
4.53125
5
# Import random module import random # Number of guesses is 3 guesses = 3 # Getting a random number between and including 1 and 10 number = random.randint(1,10) # Some basic print statements print("Welcome to guess the number") print("You have to guess a number from 1-10") print("You have 3 guesses") # While the guesses is greater than 0, repeat the code below. while guesses >0: choice = int(input("Enter your guess (1-10): ")) # Getting the player input if choice == number: # If the player's choice is equal to the number print("You WIN!! The number was ",number) # Printing a win message and the number quit() # exit the programme elif choice < number: # If the player's input is smaller than the number, run the code below. guesses -=1 # Guesses minus 1, Player has one less guess. print("Your choice is smaller than the number. You have",guesses,"more guesses") # Giving a hint that the player's choice is smaller than the number elif choice > number: # If the player's choice is greater than the number, run the code below. guesses -=1 # Guesses minus 1, Player has one less guess. print("Your choice is bigger than the number. You have",guesses,"more guesses") # Giving a hint that the player's choice is bigger than the number # When the number of guesses is 0, the code below only will be carried out as the player would have run out of guesses. print("You lost!! The number is",number)# Printing a lose message and the number
true
ee6da142b0010ee7cd926b9f55da2b6eaaa31763
CauePinheiro-2001/PythonComputacao1
/aulas_extras/funções.py
1,059
4.125
4
'''Funções são tem diferentes finalidades para que programador decida qual seja:''' #Estrutura da função: def ola_mundo(): '''Diz olá mundo''' print('Olá mundo!') ola_mundo() def saudacao(nome='caue'): '''Exibe uma saudação simples ao usuário''' print(f'Olá {nome.title()}!') saudacao('Gabriela') def objeto(cor_do_objeto,tamanho_do_objeto): print(f'A cor do objeto é: {cor_do_objeto} \nO tamanho do objeto é: {tamanho_do_objeto}') objeto('azul','Pequeno') #Para funções que tem parametros podemos utilizar, o return: def parabens(fulano): parabens_fulano = 'Parabens ' + fulano return parabens_fulano print(parabens('caue')) #função de tempo atual: from datetime import datetime def tempo_atual(): '''Busca a data e hora. Lembre-se de utilizar a biblioteca datetime: from datetime import datetime''' tempo_atual = datetime.now() print('tempo atual : {0}/{1}/{2} as {3}:{4}h'.format(tempo_atual.day, tempo_atual.month, tempo_atual.year, tempo_atual.hour, tempo_atual.minute) ) tempo_atual()
false
31285f3d75b27e60dfb4da5af6a168e90b486d46
CauePinheiro-2001/PythonComputacao1
/estrutura_repetição/6.py
274
4.25
4
'''6.Faça um programa que leia 5 números e informe a soma e a média dos números''' numeros = [] for i in range(1, 6): numeros.append(int(input(f'Digite o {i}º numero: '))) print(f'A soma dos numeros é: {sum(numeros)} \nA média dos numeros é: {sum(numeros)/5} ')
false
cd9e6c4bc8970786f367bf0d0f4fbc7a5ea7f39f
CauePinheiro-2001/PythonComputacao1
/exercicios_semana3/8.py
438
4.28125
4
'''8.Escreva um programa que lê um número inteiro. Informe se o mesmo é par ou ímpar, positivo ou negativo.''' print('Programa 8') x = int(input('Informe um valor inteiro: ')) if (x % 2) == 0 and x >= 0: print("Numero Par e Positivo") elif (x % 2) == 0 and x < 0: print('Numero Par e Negativo') elif (x % 2) != 0 and x < 0: print('Numero Ímpar e Negativo') else: print('Numero Ímpar e Positivo')
false
d711494581335922181d6ffdb616410354c28d6e
CauePinheiro-2001/PythonComputacao1
/estrutura_repetição/1.py
352
4.28125
4
'''1.Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem caso o valor seja inválido e continue pedindo até que o usuário informe um valor válido.''' nota = float(input('Escreva uma nota de zero a dez: ')) while nota < 0 or nota > 10: print('Numero Inválido') nota = float(input('Escreva uma nota de zero a dez: '))
false
e6f5138437f07b82860fdcf709097a9d963e8df0
CauePinheiro-2001/PythonComputacao1
/estrutura_repetição/8.py
1,180
4.1875
4
'''8.Faça um programa que leia e valide as seguintes informações: a.Idade: entre 0 e 100; b.Salário: maior que zero; c.Sexo: 'f' ou 'm'; d.Estado Civil: 's', 'c', 'v', 'd' ''' idade = int(input('Idade (entre 0 e 100): ')) while 0 > idade or 100 < idade: idade = int(input('Idade inválida, insira a idade novamente: ')) salario = int(input('Salario (maior que zero): ')) while salario < 0: salario = float(input('Salário inválido, insira o salário novamente: ')) sexo = input('Sexo (f ou m): ') while sexo != 'f' and sexo != 'm': sexo = input('Sexo inválido, insira o sexo novamente: ') estado_civil = input('Estado civil (s, c, v, d): ') while estado_civil != 's' and estado_civil != 'c' and estado_civil != 'v' and estado_civil != 'd': estado_civil = input('Estado Cívil inválido, insira novamente: ') from datetime import datetime tempo_atual = datetime.now() print('Valores validados em {0}/{1}/{2} {3}:{4}h '.format(tempo_atual.day, tempo_atual.month, tempo_atual.year, tempo_atual.hour, tempo_atual.minute)) print('Os valores são: ') print('Idade: ', idade) print('Saário: ', salario) print('Sexo: ', sexo) print('Estado Civil: ', estado_civil)
false
73692164f112b92a5786c10df1691a17aca9b38f
BolajiOlajide/python_learning
/beyond_basics/map_filter_reduce.py
616
4.15625
4
from functools import reduce import operator mul = lambda x: x * 2 items = [1, 2, 4, 5, 6, 8, 9, 10] print(map(mul, items)) # [4, 8, 12, 16, 20] # if you are using python3 then the result of map and filter will # be lazy loaded so you have to manually convert to a list first_names = ["John", "Jane", "James", "Jacob", "Jennifer"] last_names = ["Doe", "Wash", "McClean", "James"] print() is_odd = lambda x: not (x % 2) print(filter(is_odd, items)) # [2, 4, 6, 8, 10] mul_2 = lambda x, y: x * y new_items = [1, 2, 3, 4, 5] print(reduce(mul_2, new_items)) # 120 print(reduce(operator.add, new_items)) # 15
true
bc9d9e40d1206fb53e22c9a1b1a8f019e6f67884
BolajiOlajide/python_learning
/beyond_basics/inheritance.py
399
4.15625
4
class Base: def __init__(self): print("Base initializer") def f(self): print("Base.f()") class Sub(Base): def __init__(self): super().__init__() # we have to explicitly call the base class's initializer print("Sub initializer") def f(self): super().f() # same for every other overriden method you want to extend print("Sub.f()")
false
b0aebff67ff52cefe76ff542e07666ed58a8f39b
parallexTanatep/python
/week3_1.py
780
4.125
4
print('\nเลือกเมนูเพื่อทำรายการ') print('กด 1 เลือกเหมาจ่าย') print('กด 2 เลือกจ่ายเพิ่ม') x = int(input(':')) y = int(input('กรุณากรอกระยะทาง :')) if x==1 : if y >=25: print('ค่าใช้จ่ายรวมทั้งหมด : 55 บาท') else : print('ค่าใช้จ่ายทั้งหมด : 25 บาท') elif x==2 : if y<=25: print('ค่าใช้จ่ายทั้งหมด : 25 บาท') else : print('ค่าใช้จ่ายทั้งหมด : 80 บาท') else : print('ทำรายการไม่ถูกต้อง')
false
43c0bc0302ce5d541f29de7c3cac24a926b21209
jm-avila/REST-APIs-Python
/Refresher/09_the_in_keyword/code.py
299
4.125
4
movies_watched = {"The Matrix", "Green Book", "Her"} user_movie = input("Enter something you've watched recently: ") print("in movies_watched", user_movie in movies_watched) vowels = "aeiou" user_letter = input("Enter a letter and see if it's a vowel: ") print("in vowels", user_letter in vowels)
true
a9dd82154e83621eeed02e814449067c4720e2a4
jm-avila/REST-APIs-Python
/Refresher/22_unpacking_keyword_arguments/code.py
924
4.15625
4
# colect keyword arguments into a dictionary def example_1(**kwargs): print("example_1", kwargs) example_1(name="Bob", age=25) print() # unpack dictionary into keyword arguments def example_2(name, age): print("example_2", name, age) details = {"name": "Bob", "age": 25} example_1(**details) example_2(**details) print() # **kwargs colect keyword arguments into a dictionary. # The dictionary is then passed to example_1 func. def example_3(**kwargs): print("example_3") example_1(**kwargs) for arg, value in kwargs.items(): print(f"{arg}: {value}") # the details dictionary is passed as keyword parameters to example_3 func. example_3(**details) example_3(name="Bob", age=25) # *args unnamed arguments are colected in a tuple # **kwargs named arguments are colected in a dictionary def example_4(*args, **kwargs): print(args) print(kwargs) example_4(1, 3, 5, name="Bob", age=25)
false
92988d12250b0d14e4a4a6d5e688f33f973b8b2d
DavidCorzo/EstructuraDeDatos
/#SearchingAndSorting/Sorting.py
1,159
4.125
4
def selection_sort(unsorted: list) -> list: for i in range(0, len(unsorted) - 1): min = i for j in range(i + 1, len(unsorted)): if unsorted[j] < unsorted[min]: min = j if min != i: unsorted[i], unsorted[min] = unsorted[min], unsorted[i] return unsorted def bubble_sort(unsorted: list) -> list: for i in range(0, len(unsorted)): for j in range(0, len(unsorted) - 1 - i): if unsorted[j] > unsorted[j + 1]: unsorted[j], unsorted[j + 1] = unsorted[j + 1], unsorted[j] return unsorted def quick_sort(unordered_list: list) -> list: lenght = len(unordered_list) if lenght <= 1: return unordered_list else: # the last element is poped pivot = unordered_list.pop() upper, lower = list(), list() for item in unordered_list: if item > pivot: upper.append(item) else: lower.append(item) return quick_sort(lower) + [pivot] + quick_sort(upper) # def main(): # L = [3,5,4,1,7,9,10] # l = quick_sort(L) # print(l) # if __name__ == "__main__": # main()
true
6e1c537e147eeccb2c51a55c25900c4f0c7fa19f
PriyanshuChatterjee/30-Days-of-Python
/day_6/06_tuples.py
1,847
4.25
4
emptyTuple = () brothers = ('Arijit','Debrath') sisters = ('Apurba',) siblings = brothers+sisters noofSiblings = len(siblings) parents = ('Ma','Papa') family_members = siblings+parents (firstSibling, secondSibling, thirdSibling, firstparent, secondParent) = family_members fruits = ('apples','mangoes','bananas') vegetables = ('potatoes','cauliflower') animal_products = ('egg','milk') food_stuff_tp = fruits+vegetables+animal_products # Create fruits, vegetables and animal products tuples. Join the three tuples and assign it to a variable called food_stuff_tp. # Unpack siblings and parents from family_members # print(family_members) # Modify the siblings tuple and add the name of your father and mother and assign it to family_members # How many siblings do you have? # Join brothers and sisters tuples and assign it to siblings # Create a tuple containing names of your sisters and your brothers (imaginary siblings are fine) # Create an empty tuple # Change the about food_stuff_tp tuple to a food_stuff_lt list food_stuff_lt = list(food_stuff_tp) # print(food_stuff_lt) # Slice out the middle item or items from the food_stuff_tp tuple or food_stuff_lt list. midNumber = int((len(food_stuff_lt))/2) # Slice out the first three items and the last three items from food_staff_lt list sList = food_stuff_lt[:3]+food_stuff_lt[4:] # Delete the food_staff_tp tuple completely del(food_stuff_tp) nordic_countries = ('Denmark', 'Finland','Iceland', 'Norway', 'Sweden') # Check if 'Estonia' is a nordic country N = 'Estonia' res = False for ele in nordic_countries : if N == ele : res = True break # Check if 'Iceland' is a nordic country N = 'Iceland' res = False for ele in nordic_countries : if N == ele : res = True break print("Does tuple contain required value ? : " + str(res))
true
3034f8af8cb037de81db93f3c283ffbb8cb48116
karthikkbaalaji/CorePython
/loops.py
399
4.28125
4
# Have the user enter a string, then loop through the # string to generate a new string in which every character # is duplicated, e.g., "hello" => "hheelllloo" #import print function from python3 from __future__ import print_function #get the input from the user print("Enter a string:", end='') inputString = raw_input() #print as required for letter in inputString: print(letter*2, end='')
true
f18d0ba8eeb0dad5a1b4bad385ade4d88fa8f5fa
karthikkbaalaji/CorePython
/lists.py
2,279
4.5625
5
#write a Python program to maintain two lists and loop #until the user wants to quit #your program should offer the user the following options: # add an item to list 1 or 2 # remove an item from list 1 or 2 by value or index # reverse list 1 or list 2 # display both lists #EXTRA: add an option to check if lists are equal, even if #contents are not in the same order (i.e, if list 1 is [3, 2, #'apple', 4] and list 2 is [2, 3, 4, 'apple'], you #should indicate they are the same) from __future__ import print_function lists = [[],[]] while True: print('''Choose your option: a. Add item to a list b. Remove an item from a list by index c. Remove an item from a list by value r. Reverse the list f. Check if both lists are equal d. Display both lists e. Exit''') option = raw_input() #option to add item to the list if option == 'a': print("Enter which list to add item(1-2): ") num = int(raw_input()) print("Enter the item: ") item = raw_input() lists[num-1].append(item) print("Item added ") #Removing item from list using item index if option == 'b': print("Enter which list to remove item(1-2): ") num = int(raw_input()) print("Enter the item index: ") item = int(raw_input()) lists[num-1].pop(item) #Removing item from list using item value if option == 'c': print("Enter which list to remove item(1-2): ") num = int(raw_input()) print("Enter the item value: ") item = raw_input() lists[num-1].remove(item) #Reversing a list if option == 'r': print("Enter which list to reverse(1-2): ") num = int(raw_input()) lists[num-1] = lists[num-1][::-1] #lists[num-1].reverse() #Comparing lists if option == 'f': for i in range(0,2): print("List", i+1 , lists[i]) if(sorted(lists[0]) == sorted(lists[1])): print("Lists are equal") else: print("Lists are not equal") #Display lists if option == 'd': for i in range(0,2): print("List", i+1 , lists[i]) #Exit if option == 'e': break else: print("Incorrect Option!")
true
7d3b5f3503d8a454cb36408d04d577981bac76c9
MaoGreenDou/MyPythonStudyOne
/demo01.py
1,545
4.21875
4
# -*- coding:utf-8 -* #注意开头 # 1 first program print('Hello World!') # float data PI = 3.14159 pi = 3.14159 PI is pi id(PI) id(pi) # 2 integer data p = 3 q = 3 q is p id(q) id(p) # 3 big integer data a = 257 b = 257 a is b id(a) id(b) # 4 string data x = 'Hello World!' y = 'Hello World' x is y id(x) id(y) # 5 数据类型:新增的:单引号/双引号/三引号字符串,元组,字典 data={'cos':'cos_value','sin':'sin_value'} print(data['cos']) # 6 运算符操作 x = int(input("Input x: ")) #输入语句 y = int(input("Input y: ")) print("x+y =", x + y) print("x-y =", x - y) print("x*y =", x * y) print("x/y =", x / y) print("x//y =", x // y) # 7 r/R 运算符 print(r'this is a test\n') print(R'this is a test\n') print('this is a test\n') print('this is a test') print('this is a test') # print语句 默认加一个换行符 # 8 输入输出语句小练习 firstname = input('请输入你的姓') secondname = input('请输入你的名') print('你的姓是',firstname) print('你的名字',secondname) # 9 python当中的 包 库 模块 之间的关系 以及两种导入方式 # 10 条件结构 a = 1 b = 2 c = 3 d = 1 if a>b: print('a>b') elif b>c: print('b>c') elif c<d: print('c<d') else: print('a = d') # 11 range 函数 list(range(10)) print(range(10)) #这输出的是啥 list = range(5,10) print(list) #同上,这输出的是啥 list = range(5,10,2) print(list) print(list[2]) # 12 while循环,for循环,列表解析,生成器
false
987d0755225cb89e923d22b48d212ca75cfcf9c0
mcfaddeb4311/cti110
/M5T1_KilometerConverter_BobbyMcFadden.py
515
4.4375
4
# Convert kilometer to miles. # 6-28-2017 # CTI-110 M5T1_KilometerConverter # Bobby McFadden CONVERSION_FACTOR = 0.6214 def main (): # Get the distance in kilometers. kilometers = float (input('Enter a distance in kilometers: ')) #Display the distance converted to miles. show_miles (kilometers) def show_miles (km): # Calculate miles. miles = km * CONVERSION_FACTOR #Display the miles. print (km, 'kilometers equals', miles, 'miles.') #Call the main function. main()
true
cad19fd15b16c7a8494fd52bece96ff572d86487
csbridge/csbridge2020
/docs/starter/lectures/Lecture6/school_day.py
544
4.28125
4
""" This program tells whether go to school or not for a particular day. """ MONDAY = 1 TUESDAY = 2 WEDNESDAY = 3 THURSDAY = 4 FRIDAY = 5 SATURDAY = 6 SUNDAY = 7 def main(): print("Should I go to school?") day = int(input("Enter a day: ")) if MONDAY <= day <= FRIDAY: # day is between Monday and Friday print("School day") elif day == SATURDAY or day == SUNDAY: # day is either Saturday or Sunday print("Weekend!") else: print(str(day) + " is not a day!") if __name__ == '__main__': main()
true
f5252fb223ae9632eda4a7126d4e5f66b62085c3
caotritran/Python_Pymi
/Exercises_5/ex5_3.py
2,473
4.21875
4
#!/usr/bin/env python3 import string data = '''Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments.''' # NOQA #data = '''hoc lap trinh python la hoc ngon ngu va cu phap lap trinh''' # Chú ý: dấu “ không phải double quotes " def solve(input_data): ''' Đặt result bằng list chứa 10 tuple ứng với 10 từ xuất hiện nhiều nhất, mỗi tuple chứa từ và số lần xuất hiện tương ứng. (Nếu có nhiều từ cùng xuất hiện với số lần như nhau thì trả về từ nào cũng được). ''' result = [] dict = {} # Xoá dòng raise và Viết code vào đây set result làm kết quả input_data = input_data.lower() data_1 = string.ascii_lowercase data_2 = '' for char in input_data: if char in data_1 or char == ' ': data_2 += char for word1 in data_2.split(): count = 0 for word2 in input_data.split(): if word1 == word2: count += 1 dict[word1] = count #print(dict) ##sap xep list giam dan for key in sorted(dict, key=dict.get, reverse=True): result.append((key, dict[key])) result = result[:10] #print(li) return result def main(): # Đây là một cách làm khác với kiểu dữ liệu có sẵn # trong thư viện collections của Python #from collections import Counter # Regex (re) là một công cụ xử lý string khác so với các method của # `str`, linh hoạt nhưng phức tạp, khó đọc, dễ sai. #import re #cleaned = re.sub(r'“|”|\.|,', ' ', data) #c = Counter(cleaned.split()) #top = c.most_common(5) result = solve(data) #assert result[:5] == top, (result[:5], top) # In ra 10 từ xuất hiện nhiều nhất kèm số lần xuất hiện # Viết code in ra màn hình sau dòng này print(result) if __name__ == "__main__": main()
false
3b0e7cd368a3f121c67b9a20c75f67e532de6ae3
Cova14/PythonCourse
/dicts_exercise_1.py
518
4.3125
4
# We need to receive the basic info of a user # (first_name, last_name, age, email) # and save them as keys into a dict call user. # After receive the data, show the info in the console user = {} user['first_name'] = input('Hey bro, cual es tu nombre?: ') user['last_name'] = input('Como dices que se apellidan tus gfes?: ') user['age'] = input('Ya alcanzas el timbre?: ') user['email'] = input('Pásame tu correo para enviarte unas fotos UwU: ') for key, value in user.items(): print(f'{key.upper()}: {value}')
true
d51332be4193aa4fb7b71219d96f363de8376044
xuefengCrown/Files_01_xuef
/all_xuef/程序员练级+Never/xuef code/xuef_code_python/fluent python/8 对象引用、可变性和垃圾/8.3 深复制与浅复制.py
598
4.15625
4
""" 我强烈建议你在 Python Tutor 网站 http://www.pythontutor.com/visualize.html#mode=edit 中查看示例的交互式动画。 """ l1 = [3, [55, 44], (7, 8, 9)] l2 = list(l1) # l1 is l2 #False l1==l2 #True l1[1] is l2[1] #True """ 然而,构造方法或 [:] 做的是浅复制(即复制了最外层容器,副本中 的元素是源容器中元素的引用)。如果所有元素都是不可变的,那么这 样没有问题,还能节省内存。但是,如果有可变的元素,可能就会导致 意想不到的问题。 """ # 深复制 import copy l3=copy.deepcopy(l1)
false
5a97ae18e7319001e3eb66d4a7e55bc0f642fc48
xuefengCrown/Files_01_xuef
/all_xuef/程序员练级+Never/想研究的/python-further/metaclass1.py
2,426
4.96875
5
#http://blog.jobbole.com/21351/ #http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python """ Secondly, metaclasses are complicated. You may not want to use them for very simple class alterations. You can change classes by using two different techniques: ·monkey patching ·class decorators 99% of the time you need class alteration, you are better off using these. But 98% of the time, you don't need class alteration at all. """ ##basic """ In most languages, classes are just pieces of code that describe how to produce an object. Classes are objects too. Yes, objects. As soon as you use the keyword class, Python executes it and creates an OBJECT. The instruction >>> class ObjectCreator(object): ... pass ... creates in memory an object with the name "ObjectCreator". This object (the class) is itself capable of creating objects (the instances), and this is why it's a class. But still, it's an object, and therefore: ·you can assign it to a variable ·you can copy it ·you can add attributes to it ·you can pass it as a function parameter """ class A(): def f(self): pass print(dir(A)) ##Creating classes dynamically """ Since classes are objects, you can create them on the fly, like any object. Since classes are objects, they must be generated by something. When you use the class keyword, Python creates this object automatically. But as with most things in Python, it gives you a way to do it manually. """ ##What are metaclasses (finally) """ Metaclasses are the 'stuff' that creates classes. MyClass = MetaClass() my_object = MyClass() type is the built-in metaclass Python uses, but of course, you can create your own metaclass. """ ##The __metaclass__ attribute """ In Python 2, you can add a __metaclass__ attribute when you write a class (see next section for the Python 3 syntax): class Foo(object): __metaclass__ = something... [...] If you do so, Python will use the metaclass to create the class Foo. You write class Foo(object) first, but the class object Foo is not created in memory yet. Python will look for __metaclass__ in the class definition. If it finds it, it will use it to create the object class Foo. If it doesn't, it will use type to create the class. """ ##Metaclasses in Python 3 """ The syntax to set the metaclass has been changed in Python 3: class Foo(object, metaclass=something): """
true
5ba5d87ad6527bf35a1b1c51134babbca21e1b04
xuefengCrown/Files_01_xuef
/all_xuef/程序员练级+Never/Fun_Projects/EOPL/1.code-induction.py
434
4.28125
4
## (nth-element '(a b c d e) 3) ##= (nth-element '(b c d e) 2) ##= (nth-element '(c d e) 1) ##= (nth-element '(d e) 0) ##= d #> (invert '((a 1) (a 2) (1 b) (2 b))) ## ((1 a) (2 a) (b 1) (b 2)) def invert(lst): # lst is a list of 2-lists (lists of length two) for ele in lst: e1,e2 = ele yield (e2,e1) lst = (('a', 1), ('a', 2), (1, 'b'), (2, 'b')) inverted = invert(lst) for ele in inverted: print(ele)
false
0d89796e96912a5add194eaf2e60f0487219920e
xuefengCrown/Files_01_xuef
/all_xuef/程序员练级+Never/xuef code/xuef_code_python/python_base/元类_类也是对象.py
872
4.1875
4
""" 类(Person,Province)本就是个模板。模板当然是对象。它属于模板(class)类型 人模板(Person), 省模板(Province) """ # 解释器在遇到 class A 时会做什么? # 类是对象意味着我们可将它看作一个实体,进而可以对它进行审视和操作,施加影响。 ## 你可以在运行时创建它 class Province(): country = "China" def __init__(self, name): self.name = name print(type(10)) # <class 'int'> 意味着10是用int类(型)创建出来的对象 p=Province("zhejiang") print(type(p)) #<class '__main__.Province'> # 意味着 p 是用Province类创建出来的对象 print(type(Province)) #<class 'type'> # 意味着 Province是用 class 类创建出来的对象 # 可以使用 type 创建类(class类的对象) #type(类名, 由父类名称组成的元组,包括属性的字典)
false
72ccad5f29e9918974a57e7ccc14b85935d52afb
xuefengCrown/Files_01_xuef
/all_xuef/程序员练级+Never/xuef code/xuef_code_python/composing_programs/4. Data Processing/4.2.6 Python Streams.py
2,460
4.3125
4
""" Streams offer another way to represent sequential data implicitly. A stream is a lazily computed linked list. Like an Link, the rest of a Stream is itself a Stream. Unlike an Link, the rest of a stream is only computed when it is looked up, rather than being stored in advance. That is, the rest of a stream is computed lazily. """ ##To achieve this lazy evaluation, a stream stores a function that computes the rest of the stream. ##Whenever this function is called, its returned value is cached as part of the stream in an ##attribute called _rest, named with an underscore to indicate that it should not be accessed ##directly. class Stream: """A lazily computed linked list.""" class empty: def __repr__(self): return 'Stream.empty' empty = empty() def __init__(self, first, compute_rest=lambda: empty): assert callable(compute_rest), 'compute_rest must be callable.' self.first = first self._compute_rest = compute_rest @property def rest(self): """Return the rest of the stream, computing it if necessary.""" if self._compute_rest is not None: self._rest = self._compute_rest() self._compute_rest = None return self._rest def __repr__(self): return 'Stream({0}, <...>)'.format(repr(self.first)) #r = Link(1, Link(2+3, Link(9))) ##Here, 1 is the first element of the stream, and the lambda expression that ##follows returns a function for computing the rest of the stream. s = Stream(1, lambda: Stream(2+3, lambda: print(9))) # the rest of s includes a function to compute the rest; ##increasing integers ##Lazy evaluation gives us the ability to represent infinite sequential datasets using streams. ##For example, we can represent increasing integers, starting at any first value. ##def integer_stream(first): ## def compute_rest(): ## return integer_stream(first+1) ## return Stream(first, compute_rest) def integer_stream(first): # integer_stream is actually recursive because this stream's compute_rest # calls integer_stream again return Stream(first, lambda: integer_stream(first+1)) positives = integer_stream(1) print(positives) rg = integer_stream(5) while 1: print(rg.first) rg = rg.rest def map_stream(fn, s): if s is Stream.empty: return s def compute_rest(): return map_stream(fn, s.rest) return Stream(fn(s.first), compute_rest)
true
ea486935f6eb853ec567831155935518d9407807
itrevex/ProgrammingLogicAndela
/coffee.py
2,024
4.46875
4
''' Andela Making Coffee App ''' #Make my coffee INGREDIENTS = ['coffee', 'hot water'] print('Started making coffee...') print('Getting cup') print('Adding {}'.format(' and '.join(INGREDIENTS))) print('Stir the mix') print('Finished making coffeee...') MY_COFFEE = 'Tasty Coffee' print("--Here's your {}, Enjoy!!-- Mr. {} \n".format(MY_COFFEE, 'Evans')) def prime_numbers(upper_limit_n): """ Function to return prime numbers from 0 to n """ #upper_limit should always be a non prime_number if upper_limit_n % 2 == 0: upper_limit_n += 1 for i in range(0, upper_limit_n, 2): print(i) ##Trying a different approach of getting prime numbers print(", ".join(""+str(i) for i in range(0, upper_limit_n, 2))) ''' Big O notation analysis: Number of lines executed == 2 memory points = n second print, lines 1 memory points 1 ''' def fibonacci_squence(total_number_of_values, first_value=0, second_value=1): """ Generates fibonacci squence total_number_of_values represents the total number of values in squence first value is the start value of squence second value is the value after the start value """ if total_number_of_values < 3: raise fibonacci_squence_exception() squence_values = [first_value, second_value] for counter in range(total_number_of_values-2): value_one = squence_values[counter] value_two = squence_values[counter+1] squence_values.append(sum_of_values(value_one, value_two)) print(", ".join(str(number) for number in squence_values)) def sum_of_values(value_one, value_two): """ returns sum of two values """ return value_one + value_two def fibonacci_squence_exception(): """ prints error message if total_number_of_values passed to fibonacci squence function is less 3 """ print("Unsupported length of squence, total_number_of_values \n should b >= 3") prime_numbers(30) fibonacci_squence(20, 15, 15)
true
d75b2ad3ccccbbc64101c9d69749f14ac09e7ef1
N-eeraj/code_website
/Code/py/queue_ds.py
929
4.21875
4
def isEmpty(): return True if end == 0 else False def isFull(): return True if end == size else False queue = [] size = int(input("Enter Queue Size: ")) while True: print("Queue:", queue) end = len(queue) option = input("\nSelect Queue Operation\n1. Is Empty?\n2. Is Full?\n3. Enqueue\n4. Dequeue\n5. Exit\nEnter Option Number: ") print() if option == '1': print("Empty" if isEmpty() else "Not Empty") elif option == '2': print("Full" if isFull() else "Not Full") elif option == '3': if isFull(): print("Can't Enqueue: Queue Full") else: queue.append(int(input("Enter Element: "))) elif option == '4': if isEmpty(): print("Can't Dequeue: Queue Empty") else: del queue[0] elif option == '5': break else: print("Enter a number between 1 & 5") print("Queue:", queue)
true
bb633be4035a92e7f9e9ad8b99dad90a0871484a
Arrowarcher/Python_Concise_Handbook
/07-条件判断.py
841
4.28125
4
#if xxx:\nelse:xxx age=3 if age >= 60: print('old man') elif age >=18: print('adult') elif age >=6: print('teenager') else: print('kid') print('练习:') ''' bmi = float(weight/height**2) print('bmi=',bmi) if bmi > 32: print('严重肥胖') elif bmi >28 and bmi <=32: print('肥胖') elif bmi >25 and bmi <=28: print('过重') elif bmi >=18.5 and bmi <=25: print('正常') else:print('过轻') 残次品 ''' h=float(input('please enter your height(m):')) w=float(input('please enter your weight(kg):')) bmi=w/h**2 print('bmi = %.1f'%bmi) #不用加逗号!!! if bmi > 32: print('严重肥胖') elif 28 < bmi <= 32: print('肥胖') elif 25 < bmi <=28: print('过重') elif 18.5 <= bmi <=25: print('正常') else:print('过轻')
false
ee36f2aa49982e1926fc9859ea52987fd598bc7a
jscelza/PythonKnightsSG
/week01/funWithSys.py
868
4.1875
4
"""Playing with sys by using examples from Chapter 1. http://www.diveintopython3.net/your-first-python-program.html Available Functions printSyspath() Print value of sys.path addDirToSyspath(string) Adds string to sys.path """ import sys def display_syspath(): """Print sys.path value.""" print("sys.path has the following value:") print(sys.path) print() def add_dir_to_Syspath(pythonKnightPath='./'): """Add a directory to sys.path.""" print("Adding", pythonKnightPath, " to path") print() sys.path.insert(0, pythonKnightPath) if __name__ == '__main__': print('Default Value') display_syspath() add_dir_to_Syspath("~/repos/PythonKnightsSG") print('Value after inserting of directory') display_syspath() add_dir_to_Syspath() print('Value after inserting of directory') display_syspath()
true
13f76295927ed7cef99d759a3d4a39afaf7c47da
Pjmcnally/algo
/strings/reverse_string/reverse_string_patrick.py
874
4.46875
4
# Authored by Patrick McNally # Created on 09/15/15 # Requests a string and prints it reversed def reverse_string(chars): """Takes in a string and returns it reversed. Parameters ---------- Input: chars: string Any string or list Output: chars: string A reversed version of the input """ if chars: return chars[::-1] else: return None def main(): """Prompt user for a string and prints it reversed Parameters ---------- Input: Output: """ string_ = input("What string would you like reversed? ") rev_string = reverse_string(string_) print(rev_string) assert reverse_string(None) == None assert reverse_string(['']) == [''] assert reverse_string(['f', 'o', 'o', ' ', 'b', 'a', 'r']) == ['r', 'a', 'b', ' ', 'o', 'o', 'f'] if __name__ == '__main__': main()
true
1dd422098c2b504fef437676c9895036a45ada70
Pjmcnally/algo
/sort_visualized/bubble_sort.py
2,950
4.28125
4
"""Visualization of the bubble sort algorithm. For reference: https://matplotlib.org/2.1.2/gallery/animation/basic_example_writer_sgskip.html https://github.com/snorthway/algo-viz/blob/master/bubble_sort.py """ from random import shuffle import matplotlib.pyplot as plt import matplotlib.animation as ani # Create a list of random integers between 0 and 100 sorted_data = list(range(1, 16)) data = sorted_data.copy() shuffle(data) # Create the figure fig, ax = plt.subplots() ax.axes.get_xaxis().set_visible(False) ax.axes.get_yaxis().set_visible(False) def bubble_sort_gen(): """Yield current state of bubble sort.""" sorted_index = len(data) swapped = True while swapped: swapped = False for i in range(sorted_index - 1): yield (data, i, i + 1, sorted_index) if data[i] > data[i + 1]: swapped = True data[i], data[i + 1] = data[i + 1], data[i] yield (data, i + 1, i, sorted_index) sorted_index -= 1 for i in range(10): # Add frames of fully sorted to end yield (data, 0, 0, 0) def cocktail_shaker_gen(): """Yield current state of bubble sort.""" sorted_index_high = len(data) sorted_index_low = -1 swapped = True while swapped: swapped = False for i in range(sorted_index_low + 1, sorted_index_high - 1): yield (data, i, i + 1, sorted_index_low, sorted_index_high) if data[i] > data[i + 1]: swapped = True data[i], data[i + 1] = data[i + 1], data[i] yield (data, i + 1, i, sorted_index_low, sorted_index_high) sorted_index_high -= 1 if not swapped: break swapped = False for i in range(sorted_index_high - 1, sorted_index_low + 1, -1): yield (data, i, i - 1, sorted_index_low, sorted_index_high) if data[i] < data[i - 1]: swapped = True data[i], data[i - 1] = data[i - 1], data[i] yield (data, i - 1, i, sorted_index_low, sorted_index_high) sorted_index_low += 1 for i in range(10): # Add frames of fully sorted to end yield (data, 0, 0, 0, 0) def update(frame): """Frame is the (data, i, iter_count) tuple.""" datums, orange, red, sorted_index_low, sorted_index_high = frame ax.clear() bars = ax.bar(range(len(data)), datums) for k in range(len(data)): if k <= sorted_index_low or k >= sorted_index_high: bars[k].set_color("green") elif k == orange or k == red: bars[k].set_color("orange") else: bars[k].set_color("blue") ax.set_title('Bubble Sort') animation = ani.FuncAnimation( fig, update, frames=cocktail_shaker_gen, interval=200, blit=False, repeat=False, save_count=10000, ) # animation.save(r"C:\Users\Patrick\Desktop\Demo.mp4") plt.show()
true
7b83ce10efb3bf9da2f9650cc1718327bf462193
Pjmcnally/algo
/math/primes/primes_old.py
2,206
4.34375
4
# Authored by Patrick McNally # Created on 09/15/15 # Requests a number from the user and generates a list of all primes # upto and including that number. import datetime def list_primes(n): """Return a list of all primes up to "n"(inclusive). Parameters ---------- Input: n: int or float A number Output: prime_list: list A list including all numbers up to "n"(inclusive) """ prime_list = [] for num in range(2, int(n) + 1): for div in range(2, int(num**.5 + 1)): if num % div == 0: break else: prime_list.append(num) return prime_list def list_primes_better(n): """Return a list of all primes up to "n"(inclusive). Parameters ---------- Input: n: int or float A number Output: prime_list: list A list including all numbers up to "n"(inclusive) """ prime_list = [2] for num in range(2, int(n) + 1): for x in prime_list: if num % x == 0: break elif x > num**.5: prime_list.append(num) break return prime_list def main(): """Requests a number from the user and returns a list of all primes up to and including that number. Parameters ---------- Input: Output: """ total_num = 5000000 start = datetime.datetime.now() final = list_primes(total_num) end = datetime.datetime.now() first_try = end - start print("\nPrime finder process took {} seconds.\n".format(datetime.timedelta.total_seconds(first_try))) start = datetime.datetime.now() final2 = list_primes_better(total_num) end = datetime.datetime.now() sec_try = end - start print("\nBetter Prime finder process took {} seconds.\n".format(datetime.timedelta.total_seconds(sec_try))) if final == final2: print("both lists match") else: print("The lists are not the same") # assert list_primes(1) == [] # assert list_primes(2) == [2] # assert list_primes(12) == [2, 3, 5, 7, 11] # assert list_primes(12.9) == [2, 3, 5, 7, 11] if __name__ == '__main__': main()
true
e887c0efe28523e4de25a523684cea8e1e1b2d92
Neha-kumari31/Sprint-Challenge--Data-Structures-Python
/names/bst.py
1,456
4.125
4
''' Binary search trees are a data structure that enforce an ordering over the data they store. That ordering in turn makes it a lot more efficient at searching for a particular piece of data in the tree. ''' class BSTNode: def __init__(self, value): self.value = value self.left = None self.right = None # Insert the given value into the tree def insert(self, value): #compare the current value of the node(self.value) if value < self.value: #insert the value in left if self.left is None: # insert node value if no node in the left side self.left = BSTNode(value) else: # repeat the process for the next node self.left.insert(value) if value >= self.value: if self.right is None: self.right =BSTNode(value) else: self.right.insert(value) # Return True if the tree contains the value # False if it does not def contains(self, target): if target ==self.value: return True if target < self.value: if self.left is None: return False else: return self.left.contains(target) if target >=self.value: if self.right is None: return False else: return self.right.contains(target)
true
3483d89da70d27855bc0854d531361b2f17b10fa
TanbirulM/Rock-Paper-Scissors
/rps.py
1,551
4.125
4
import random def play_game(): print('Welcome to Rock Paper Scissors!') player_score = 0 bot_score = 0 while True: print('Make your choice:') choice = str(input()).lower() print("My choice is", choice) choices = ['rock', 'paper', 'scissor', 'end'] bot_choices = ['rock', 'paper', 'scissor'] bot_choice = random.choice(bot_choices) print("Computer choice is", bot_choice) if choice in choices: if choice == bot_choice: print('it is a tie') elif choice == 'rock': if bot_choice == 'paper': print('sorry, you lose') bot_score += 1 elif bot_choice == 'scissor': print('You win!') player_score += 1 elif choice == 'paper': if bot_choice == 'scissor': print('sorry, you lose') bot_score += 1 elif bot_choice == 'rock': print('You win!') player_score += 1 elif choice == 'scissor': if bot_choice == 'rock': print('sorry, you lose') bot_score += 1 elif bot_choice == 'paper': print('You win!') player_score += 1 elif choice == 'end': if player_score > bot_score: print('game has ended, player has won :D') elif player_score < bot_score: print('game has ended, computer has won :(') else: print('game has ended in a draw') break print('Player Score: ', player_score, ', Bot Score: ', bot_score) else: print('invalid choice, try again') print('--------------------------------') def main(): play_game() # Standard call for main() function if __name__ == '__main__': main()
true
1cbbe648adf947a8c230a15578b1117c3a523064
jitensinha98/Python-Practice-Programs
/ex32_2.py
433
4.15625
4
y=int(raw_input("Enter the starting element:")) z=int(raw_input("Enter the ending element:")) element=[] for i in range(y,z+1): element.append(i) print "All elements are stored in the list." print "Do you want to veiw the list :" raw_input() print "All elements in the list are :" for numbers in element: print "Numbers=%d"%numbers p=int(raw_input("Enter the interval:")) for i in element: print "Numbers=%d"%i
true
f911f45e6505a6a3916aa7a900bcaa2379a00075
garycunningham89/pands-problem-set
/solution1sumupto.py
657
4.4375
4
#Gary Cunningham. 03/03/19 #My program intends to show the sum of all the numbers for, and including, the inputted integer from number 1. #Adaptation from python tutorials @www.docs.python.org and class tutorials. n = input("Please enter a positive integer: ") # Inputting the first line of the program as per the requested format. n = int(n) # Use of int() to ensure use of postive integers. sum = 0 # Defining base number for program. for num in range(1, n+1, 1): sum = sum+num # Creeating the range with increases to n added together within the range. print("Sum of all numbers between 1 and", n, "is:", sum) # Ensuring the output is explained in the program.
true
251f9d376aefb865fffdbba56b6d4c9bbe0b305c
shawnTever/documentAnalysis
/week1/PythonBasicsTutorial.py
2,480
4.28125
4
my_list2 = [i * i for i in range(10)] # Creates a list of the first 10 square integers. my_set2 = {i for i in range(10)} my_dict2 = {i: i * 3 + 1 for i in range(10)} print(my_list2) print(my_set2) print(my_dict2) # Comprehensions can also range over the elements in a data structure. my_list3 = [my_list2[i] * i for i in my_set2] print(my_list3) dictionary = {} for a in my_list2: if a in my_set2: dictionary[a] = True else: dictionary[a] = False print(dictionary) import numpy as np # This statement imports the package numpy and gives it the name np my_array1 = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) # This is a 2x3 matrix. my_array2 = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]) # This is a 3x2 matrix. # elements addition np.sum(my_array1) # Matrix multiplication np.matmul(my_array1, my_array2) # Matrix transpose print(np.transpose(my_array2)) # Operations such as '+' and '*' can be directly applied to matrices my_array1 + np.transpose(my_array2) # The element in the first row and second column. print(my_array1[0, 1]) # second row. print(my_array1[1, :]) # Everything from the second row onwards. print(my_array1[1:]) # second column. print(my_array1[:, 1]) # Everything from the second column onwards. print(my_array1[:, 1:]) # Everything upto (but not including) the last row print(my_array1[:-1]) # Everything upto (but not including) the last column print(my_array1[:, :-1]) # computing the sum of all of the elements in my_array1 except for the last column. print(np.sum(my_array1[:, :-1])) print('--------------------------------------------------') import pandas as pd my_df = pd.DataFrame({'c1': [1.0, 2.0, 3.0], 'c2': ['a', 'b', 'c'], 'c3': [True, False, True]}) print(my_df) print(my_df.shape) # From the second row on, up to the second column print(my_df.iloc[1:, :2]) # index a DataFrame by using column names print(my_df['c2']) # In Python reading and writing to files can be done using the 'open' keyword, which creates a file handle for the # given path. It is good practice to always use 'open' inside a 'with' clause. This will ensure that the file handle # is closed properly once the with clause finishes. with open('my_file.txt', 'w') as f: # Note that the 'w' means we want to write strings to this path. # *IMPORTANT* If the file already exists, it will be overwritten. f.write('Hello\nWorld!') # After the with clause, the file will be closed.
true
8982047e06eceb6dd3a530bc09584d55cf734e25
aa-fahim/practice-python
/OddOrEven.py
846
4.21875
4
## The programs asks the user to input an integer. The program will then ## determine if the number is odd or even and also if it is a multiple of 4. ## The second part of program will ask for two numbers and then check ## if they are divisble or not. number = int(input('Please enter a number:\n')) a = number % 2 b = number % 4 if (a == 0): print('The number {} is even'.format(number)) elif (a == 1): print('The number {} is odd'.format(number)) if (b == 0): print('The number {} is a multiple of 4'.format(number)) num = int(input('Enter another number:\n')) check = int(input('Enter a number to divide by:\n')) c = num % check if (c == 0): print('The number {} is divisible by {}'.format(num, check)) elif (c != 0): print('The number {} is not divisble by {}'.format(num, check))
true
b8abc55567a07dcd99e00d752a3790ab409f6858
aa-fahim/practice-python
/ListEnds.py
213
4.1875
4
## List Ends # Takes first and last element of input list a and places into new list and # prints it. def list_ends(a): a = [5, 10, 15 ,20 ,25] new_list = [a[0], a[len(a)-1]] print(new_list)
true
c3ecd3b01a046af4f3e6c203878b0864d85a0317
bio-chris/Python
/Courses/PythonBootcamp/Project_3_Pi.py
517
4.21875
4
# Project 3: Find PI to the Nth Digit # Enter a number and have the program generate PI up to that many decimal places. Keep a limit to how far the program # will go. """ Using the Bailey-Borwein-Plouffe formula """ from decimal import * def pi(i): pi_value = 0 getcontext().prec = i for n in range(i+1): pi_value += Decimal((1/16**n)*((4/(8*n+1))-(2/(8*n+4))-(1/(8*n+5))-(1/(8*n+6)))) return pi_value #print(pi(1000)) """ Need to determine accuracy of above function !!! """
true
d3a9f412143fd1304fe4e657bd476263ebec69d4
beade88/ejercicios_python_principiantes
/sentence_manage.py
526
4.34375
4
""" Mira, toma este : supón la cadena ‘esta es una cadena de texto’ conviértela a ‘Esta Es Una Cadena De Texto’ todas la letra inicial mayúscula. Simple pero usarás tres funciones básicas para procesar strings :) Q son split, join, list comprehension y capitalice """ sentence_1 = 'this is a text string' def sentence_manage(sentence): list_1 = sentence.split() list_2 = [list_1[i].capitalize() for i in range(len(list_1))] list_3 = ' '.join(list_2) print(list_3) sentence_manage(sentence_1)
false
4e98356bdc6f0df8b2715536dacf8f55a792f5a9
Nayan-Chimariya/Guess-the-number
/app.py
2,562
4.15625
4
#game game from random import randint import time import os guess_count = 5 hint_count = 3 def end_screen(): print("\nSee ya later loser! \n") time.sleep(1) exit() def counters(guess_count, hint_count): print(f"\nNumber of guess left = {guess_count}") print(f"Number of hints left = {hint_count}") def hint(correct,user_guess): global hint_count if hint_count != 0: if_hint = input("\nDo you want to use hint ? (Y/N): ").lower() if if_hint == 'y': hint_count -= 1 if user_guess < correct: print(f"\nHINT: your guess {user_guess} is lower than the answer") if user_guess > correct: print(f"\nHINT: your guess {user_guess} is higher than the answer") else: is_hint_left = False def main(): game_running = True is_hint_left = True is_guess_left = True global guess_count global hint_count print("\n---------------------------") print("welcome to Guess the number") print("---------------------------") counters(guess_count, hint_count) is_enter = input("\nPress [Enter] to play: ") if is_enter == "": random_number = randint(0,100) while game_running == True: correct = random_number try: user_guess = int(input("\nEnter your guess: ")) if user_guess == correct: print("🏆 Correct!") game_running = False print("\n----------------------------------") play_again = input("Do you want to play again ? (Y/N): ").lower() if play_again == 'y': os.system('cls') guess_count = 5 hint_count = 3 main() else: end_screen() else: print("-------------------\n") print("❌ Incorrect") print(f"Your guess = {user_guess}") guess_count -= 1 if guess_count == 0: is_guess_left = False game_running = False print(f"The correct answer was {correct}") print("\n----------------------------------") play_again = input("Do you want to play again ? (Y/N): ").lower() if play_again == 'y': os.system('cls') guess_count = 5 hint_count = 3 main() else: end_screen() if is_guess_left == True: counters(guess_count, hint_count) if is_hint_left == True: hint(correct,user_guess) except ValueError: pass else: end_screen() main()
true
e351e2fb38e050f759a81de0879297623723ffea
amir-jafari/Data-Mining
/01-Pyhton-Programming/3- Lecture_3(Python Adavnce)/Lecture Code/2-String_Objects-Example.py
290
4.25
4
word1 = 'Wow' word2 = 'Wow' print('Equal:',word1 == word2, ' Alias:',word1 is word2) name = input("Please enter your name: ") print("Hello " + name.upper() + ", how are you?") word = "ABCD" print(word.rjust(15, "*")) print(word.rjust(15, ">")) print(word.rjust(10)); print('#',50*"-")
false
4cd731424693d2ae3287132de455cd2a75c1e59f
taismassaro/stunning-engine
/anagram-finder/anagram_finder.py
559
4.125
4
with open('anagram_finder/2of4brif.txt') as in_file: words = in_file.read().strip().split('\n') words = [word.lower() for word in words] lookup_word = 'charming' anagrams = [lookup_word] for word in words: if word != lookup_word: # to find out if a word is an anagram of another, we can convert them into a list and sort the items in the list if sorted(word) == sorted(lookup_word): anagrams.append(word) if len(anagrams) <= 1: print(f"'{lookup_word}' has no anagrams") else: print(f"Anagrams: {anagrams}")
true
9605f705daf53c27cd8292df1a5b0c6cba86604f
TimurTimergalin/natural_selection
/simulation/app.py
2,141
4.15625
4
import pygame class App: """ Methods: set_variables create_sprite_groups main_loop run set_variables: Args: None Returns: None Set constant variables to use it in the simulation create_sprite_groups: Args: None Returns: None Create pygame.sprite.Group instances to use it in the simulation main_loop: Args: screen Returns: None The main loop of the simulation, that displays onto the screen run: Args: x y Returns: None Create screen X*Y and safely run the main loop """ def __init__(self): self.set_variables() self.create_sprite_groups() def set_variables(self): """ set_variables: Args: None Returns: None Set constant variables to use it in the simulation """ self.fps = 60 def create_sprite_groups(self): """ create_sprite_groups: Args: None Returns: None Create pygame.sprite.Group instances to use it in the simulation """ self.all_sprites = pygame.sprite.Group() self.creatures = pygame.sprite.Group() def main_loop(self, screen): """ main_loop: Args: screen Returns: None The main loop of the simulation, that displays onto the screen """ run = True clock = pygame.time.Clock() while run: # Game loop for event in pygame.event.get(): if event.type == pygame.QUIT: run = False screen.fill((0, 0, 0)) pygame.display.flip() clock.tick(self.fps) def run(self, x, y): """ run: Args: x y Returns: None Create screen X*Y and safely run the main loop """ pygame.init() screen: pygame.Surface = pygame.display.set_mode((x, y)) try: self.main_loop(screen) finally: pygame.quit()
true
9aa2b9c5089a3af7d75c3a1bd61af6c544efc00c
NagiReddyPadala/python_programs
/Python_Scripting/Pycharm_projects/DataStructures/Stack/IntToBinary.py
574
4.125
4
""" Use a stack data structure to convert integer values to binary 242 / 2 = 121 -> 0 121 / 2 = 60 -> 1 60 / 2 = 30 -> 0 30 / 2 = 15 -> 0 15/ 2 = 7 -> 1 7 / 2 = 3 -> 1 3 / 2 = 1 -> 1 1 / 2 = 0 -> 1 """ from DataStructures.Stack.stack import Stack def get_binary(dec_num): s = Stack() while dec_num > 0: remainder = dec_num % 2 s.push(remainder) dec_num = dec_num // 2 binary_num = "" while not s.is_empty(): binary_num += str(s.pop()) print("Binary number is: ", binary_num) get_binary(242)
false
927b69be4111dd0b12631e59cd8d42c3bb0e9074
gygergely/Python
/Misc/FizzBuzz/fizzbuzz.py
1,237
4.1875
4
def welcome(): """ Simple welcome message to the user. :return: None """ print('Welcome to the \'fizzbuzz\' game') def user_number_input(): """ Request a number from the user. :return: int """ while True: try: nr = int(input('Please enter a number between 1 and 100: ')) if nr < 1 or nr > 100: print('Range must be between 1 and 100') continue else: return nr except (TypeError, ValueError): print('Ups something went wrong') continue def get_fizzbuzz(number): """ In case the number is divisible with 3, it prints "fizz" instead of the number. If the number is divisible with 5, it prints "buzz". If it's divisible with both 3 and 5, it prints "fizzbuzz". :param number: end of number loop :return: None """ for nr in range(1, number + 1): if nr % 5 == 0 and nr % 3 == 0: print('fizzbuzz') elif nr % 5 == 0: print('buzz') elif nr % 3 == 0: print('fizz') else: print(nr) # PROGRAM STARTS HERE # ------------------- welcome() get_fizzbuzz(user_number_input())
true
4163960e911dc1a91fed505e1a348d5ffb6e9d25
AndreaCossio/PoliTo-Projects
/AmI-Labs/lab_1/e02.py
277
4.375
4
# Lab 01 - Exercise 02 # Retrieving the string string = input("Insert a string: ") # Checking length and printing if len(string) > 2: print("'" + string + "' yields '" + string[0] + string[1] + string[len(string) - 2] + string[len(string) - 1] + "'") else: print("")
true
e73464eaff804a0128456f9c37ad348b08856049
AndreaCossio/PoliTo-Projects
/AmI-Labs/lab_2/e01.py
1,214
4.25
4
# Lab 02 - Exercise 01 # List of tasks tasks = [] num = -1 # Main loop while num != 4: # Printing menu print("""Insert the number corresponding to the action you want to perform: 1. Insert a new task 2. Remove a task (by typing its content exactly) 3. Show all existing tasks, sorted in alphabetic order 4. Close the program""") # Catching exceptions and performing different actions try: num = int(input("> ")) if num == 1: new_task = input("\nPlease insert the task to insert: ") tasks.append(new_task) elif num == 2: del_task = input("\nPlease insert the task to remove: ") try: tasks.remove(del_task) except ValueError: print("It seems that the task you inserted does not already exist.") elif num == 3: print("\nInserted tasks:") for task in sorted(tasks): print(task) elif num == 4: print("\nExiting...") else: print("That didn't seem a valid number!") print() except ValueError: print("That didn't seem a number!")
true