blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
ac92b6bda92b4f22c28f9046af50b74678dbf183
CABT/Patrones
/primeraPrac.py
602
4.25
4
#x = 2 + 3 + 7; print y; #x = 10; #while x!=1: print x; x = x-1; #t = x * 100; #print t; #print "hello world", "this is a test"; #print "im trying to", "make a list of smallstmt"; #x = 10; #while x <= 100 and z!= 0 or y == 2*x : print y; x = x+1; #print "testing after while"; #y = 2 ** 3 + 4 * 5; #while x : x = x - 1; #print "another print cause why not" #if x > 9000 : print "its over 9000!"; #elif x < 100 : print "x menor a 100"; #elif x==0 : print "x es 0"; #si el cuerpo del while solo tiene una instruccion #hay que ponerla en la misma linea, sino, #el cuerpo se vuelve todo el programa :S
false
1fea315144e0819635ff6d9a81401eb839e0b18a
MingXu-123/CMU-15112-HW
/15112-CMU/week9/lec.py
1,500
4.1875
4
def factorial(n): if n == 1: return 1 else: return n * factorial(n - 1) print(factorial(5)) print("aaabbcaad") print("abcad") # recursive calls def shortenStrings(s): if len(s) == 1: return s else: if s[1] == s[0]: return shortenStrings(s[1:]) else: return s[0] + shortenStrings(s[1:]) print(shortenStrings("aaabbcaad")) # The fibonacci sequence is a mathematical sequence where each element is equal to # the sum of the two elements that came before it. This translates nicely into recursive code! def fib(n, depth = 0): # print("my n is", n) # print("fib(",n,") at depth",depth) print(depth*" |", "fib(", n, ")") if (n < 2): # Base case: fib(0) and fib(1) are both 1 return 1 else: # Recursive case: fib(n) = fib(n-1) + fib(n-2) return fib(n-1, depth + 1) + fib(n-2, depth + 1) print([fib(n) for n in range(15)]) # print(fib(5)) def merge(a, b): if len(a) == 0 or len(b) == 0: return a + b else: if a[0] < b[0]: return [a[0]] + merge(a[1:], b) else: return [b[0]] + merge(a, b[1:]) def mergeSort(lst): if len(lst) < 2: return lst else: mid = len(lst)//2 left = lst[:mid] right = lst[mid:] left = mergeSort(left) right = mergeSort(right) return merge(left, right) print(merge([1,2,4,7,9],[0,1,4,6,9])) print(mergeSort([83,45,21,23,5]))
true
eb750bbb4d37161b52a44d2179833240f2139ed6
MingXu-123/CMU-15112-HW
/15112-CMU/week1/week1/week1+.py
2,028
4.15625
4
import math from tkinter import * def drawClock(canvas, x0, y0, x1, y1, hour, minute): # draw a clock in the area bounded by (x0,y0) in # the top-left and (x1,y1) in the bottom-right # with the given time # draw an outline rectangle canvas.create_rectangle(x0, y0, x1, y1, outline="black", width=1) # find relevant values for positioning clock width = (x1 - x0) height = (y1 - y0) r = min(width, height)/2 cx = (x0 + x1)/2 cy = (y0 + y1)/2 # draw the clock face canvas.create_oval(cx-r, cy-r, cx+r, cy+r, outline="black", width=2) # adjust the hour to take the minutes into account hour += minute/60.0 # find the hourAngle and draw the hour hand # but we must adjust because 0 is vertical and # it proceeds clockwise, not counter-clockwise! hourAngle = math.pi/2 - 2*math.pi*hour/12 hourRadius = r*1/2 hourX = cx + hourRadius * math.cos(hourAngle) hourY = cy - hourRadius * math.sin(hourAngle) canvas.create_line(cx, cy, hourX, hourY, fill="black", width=1) # repeat with the minuteAngle for the minuteHand minuteAngle = math.pi/2 - 2*math.pi*minute/60 minuteRadius = r*9/10 minuteX = cx + minuteRadius * math.cos(minuteAngle) minuteY = cy - minuteRadius * math.sin(minuteAngle) canvas.create_line(cx, cy, minuteX, minuteY, fill="black", width=1) def draw(canvas, width, height): # Draw a large clock showing 2:30 drawClock(canvas, 25, 25, 175, 150, 2, 30) # And draw a smaller one below it showing 7:45 drawClock(canvas, 75, 160, 125, 200, 7, 45) # Now let's have some fun and draw a whole grid of clocks! width = 40 height = 40 margin = 5 hour = 0 for row in range(3): for col in range(4): left = 200 + col * width + margin top = 50 + row * height + margin right = left + width - margin bottom = top + height - margin hour += 1 drawClock(canvas, left, top, right, bottom, hour, 0)
true
46845b4b012f20367fca665c4b35e17bdff7dd65
Dualvic/Python
/Ejercicios iniciales py/Ejercicio 22.py
1,004
4.21875
4
# Repite el programa anterior, pero en vez de leer 5 números, el usuario ha # de indicar antes cuántos números van a ser leídos, indicándolo mediante # el mensaje: Introduzca cuántos números tienen que leerse por teclado: _ ## Inputs rangonumeros = int(input ("Introduzca cuántos números tienen que leerse por teclado: ")) ListaNumeros = [] contador = 0 while contador < rangonumeros: valorAintroducir = int(input("Escribe un numero aqui: ")) ListaNumeros.append(valorAintroducir) contador = contador + 1 ## PreConditions assert isinstance (ListaNumeros,list), "Internal Error" assert isinstance (valorAintroducir,int), "No es un numero" assert len(ListaNumeros) == rangonumeros, "Valor introducido no es igual al prefijado" ## Programa Principal if len(ListaNumeros) == rangonumeros: print ("El numero mas grande es", max(ListaNumeros)) print ("El numero mas pequeño es", min(ListaNumeros)) else: print ("Rango introducido incorrecto")
false
fce2608e4c098fc02ffa8a179df6b6d3abdcc46f
LiviaChaves/Python-Fundamentos
/AnaliseDeDados/Cap.03/Metodos.py
598
4.375
4
#MÉTODOS #Permitem executar ações específicas no objeto e podem também ter #argumentos, exatamente como função. # Criando uma lista lst = [2,36,12,14,17,42] # Usando um método do objeto lista lst.append(52) #add um novo item na lista print(lst) # Usando um método do objeto lista lst.count(12) # A função help() explica como utilizar cada método de um objeto help(lst.count) # A função dir() mostra todos os métodos e atributos de um objeto dir(lst) # O método de um objeto pode ser chamado dentro de uma função, como print() a = 'Isso é uma string' print (a.split())
false
9b7b356a0b05a7589de94dd0e6f4695f7c6950ce
spaul2010/Python
/Database/Database - Basic - Example - 1.py
793
4.375
4
# ------------------------------------------------------------------------------ # Database Example - Create Tables and Insert Data # ------------------------------------------------------------------------------ import sqlite3 # Step-1: Connect to Database db = sqlite3.connect("contacts.sqlite") # Step-2: Create the database table; Only if does not exists db.execute("CREATE TABLE IF NOT EXISTS contacts(name TEXT, phone INTEGER, email TEXT)") # Step-3: Insert data to the database table db.execute("INSERT INTO contacts(name, phone, email) VALUES('Hellos', 568471, 'sp@gmail.com')") db.execute("INSERT INTO contacts(name, phone, email) VALUES('Paul', 1254780, 'skp@gmail.com')") # Step-4: Commit the changes into the database db.commit() # Step-5: Close the database connection db.close()
true
05dd08248261d53e0caa3657ab46aec7adf2e8c4
KMSEOK/GitHub
/Python/Data Structures/Tree_v2.py
1,928
4.375
4
# 기존 Tree에서 left child, right child 활용 from turtle import right class Node: def __init__(self, data): self.data = data self.left_child = None self.right_child = None def get_data(self): return self.data def get_left(self): return self.left_child def get_right(self): return self.right_child def set_left_child(self, left): self.left_child = left def set_right_child(self, right): self.right_child = right class Tree: def __init__(self): self.root = None def get_root(self): return self.root def set_root(self, root): self.root = root def print_tree(self): self.print_node(self.root, 0) def print_node(self, node, depth): msg = "" if node is not None: for i in range(0, depth): msg += " " msg += node.get_data() print(msg) self.print_node(node.get_left(), depth + 1) self.print_node(node.get_right(), depth) tree = Tree() node_a = Node("A") node_b = Node("B") node_c = Node("C") node_d = Node("D") node_e = Node("E") node_f = Node("F") node_g= Node("G") node_h = Node("H") node_i = Node("I") node_j = Node("J") node_k = Node("K") node_l = Node("L") node_m = Node("M") node_n = Node("N") node_o = Node("O") node_p = Node("P") tree.set_root(node_a) node_a.set_left_child(node_b) node_b.set_left_child(node_e) node_b.set_right_child(node_c) node_e.set_left_child(node_k) node_e.set_right_child(node_f) node_k.set_right_child(node_l) node_f.set_right_child(node_g) node_g.set_left_child(node_m) node_c.set_left_child(node_h) node_c.set_right_child(node_d) node_h.set_left_child(node_n) node_h.set_right_child(node_i) node_d.set_left_child(node_j) node_j.set_left_child(node_o) node_o.set_right_child(node_p) tree.print_tree()
true
9cb35a4516247520970d9d836caef8510a4552ac
xinyushi/homework-0-template
/fizzbuzz.py
268
4.1875
4
""" fizzbuzz Write a python script which prints the numbers from 1 to 100, but for multiples of 3 print "fizz" instead of the number, for multiples of 5 print "buzz" instead of the number, and for multiples of both 3 and 5 print "fizzbuzz" instead of the number. """
true
46ee8f134641a9016619742ba1382db5368987f2
nipunsadvilkar/web-dev-deliberate-practice
/sql_intro/sqla.py
615
4.1875
4
""" Explore SQLite functionalty """ import sqlite3 # connect with given DB otherwise create new database conn = sqlite3.connect('new.db') # get a cursor object used to execute SQL commands cursor = conn.cursor() # create a table with given column cursor.execute("""CREATE TABLE population (city TEXT, state TEXT, population INT) """) cursor.execute("INSERT INTO population VALUES('NEW YORK CITY', \ 'NY', '8200000')") cursor.execute("INSERT INTO population VALUES('SAN FRANCISCO', \ 'CA', '8000000')") conn.commit() # close the database connection conn.close()
true
bbad81f029ba01976ce484b126b97bc2d2d0e2c8
qiwsir/LearningWithLaoqi
/PythonBase/03program.py
411
4.25
4
# coding:utf-8 ''' filename:03program.py Input a word, and then, find the vowels in it. ''' word = input("please input one word:") word = word.split()[0].lower() vowels = ["a", "e", "i", "o", "u"] word_vowels = [w for w in word if w in vowels] if bool(word_vowels): print("the word {0} include vowels {1}".format(word, word_vowels)) else: print("There is no vowels in the word {0}".format(word))
true
3d36deab9038ba3ff117b0d89e1ac9a85a3e32cf
lingtengkong/PyTutorial
/best practice /books.py
524
4.46875
4
def word_count(text, word=''): """ Count the number of occurences of ``word`` in a string. If ``word`` is not set, count all words. Args: text (str): the text corpus to search through word (str): the word to count instances of Returns: int: the count of ``word`` in ``text`` """ if word: count = 0 for text_word in text.split(): if text_word == word: count += 1 return count else: return len(text.split())
true
bcba9edabc8cca5b1bb7b3588e0427ba7da43fa4
v370r/projects
/pythonproject.py
1,533
4.1875
4
print("Welcome to my game") name= input("What is your name? ") age = int(input("Enter your age? " )) health = 10 print("YOu are starting with",health,"health") if age >= 18: print("You are old enough to play! ") wants_to_play = input("Do you want to play? ").lower() if wants_to_play == "yes": print("Lets play!.......") left_or_right = input("First Choice...Left or Right(left/right) ?").lower() if left_or_right == "left": ans = input("Nice,you followed the path and reached a lake.... DO you swim across or go around (across/around)? ") if ans =="around": print("You went around and reached the other side of lake") elif ans == "across": print("You managed to get across ,but were bit by a fish and lost 5 health.") health -=5 ans = input("You notice a house and a river.. which do you go for? ") if ans =="house": print("you go to the house and are greeted by the owner...He doesnt like you and you loose 5 health") health -=5 if health <=0: print("You now has 0 health and you lost the game....") else: print("You survived!........") else: print("You fell in river and lost") else: print("You fell down and lost ...") else: print("Cya...") else: print("You aren't old enough to play .......")
true
926bd1441ac0331910f44d47bb10c2395c3dd836
Priyankakore21/Dailywork
/PYTHON Training/day4/exercise_7/Problem12.py
1,059
4.46875
4
Question 1. Write a Python program to convert a temperature given in degrees Fahrenheit to its equivalent in degrees Celsius. You can assume that T_c = (5/9) x (T_f - 32), where T_c is the temperature in °C and T_f is the temperature in °F. Your program should ask the user for an input value, and print the output. The input and output values should be floating-point numbers. program : T_f = float(input("Please enter a temperature in °F: ")) T_c = (5/9) * (T_f - 32) print("%g°F = %g°C" % (T_f, T_c)) Question 2. What could make this program crash? What would we need to do to handle this situation more gracefully? Ans = The program could crash if the user enters a value which cannot be converted to a floating-point number. We would need to add some kind of error checking to make sure that this doesn’t happen – for example, by storing the string value and checking its contents. If we find that the entered value is invalid, we can either print an error message and exit or keep prompting the user for input until valid input is entered.
true
283a08cd614b31de5aacba39f3e23d48360cf118
zyga/arrowhead
/examples/tutorial1.py
2,447
4.28125
4
#!/usr/bin/env python3 """ Tutorial Lesson 1 ================= This is the first tutorial arrowhead program. This program simply prints 'hello world' they way you would expect it to. In doing so it introduces three core features of arrowhead: flow, step and arrow. Flow - the flow class is where flow programs are defined. While they look like normal classes they behave a little bit like magic so keep that in mind. @step - the step decorator can convert regular methods into special step classes. Each step class wraps the method that was decorated and adds local state and meta-data. Local state like just like local variables that you would assign in regular programs but they live beyond the lifetime of the call to the wrapped method. It may be easy to miss but the first argument of each step method is not self (implying that it would be related to the flow) but actually 'step'. It does in fact refer to a step object. Step objects (and classes) are entirely empty except for the ``Meta`` attribute and the __call__ method that is the decorated function itself. Step management is explained further in the tutorial. If you don't understand any of that then just keep in mind that @step does quite a bit of magic and you should not treat anything decorated as such as a normal method anymore. Oh, and each flow needs at least one accepting state or it will never stop. @arrow - the arrow decorator is how you navigate between steps. Instead of performing direct calls to other methods you let arrowhead do that for you. All you have to do is to statically declare where you want to go (and as you will later see, how to decide which arrow to follow if more than arrow is used). Arrows are less drastic than '@step' as they simply add some meta-data that the engine later uses. That's it for this lesson. Make sure to run this program with '--help' to see additional options. You can experiment with them all you like. I would especially recommend '--trace x11' (in this case perhaps with '--delay 5'). For more hardcore users you will want to see '--dot'. Read on to tutorial lesson 2 to see subsequent features being introduced. """ from arrowhead import Flow, step, arrow, main class HelloWorld(Flow): @step(initial=True) @arrow(to='world') def hello(step): print("Hello...") @step(accepting=True) def world(step): print("... world!") if __name__ == '__main__': main(HelloWorld)
true
3b6590425bc52be9da50ac9e4cb4835031dcdc5b
udaymohannaik/dsp
/mat_mul.py
1,082
4.3125
4
def print_matrix(matrix): for i in range(len(matrix)): for j in range(len(matrix[0])): print(matrix[i][j]) print("\n") for h in matrix: print (h) #def main(): a=int(input("matrix 1 rows:")) b=int(input("matrix 1 columns:")) c=int(input("matrix 2 rows:")) d=int(input("matrix 2 columns:")) if(b!=c): print("matrix multiplication is not possible:") exit() #declaration of arrays array1=[[0 for j in range (0,b)] for i in range (0,a)] array2=[[0 for j in range (0,d)] for i in range (0,c)] result=[[0 for j in range (0,d)] for i in range (0,a)] print ("enter 1st matrix elements:" ) for i in range(0 , a): for j in range(0 , b): array1[i][j]=int (input("enter element")) print ("enter 2nd matrix elements:") for i in range(0 , c): for j in range(0 , d): array2[i][j]=int(input("enter element")) print ("1st matrix") print_matrix(array1) print ("2nd matrix") print_matrix(array2) for i in range(0 , a): for j in range(0 , d): for k in range(0 , b): result[i][j] += array1[i][k] * array2[k][j] print ( "multiplication of two matrices:" ) print_matrix(result)
false
ae2de18f61758658f8cdfeefb8f01a7966183654
GuillhermeLeitte/Blue-Python
/sistema-senha.py
529
4.15625
4
""" #01 - Escreva um programa que pede a senha ao usuário, e só sai do looping quando digitarem corretamente a senha: """ senha = int(input('Digite a senha; ')) while senha != 1095: print('Senha incorreta. \n Digite nova senha:') senha = int(input('Digite a senha: ')) if senha == 1095: print('Senha correta, Abrindo sistema...') """ n = 1 while n != 0: # O while é um laço com condição de parada, ENQUANTO o n for diferente de zero, faça... n = int(input('Digite um valor: ')) print('Fim') """
false
8fc548c3df499d54dd63f544170d190cdd8fa352
SunnyRo/Python
/Projects/project1/Task1.py
2,449
4.125
4
""" Name: Son Vo Course: CS-3310-SPR20 Project: 1 Due: 03/06/20 Description: Program Merge Sort and Quick Sort to sort a list of n elements with n = 10000, 20000, 50000, 100000, 200000, 500000, 1000000, ... """ import random import time # ask user to enter number of elements for creating a list. n = int(input("Please enter the number of elements\n")) # creating a list with n elements random value randomlist1 = random.sample(range(0, n * 1000), n) randomlist2 = randomlist1.copy() # merge sort def mergeSort(arr): if len(arr) > 1: mid = len(arr) // 2 left = arr[:mid] right = arr[mid:] mergeSort(left) mergeSort(right) i = j = k = 0 while i < len(left) and j < len(right): if left[i] < right[j]: arr[k] = left[i] i += 1 else: arr[k] = right[j] j += 1 k += 1 while i < len(left): arr[k] = left[i] i += 1 k += 1 while j < len(right): arr[k] = right[j] j += 1 k += 1 # quick sort def partition(arr, low, high): i = low - 1 pivot = arr[high] for j in range(low, high): if arr[j] < pivot: i = i + 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return i + 1 def quickSort(arr, low, high): if low < high: pi = partition(arr, low, high) quickSort(arr, low, pi - 1) quickSort(arr, pi + 1, high) # creating a menu enter 1 if we want to see the execution time, 2 if want to see if both functions actually sort the list print("Enter 1 to see execution time") print("Enter 2 to see list before and after sorting") menu = int(input("")) if menu == 1: start_time1 = time.time() # start time mergeSort(randomlist1) # execution time = end time - start time print("--- Merge Sort: %.8f seconds ---" % (time.time() - start_time1)) start_time2 = time.time() quickSort(randomlist2, 0, n - 1) print("--- Quick Sort: %.8f seconds ---" % (time.time() - start_time2)) else: print("\nunordered lists:") print(randomlist1) print("\nList 1 after Merge Sort:") mergeSort(randomlist1) print(randomlist1) print("\nList 2 after Quick Sort:") quickSort(randomlist2, 0, len(randomlist2) - 1) print(randomlist2)
true
1f170067757462afb206b1fe32bac473c91a6842
Livingdead1989/com404
/TCA 1/bonus points/functions.py
1,356
4.3125
4
# function which performs the action selected by the user def actions(option, the_word): # action for under if(option == 1): print(the_word) print("*" * len(the_word)) # action for over elif(option == 2): print("*" * len(the_word)) print(the_word) # action for both elif(option == 3): print("*" * len(the_word)) print(the_word) print("*" * len(the_word)) # action for grid elif(option == 4): rows = int(input("Number of rows: ")) columns = int(input("Number of columns: ")) print("\n") # series of for loops to create the rows and columns based on the users input for row in range(0, rows): # top border row print(" ", end="") for column in range(0, columns): print("*" * len(the_word) + " ", end="") print("\n") # middle text row print("| ", end="") for column in range(0, columns): print(the_word + " | ", end="") print("\n") # bottom border row print(" ", end="") for column in range(0, columns): print("*" * len(the_word) + " ", end="") else: print("Error")
true
84caf8e191aa7f70f8f869cf5d771aadc1c9fbee
Livingdead1989/com404
/2-guis/1-classes-and-objects/bot.py
1,246
4.125
4
# Creating the class class Bot: # Constructor Init # anything following a default value should have a default value def __init__(self, name, age=0): self.name = name self.age = age self.energy = 10 self.shield = 10 def display_name(self): print("-" * (len(self.name) + 4)) print("| {} |".format(self.name)) print("-" * (len(self.name) + 4)) def display_age(self): print("*" * (len( str(self.age) ) + 4) ) print("|" * (len( str(self.age) ) + 4) ) print("-" * (len( str(self.age) ) + 4) ) print("| {} |".format(self.age)) print("-" * (len( str(self.age) ) + 4) ) def display_energy(self): print("Energy:", "X" * self.energy) def display_shield(self): print("Shield:", "O" * self.shield) def display_summary(self): print("My name is", self.name) print("I am", self.age) print("My current energy level is", self.energy) print("My shields are at", self.shield) my_bot = Bot("William", 7) #my_bot.display_name() #my_bot.display_age() #my_bot.display_energy() #my_bot.display_shield() my_bot.display_summary()
false
88c3fb392c960f6f47f98e43f4854c4c02a41637
Livingdead1989/com404
/1-basics/3-decision/9-or-operator/bot.py
321
4.15625
4
adventure_type = input("enter the type of adventure ") if( (adventure_type == 'scary') or (adventure_type == 'short') ): print("Entering the dark forest!") elif( (adventure_type == 'safe') or (adventure_type == 'long') ): print("Taking the safe route!") else: print("Not sure which route to take.")
true
49f32905b2e6cceb983fce31eb870bd5017de05f
Livingdead1989/com404
/1-basics/4-repetition/python.py
1,941
4.28125
4
### SIMPLE FOR LOOPS ## Activity 3: Range # brightness = int(input("What level of brightness is required? ")) # print("You have selected:", brightness) # for x in range(2, brightness, 2): # print("Beep's brightness level: ", ("*" * x)) # print("Bop's brightness level: ", ("*" * x)) # print("\n") ## Activity 4: Characters # markings = input("What strange markings do you see? ") # print("You saw the following markings:", markings, "\n") # for m in range(0, len(markings), 1): # print("index " + str(m) + ":", markings[m]) ## Activity 5: Reverse Word # phrase = input("What phrase do you see? ") # reverse = "" # print("You saw the phrase:", phrase, "\n") # print("Reversing...\n") # for p in range((len(phrase)-1), -1, -1): # reverse = reverse + phrase[p] # print("The phrase is:", reverse) ### NESTED LOOPS ## Activity 1: Nested Loop # rows = int(input("How many rows should I have?\n")) # columns = int(input("How many columns should I have?\n")) # print("Here I go:") # for r in range(0, rows, 1): # for c in range(0, columns,1): # print(":) ", end="") # print("\n") # print("Done!") ## Activity 2: Nestings sequence = input("Please enter a sequence consisting of dashes and two markers\n") marker = input("Please enter the character for the marker e.g. 'x'\n") print("\n") position_counter = 0 first_marker = 0 last_marker = 0 for mark in (sequence): position_counter += 1 # if the character matches if(mark == marker): # if first_marker has a value if(first_marker > 0): last_marker = position_counter # else set first_marker else: first_marker = position_counter print("The distance between the markers is:", (last_marker - first_marker -1)) # find the first marker, store position # find the second marker, store position # calculate the difference between the two
true
f1514d6f540d50a7648ce49c460d70b4c5cfbca6
gorgyboy/holbertonschool-higher_level_programming
/0x0B-python-input_output/4-append_write.py
286
4.1875
4
#!/usr/bin/python3 ''' I/O module ''' def append_write(filename="", text=""): ''' Appends a string at the end of a text file (UTF8) and returns the number of characters added. ''' with open(filename, mode='a', encoding='utf-8') as f: return f.write(text)
true
08f1a9c89937d4cf388c6516f575d24b41b9e858
bhandarisantosh757/Python-Project
/primes.py
1,012
4.1875
4
""" generate list of first 50 prime numbers sqrt() """ import math import time # functions => arguments/parameters def is_prime(num): op = num - 1 is_prime = True while op > 1: if num % op == 0: is_prime = False op -= 1 return is_prime def is_prime2(num): op = num - 1 while op > 1: if num % op == 0: return False op -= 1 return True def is_prime2_5(num): op = 2 while op < num: if num % op == 0: return False op += 2 return True def is_prime3(num): for i in range(2, int(math.sqrt(num)) + 1): if num % i == 0: return False return True # this will override the name of above function # is_prime = False # print(op) # print(is_prime2(13)) #is_prime(14) #is_prime(15) #is_prime(16) #is_prime(17) # start = time.time() for num in range(1000): if is_prime2_5(num): print("Number: {} is a prime".format(num)) # print(time.time() - start)
false
767ce553b5e3b1a2396ab5610d9cd9531774f3ec
hongs1234/ICS4U-Classwork
/Classes/prep_for_test.py
950
4.1875
4
# Q1 class Food: """Food Class Attributes: name(str): the name of the food cost(int): how much the food costs nutrition(int): """ def __init__(self, name: str, cost: int, nutrition: int): self.name = name self.cost = cost self.nutrition = nutrition food = Food("Bread", 4, 10) #Q2 class Dog: """Dog Class Attributes: name(str): name of the dog breed(str): breed of dog happiness(int): happiness level of dog """ def __init__(self, name: str, breed: str): self.name = name self. breed = breed self.happiness = 100 def eat(self, food): self.happiness += int((food.nutrition * 0.1)) def bark(): print("RUFF RUFF!") def __str__(): print(f"""Name: {name} Happiness: {happiness}""") food = Food("Bread", 6, 10) dog = Dog("Jok", "Dalmation", 5) print(dog.__str__)
true
36817783671ae6b5bccc26614bd892c8af424af0
Guilherme2020/ADS
/Algoritmos 2016-1/LOP/mediaNotas.py
390
4.125
4
print(''' CALCULO FINAL ''') notaOne = float(input("Digite a sua primeira nota: ")) notaTwo = float(input("Digite a sua segunda nota: ")) notaThree = float(input("Digite a sua terceira nota: ")) mediaFinal = notaOne+notaTwo+notaThree/3 if mediaFinal >= 7: print("Aprovado") elif mediaFinal > 5 or mediaFinal < 7: print("Recuperacao") elif mediaFinal < 5: print("Reprovado")
false
c5097435160f4e61ae21e51004137c22c7a781d7
zzy0371/Py1901Advance
/day0401/demo1.py
783
4.1875
4
""" 类 与对象(实例) 类:模板定义属性和方法的封装 实例:具体的类对象 ,类的表现 1实例属性会根据实例不同而不同,类属性由类决定 2实例属性通常在构造赋值 3类属性(类变量)属于类 , 实例属性属于实例 实例确定,实例属性确定 实例可以调用类属性 ,类不可以调用实例属性 """ class Good(): name = 'tea' def __init__(self, _addr): self.addr = _addr g1 = Good("fujian") g2 = Good("guangdong") print(g1.addr,g2.addr,g1.name,g2.name) Good.name = 'coffee' print(Good.name, g1.name) # print(id(g1), id(g2)) # print(id(g1.name), id(g2.name), id(Good.name)) # 给g1对象添加name 属性 g1.name = 'cookle' print(id(g1.name), id(g2.name), id(Good.name))
false
90a3a8d1a4a00936bd71f5ac31bb251e765921c6
zhdankras/Learn
/Learn/task165.py
826
4.25
4
# Написать функцию max_multiple(divisor, bound), которая определяет максимальное N, # которое делится на divisor, меньше или равно bound и больше нуля # # Примеры: # max_multiple(2,7) ==> 6 # max_multiple(10,50) ==> 50 import traceback def max_multiple(divisor, bound): t = None N = 0 while N <= bound: if N % divisor == 0: t = N N+=1 return t # Тесты try: assert max_multiple(7, 100) == 98 assert max_multiple(37, 100) == 74 assert max_multiple(4, 1) == 0 assert max_multiple(1, 1) == 1 assert max_multiple(7,17) == 14 except AssertionError: print("TEST ERROR") traceback.print_exc() else: print("TEST PASSED")
false
06a765adca6d783f67eca5077b45c92327c21d0e
Sangee23-vani/python
/section_8/methods.py
921
4.28125
4
# Functions inside the Class is called as Methods class Dog(): species = 'Mammal' def __init__(self,breed,name,age,spot): # Like Constructor. self parameter mandatory self.breed = breed self.name = name self.age = age self.spot = spot def bark(self,number): print('{} barks as WOOF! and the number is {}'.format(self.name,number)) my_dog = Dog('Lab','Eben',3,False) # Need not to give value for self print('My Dog {} {} {} {}'.format(my_dog.name,my_dog.breed,my_dog.age,my_dog.spot)) my_dog.bark(23) # EXAMPLE 2 class Circle(): # CLASS OBJECT ATTRIBUTE pi = 3.14 def __init__(self,radius = 1): self.radius = radius def get_circumference(self): return 2 * self.pi * self.radius my_circle = Circle() my_new_circle = Circle(7) print(my_circle.get_circumference()) print(my_new_circle.get_circumference())
true
58e215a027b6b6c320e0d50cb169575fbb7e5433
genessym/PythonHardWay
/ex19.py
2,177
4.28125
4
# Creates a function that takes two arguments def cheese_and_crackers(cheese_count, boxes_of_crackers): # prints the statement "You have '20'cheeses! print "You have %d cheeses!" % cheese_count # prints the statement "You have 30 boxes of crackers!" print "You have %d boxes of crackers!" % boxes_of_crackers # prints the statment "Man that's enough for a party!" print "Man that's enough for a party!" # prints the statement "Get a blanket" and skips # to the next line print "Get a blanket.\n" # prints the statement below as is print "We can just give the function numbers directly:" # gives the value to the two arguments cheese_count and boxes_of_crackers cheese_and_crackers(20, 30) # prints the statement below as is print "OR, we can use variables from our script:" # assigns the value 10 to amount_of_cheeses amount_of_cheese = 10 # assigns the value of 50 to amountof_crackers amount_of_crackers = 50 # the value 10 and 50 assigned to cheese_count, boxes_of_crackers cheese_and_crackers(amount_of_cheese,amount_of_crackers) # print the statement below as is print "We can even do math inside too:" # 20 gets assigned to cheese_count & 11 assigned to boxes_of_crackers cheese_and_crackers(10 + 20, 5 + 6) # 100 gets assigned to amount_of_cheese and 1000 gets assigned to amount_of_crackers cheese_and_crackers(amount_of_cheese + 100,amount_of_crackers + 1000) def smores (graham_crackers, chocolate_bars): print "We have %d graham crackers" % graham_crackers print "And we have %d chocolate bars" % chocolate_bars print "Let's make some smores!!" print "Printing numbers directly:" smores (50,25) print "\nAdding numbers:" smores(10+20,30 + 40) print"\nVariables:" graham_crackers = 1000 chocolate_bars = 4000 smores(graham_crackers,chocolate_bars) print "\n variables and adding:" smores(graham_crackers +325, chocolate_bars + 375) #Raw input attempt print ("\n") graham = int(raw_input("How many graham crackers do we have?\n>")) chocolate = int(raw_input("How many chocolate bars do we have?\n>")) print ("We have %d graham crackers and %d chocolate bars.") % (graham,chocolate) print "Let's make smores!"
true
d57dc6c0e6ee059cbb4c06f14c2c57752806e4d7
roppan/Homework-Unit3
/Homework-Unit3/NumberChain.py
885
4.21875
4
# Initial variable to track game play play = "y" # Set start and last number last_number = 0 # While we are still playing... while play == "y": # Ask the user how many numbers to loop through x =int (input("How many numbers?")) x+=last_number # Loop through the numbers. (Be sure to cast the string into an integer.) for i in range (last_number, x): # Print each number in the range print(f'{last_number}: last_number') print(f'{x}: x') # Set the next start number as the last number of the loop last_number = last_number + 1 play = input("Continue the chain:(y)es or (n)o? ") if play == "n": 'break' elif play =="y": 'continue' else: # Once complete... ask if the user wants to continue play = input("Choose y or n! no other option") 'continue'
true
4e12f8bdb25268c91039a01124914b81abd886c8
natalia-sa/recursao-em-python
/recursao.py
1,422
4.46875
4
# coding: utf-8 #Exercícios de recursão em python """ 1. O fatorial de um número natural n é o produto de todos os inteiros positivos menores ou iguais a n. Crie a chamada recursiva de n fatorial""" def fatorial(n): if n == 1: return 1 return n* fatorial(n - 1) """implemente uma função reccursiva que, dados dois números inteiros x e n, calcula o valor de x ** n""" def exponencial(x, n): if n == 0: return 1 return x * exponencial(x, n - 1) """Usando recursividade, calcule a soma de todos os valores de um array de reais""" def soma(a, n): if n == len(a): return 0 return a[n] + soma(a, n + 1) """Dado um array de inteiros inverta a posição dos seus elementos""" def inverte(a, i): if i == len(a) / 2: return a a[i], a[len(a) - i - 1] = a[len(a) - i - 1], a[i] return inverte(a, i + 1) """Em uma função recursiva determine quantas vezes um digito k ocorre em um numero naturaln.""" def conta_digito(d, n, i): n = str(n) d = str(d) if i == len(n): return 0 if n[i] == d: return 1 + conta_digito(d, n, i + 1) return conta_digito(d, n, i + 1) """O máximo divisor comum de dois números inteiros x e y pode ser calculado usando-se uma definição recursiva: mdc(x, y) = mdc(x - y, y) , se x > y mdc(x, y) = mdc(y,x) mdc(x, x) = x """ def mdc(x, y): if x == y: return x if x > y : return mdc(x - y, y) return mdc(y, x)
false
2ef5005b1e9905a49b7031c32819c92f69b77fd7
robgoyal/LearnCodeTheHardWay
/Python/ex29/ex29_firstex.py
1,016
4.15625
4
#!/usr/bin/env/python # What If # Code written by Robin Goyal # Created on July 9, 2016 # Last updated on July 9, 2016 # ANSWERS TO STUDY DRILL QUESTIONS # The if statement evaluates the condition and if its true, it'll run the code within the if block # The code is indented so the interpreter knows the code that is in the if-block # If it isn't indented, that code will not run under the if-block people = 25 cats = 15 dogs = 10 if people < cats: print "Too many cats! The world is doomed!" if people > cats: print "Not many cats! The world is saved!" if people < dogs: print "The world is drooled on!" if people > dogs: print "The world is dry" dogs += 5 if people >= dogs: print "People are greater than or equal to dogs." if people <= dogs: print "People are less than or equal to dogs." if people == dogs: print "People are dogs." if not(True and False): print "This is False" if True or False: print "This is True" if not(False): print "This is also True"
true
585713394476dee2329e5f837cf864bff945d6a7
robgoyal/LearnCodeTheHardWay
/Python/ex6/ex6_firstex.py
1,207
4.375
4
#!/bin/python2 # Strings And Text # Initialize x to "There are 10 types of people" with string formatter x = "There are %d types of people." % 10 # Initializing binary to "binary" binary = "binary" # Initializing do_not to "don't" do_not = "don't" # Initializing y to "Those who know binary and those who don't" with string formatters y = "Those who know %s and those who %s." % (binary, do_not) # Print "There are 10 types of people" print x # Print "Those who know binary and those who don't" print y # Print "I said: There are 10 types of people" with %r string formatter print "I said: %r." % x # Print "I also said: "Those who know binary and those who don't"" print "I also said: '%s'." % y # Initialize hilarious to False hilarious = False # Initialize joke_evaluation to "Isn't that joke so funny?! False" with string formatter joke_evaluation = "Isn't that joke so funny?! %r" # Print joke_evaluation with the string formatter print joke_evaluation % hilarious # Initialize w with "This is the left side of ..." w = "This is the left side of ... " # Initialize e with "a string with a right side." e = "a string with a right side." # Prints the concactenation of the two strings print w + e
false
8e376851b77f9cbde95286ab19f5123c4a0d3988
HienH/Python-module-2
/chapter11_the_while_loop/dicegame.py
1,176
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 18 13:52:25 2018 @author: hienh """ from random import randint def diceGame(): print("Guess whether the random number is odd or even") rounds = int(input("how many rounds do you want to play? ")) result = "playing" while rounds> 0: number1 = randint(1,6) number2 = randint(1,6) number = number1 + number2 print(number1) print(number2) answer = input("is the number odd or even? ") if number % 2 == 0 and answer == "even": result = "win" print(result) print("Congratulation you have successfully guessed correctly, You win :} ") break; elif number % 2 == 1 and answer == "odd": result = "win" print("Congratulation you have successfully guessed correctly, You win :} ") break; else: print("wrong guess, try again. You have", rounds, "left") rounds = rounds - 1 if result != "win": print("oh no! Your out of guesses, You lose :{ ") print("game over") diceGame()
true
df2d8489e45b603f514502f3d1d5b07e9ef912f4
shuixingzhou/learnpythonthehardway
/ex41.py
1,351
4.25
4
#!usr/bin/env python3 #-*- coding: utf-8 -*- class TheThing(object): def __init__(self): self.number = 0 def some_function(self): print('I got called.') def add_me_up(self,more): self.number += more return self.number #two different things a = TheThing() b = TheThing() a.some_function() b.some_function() print(a.add_me_up(20)) print(b.add_me_up(30)) print(a.number) print(b.number) #Study this. This is how you pass a variable #from one class to another. You will need this. class TheMultiplier(object): def __init__(self,base): self.base = base def do_it(self,m): return m * self.base x = TheMultiplier(a.number) print(x.do_it(b.number)) # Animal is a object (yes, sort of confusion) look at the extra credit class Animal(object): pass ##?? class Dog(Animal): def __init__(self,name): self.name = name class Cat(Animal): def __init__(self,name): self.name = name class Person(object): def __init__(self,name): self.name = name ## Person has a pet of some kind self.pet = None class Employee(Person): def __init__(self, name, salary): ## Hmm, what is this strange magic? super(Employee,self).__init__(name) self.salary = salary class Fish(object): pass class Salmon(Fish): pass class Halibut(Fish): pass ## rover is a Dog rover = Dog('Rover') satan = Cat('Satan') mary = Person('Mary')
true
378e9470c571b8d543456ee7df28a428ff0f46dc
SebastianGo50/LearningPython
/D26 List and Dictionary comprehensions/main.py
1,183
4.3125
4
import pandas import csv # This part creates a dictionary which has all the letters and their according words with open("nato_phonetic_alphabet.csv", mode="r") as alphabet_file: content = csv.reader(alphabet_file) my_dict = dict((rows[0], rows[1]) for rows in content) del my_dict["letter"] # deletes first pair (letter,code), as it is not needed # this part first asks for a name as an input # then it iterates through it and adds lists to a list, with the corresponding alphabet words input_text = (input("Enter your name: ")).upper() # Alternative with less list comprehension: # new_list_with_al_words = [] # for letter in input_text: # word = (value for (key, value) in my_dict.items() if key == letter) # new_list_with_al_words.append(word) new_list_with_al_words = [[value for (key, value) in my_dict.items() if key == letter] for letter in input_text] print(new_list_with_al_words) # solution of course: data = pandas.read_csv("nato_phonetic_alphabet.csv") phonetic_dict = {row.letter: row.code for (index, row) in data.iterrows()} word = input("Enter a word: ").upper() output_list = [phonetic_dict[letter] for letter in word] # print(output_list)
true
5efb1e3f307c3c87336415fb85d6691fd0df83d6
Patipat-s/Python_test
/ex15.py
337
4.125
4
num1 = int(input("Fill num1 : ")) num2 = int(input("Fill num2 : ")) num_sum = num1 + num2 if num_sum > 0: if num_sum%2 == 0: print("Positive Even") else: print("Positive Odd") elif num_sum < 0: if num_sum%2 == 0: print("Negative Even") else: print("Negative Odd") else: print("Zero")
false
06d26cf0fd490f7f8d34d0c322d2fbcc785671f8
JosueHernandezR/Analisis-de-algoritmos-ESCOM
/Practica2/Fibonacci/Recursivo/main.py
1,099
4.125
4
#Análisis de Algoritmos 3CV2 # Alan Romero Lucero # Josué David Hernández Ramírez # Práctica 2 Fibonacci Recursivo # En este archivo ejecuta el programa completo # va insertando las duplas de los numeros fibonacci para después graficarlas # mediante el uso de listas (parametros) from fibonacci import fibonacci from grafica import graph def main ( ): n, parameters = -1, [ ] while ( n <= 0 ): n = int ( input ( "\n\tFibonacci Number to Calculate: " ) ) # fibonacci (n): devuelve una lista de tuplas con los números de Fibonacci # y el tiempo computacional del algoritmo [(F (n), T (n))]. for i in range ( 1, n + 1 ): parameters.append ( fibonacci ( i, 0 ) ) #va imprimiendo cada dupla de numeros fibonacci en la lista en cada iteracion del ciclo print("\t",parameters) print ( "\n\tFibonacci ( ", n, " ): ", parameters [ len ( parameters ) - 1 ] [ 0 ], "\n" ) # Imprime los números fibonacci guardados en la lista print(len(parameters)) # Crea la gráfia con los parametros creados. graph ( parameters [ len ( parameters ) - 1 ], parameters, n ) main ( )
false
8b0ae1661fec39606496a481a932879d2ffdb14a
BiKodes/python-collectibles
/recursion-recursive-functions/direct-recursion.py
2,027
4.15625
4
# Print numbers using recursion: def printnum(lr, ur): if lr > ur: return print(lr) printnum(lr + 1, ur); #recursive call n = int(input("Enter number:")) printnum(1, n) # Printing pyramid pattern def printn(num): if (num == 0): return print("*", end=" ") printn(num - 1) #recursive call to printn function def pattern(n, i): if (n == 0): return printn(i) print("\n", end="") pattern(n - 1, i + 1) #recursive call to pattern n = int(input("Enter number:")) pattern(n, 1) # Print Fibonacci number: def Fibonacci(n): if n < 0: print("Incorrect input") elif n == 0: return 0 #base case elif n == 1 or n == 2: return 1 #base case else: return Fibonacci(n - 1) + Fibonacci(n - 2) #recursive call to the function n = int(input("Enter number of terms: ")) i = 0 for i in range(n): print(Fibonacci(i), end="\t") # This is a recursive function to find the factorial of an integer: def factorial(x): if x == 1: return 1 #base case else: return (x * factorial(x-1)) num = 3 print("The factorial of", num, "is", factorial(num)) # Recursion in with a list: def sum(list): if len(list) == 1: return list[0] else: return list[0] + sum(list[1:]) print(sum([ 5, 8, 4, 8, 10])) # Factorial with recursion: def factorial(n): if n == 1: return 1 else: return n * factorial(n-1) print(factorial(3)) # Count Down to Zero: def countdown(n): print(n) if n > 0: countdown(n -1) # Factorial Function: def factorial(n): print(f"factorial() called with n = {n}") return_value = 1 if n<= 1 else n * factorial(n -1) print(f"-> factorial({n}) returns {return_value}") return return_value factorial(4) def get_recursive_factorial(n): if n < 0: return -1 elif n < 2: return 1 else: return n * get_recursive_factorial(n*1) get_recursive_factorial(10)
true
fa4fcea614752511a01b45745359cc2ed5750f0c
BiKodes/python-collectibles
/generators/generator-expressions.py
1,228
4.125
4
# List comprehension produces the complete list of items at once: a = range(6) print("List comprehension", end=':') b = [x + 2 for x in a] print(b) # generator expression which returns the same items but one at a time: print("Generator expression", end=':n') c=(x+2 for x in a) print(c) for y in c: print(y) # Generator functions can be used within other functions as well: a = range(6) print("Generator expression", end=':n') c = (x+2 for x in a) print(c) print(min(c)) cookie_list = ["Raspberry", "Choc-Chip", "Cinnamon", "Oat"] cookie_generator = (cookie for cookie in cookie_list) for cookie in cookie_generator: print(cookie) # Reading Large Files: csv_gen = (row for row in open(file_name)) nums_squared_gc = (num**2 for num in range(5)) # Creating Data Pipelines With Generators: file_name = "techcrunch.csv" lines = (line for line in open(file_name)) list_line = (s.rstrip().split(",") for s in lines) cols = next(list_line) company_dicts = (dict(zip(cols, data)) for data in list_line) funding = ( int(company_dict["raisedAmt"]) for company_dict in company_dicts if company_dict["round"] == "a" ) total_series_a = sum(funding) print(f"Total series A fundraising: Ksh.{total_series_a}")
true
a8d022148017995a414216226ed97ad6b5f5c35b
Pasupathi9897/testdemo
/pratice.py
1,690
4.46875
4
import numpy as np my_list=[1,2,3] print(my_list) print(np.array(my_list)) my_matric=[[1,2,3],[4,5,6],[7,8,9]] print(my_matric) print(np.array(my_matric)) #arrange:Return evenly spaced values within a given interval print(np.arange(0,10)) print(np.arange(0,11,3)) #Generate arrays of zeros or ones print(np.zeros(3)) print(np.zeros((5,5))) print(np.ones(3)) print(np.eye(4))#diadonal elements #random #Numpy also has lots of ways to create random number arrays: #rand #Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1]. print(np.random.rand(3)) print(np.random.rand(5,5)) #rand:Return a sample (or samples) from the "standard normal" distribution. Unlike rand which is uniform print(np.random.randn(3)) print(np.random.randn(5,5)) #randint:Return random integers from low (inclusive) to high (exclusive) print(np.random.randint(4,10)) print(np.random.randint(1,100,10)) #array attributes and methos:Let's discuss some useful attributes and methods or an array aar=np.arange(25) aar1=np.random.randint(0,50,10) print(aar) print(aar1) #reshape:Returns an array containing the same data with a new shape print(aar.reshape(5,5)) #max,min,argmin,argmax:These are useful methods for finding max or min values. Or to find their index locations using argmin or argmax print(aar.max()) print(aar.min()) print(aar.argmin()) print(aar.argmax()) #shape:Shape is an attribute that arrays have (not a method) a=np.arange(10) print(a.shape) print(a.reshape(1,10)) print(a.reshape(1,10).shape) print(a.reshape(10,1)) #dtype:You can also grab the data type of the object in the array print(a.dtype)
true
24634c503c3dac119f6001857b941ccee94e0228
Pasupathi9897/testdemo
/check.py
443
4.125
4
#How do you check whether a particular key/value exist in a dictionary dict={} n=int(input("enter the n value")) for i in range(0,n): first=input("enter the key") second=input("enter the value") dict[first]=second print(dict) e=input("enter the key") f=input("enter the values") if((dict.__contains__(e))|(dict.__contains__(f))): print("the element was present in the dictionary") else: print("dont found")
true
4a8d36809efe7a342f20429c263dd6b771df741c
wanghan79/2019_Python
/2017010886_WangYuTing/ConnectMongodb.py
947
4.125
4
''' 姓名:王宇婷 学号:2017010886 内容:连接mongodb并操作 ''' import pymongo client = pymongo.MongoClient(host='localhost', port=27017) db = client['RandomData']#指定数据库 collection = db['students'] student1 = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male' } student2 = { 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male' } #插入数据 result = collection.insert_many([student1, student2]) print(result) print(result.inserted_ids) #数据更新 condition = {'name': 'Kevin'} student = collection.find_one(condition) student['age'] = 25 result = collection.update(condition, student) print(result) def save_to_mongo(ur): #如果插入的数据成功,返回True,并打印存储内容:否则返回False if db[student].insert(ur): print("成功存储到MongoDB",ur) return True return False
false
7f6b31cb0a69f0e64fc1e77f34efdc7c7ace703c
pramod-yadav-97/dsa-python
/search_sort/sort_selection.py
584
4.28125
4
### SELECTION SORT ## Sorting is done by repeatedly finding the minimum element in the array and putting it at the beginning. # Time Complexity: O(n^2) # Space Complexity/Auxiliary Space: O(1) arr = [64, 25, 12, 22, 11] # function for selection sort def selection_sort(arr): for i in range(len(arr)): min_index = i for j in range(i+1, len(arr)): if arr[min_index]>arr[j]: min_index = j arr[min_index], arr[i] = arr[i], arr[min_index] # swapping elements selection_sort(arr) print("Sorted array is", arr)
true
527b34c3ce928af8ff8c1e6be6a3470f7fad242e
automationtrainingcenter/sirisha_python
/basics/string_methods.py
854
4.5625
5
""" this program explains strings in Python """ str1 = "python with Django" str2 = 'welcome to the course Sirisha' str3 = "12324" print(str1+str2) print(len(str1)) print(str1[10]) print(str1[len(str1)-1] ) print(str1[-1]) # slicing str[start : end : step] # default step value is 1 and ending index value does not include print(str1[0 : 8]) print(str1[10:]) # from index 10 to len print(str2[:16]) # from index 0 to 15 print(str1[:]) #complete string print(str1[::-1]) # reverse of the string print(str1[2:10:2]) # to i print(str1[::2]) #values at even index print(str1[1::2]) # values at odd index # string methods print(str1.capitalize()) print(str1.lower()) print(str1.title()) print(str1.upper()) if str2.isnumeric(): print(int(str2)) print(type(str2.split(" "))) print(str2.split(' ')) print(''.join([str1,' ',str2])) print(str1 == '')
true
a7cab0ad9622e67f6242afe2b74c2c71c1d7979c
automationtrainingcenter/sirisha_python
/basics/input_output.py
501
4.375
4
""" to read input from the console we have to use input() input() always returns string type """ # print('enter your name') # name = input() name = input('enter your name \n') print('your name is ', name) """ formatted strings """ interseted_course = input('which course are you interested? \n') # .format() is used till 3.6 print('Hi, {} and you are interested in {}'.format(name, interseted_course)) # from 3.6 we have f strings print(f'Hi, {name} and you are interested in {interseted_course}')
true
6ac600c0db3e3cd5159e242b407f44e0eafdfaa5
agajankush/HackerRank
/Data Structures/Trees/height.py
915
4.1875
4
def getHeight(self, root): if root is None: return 0 q = [] q.append(root) #Start from the root height = 0 while(True): nodeCount = len(q) # Will check if the traversing has reached its end. if nodeCount == 0 : # Will print the length of the tree when end of the tree is reached return height-1 height += 1 # adding height while(nodeCount > 0): #While list q is not empty node = q[0] # point to the first element q.pop(0) # remove the node used if node.left is not None: # if that node contains left child q.append(node.left) # Append it to the list if node.right is not None: # if the node contains right child q.append(node.right) # Append it to the list nodeCount -= 1 # Decrease the list count by one every time.
true
ef44ab3ba154d1845da1c393c73e8dce12476c7b
EsdrasGrau/Courses
/Udemy/Python Programmer Bootcamp 2020/file_function_questions.py
2,564
4.3125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jun 6 15:09:58 2020 @author: esdras """ ''' Question 1 Create a function that will calculate the sum of two numbers. Call it sum_two. ''' def sum_two(a,b): ''' This function calcualates the sum of 2 numbers ''' return a + b print (f'The sum of 7 and 5 is: {sum_two(7,5)}') ''' Question 2 Write a function that performs multiplication of two arguments. By default the function should multiply the first argument by 2. Call it multiply. ''' def multiply(a, b = 2): ''' This function multiply two arguments by deafult the 1st one is multiply by 2 if not giving a 2nd argument ''' return a * b print(f'Multiplying 3 by 5 is: {multiply(3,5)}') print(f'Multiplying 3 is: {multiply(3)}') ''' Question 3 Write a function to calculate a to the power of b. If b is not given its default value should be 2. Call it power. ''' def power (a, b=2): ''' This functions calcuates the power of a, default value is 2 ''' return a**b print(f'3 to the power of 3 is: {power(3,3)}') print(f'The square root of 3 is: {power(3)}') ''' Question 4 Create a new file called capitals.txt , store the names of five capital cities in the file on the same line. ''' # file = open('capitals.txt','w') # file.write('Mexico City, ') # file.write('Tokyo, ') # file.write('Manila, ') # file.write('Canberra, ') # file.write('Ottawa,') # file.close() ''' Question 5 Write some code that requests the user to input another capital city. Add that city to the list of cities in capitals. Then print the file to the screen. ''' # city = input('Please type a capital city: >>>') # file = open('capitals.txt', 'a') # file.write('\n' + city) # file.close # file = open('capitals.txt', 'r') # print(file.read()) # file.close ''' Question 6 Write a function that will copy the contents of one file to a new file. ''' # import shutil # def copy_file(scr, tgt): # ''' # This function copy a file # scr = origin route # tgt = destination # ''' # shutil.copyfile(scr,tgt) # copy_file(r'/Users/esdras/Courses/Udemy/Python Programmer Bootcamp 2020/capitals.txt', r'/Users/esdras/Courses/Udemy/Python Programmer Bootcamp 2020/new_cap.txt') #Other solution # def copy_file(infile,outfile): # ''' Copies the contents of infile to a new file, outfile.''' # with open(infile) as file_1: # with open(outfile, "w") as file_2: # file_2.write(file_1.read()) # copy_file('capitals.txt','new_capitals.txt')
true
eb2db9b1caf47b1ae8fa82b1d78a36d4e708ec4f
shermy99/E02a-Control-Structures
/main10.py
2,494
4.21875
4
#!/usr/bin/env python3 import sys, random #imports random assert sys.version_info >= (3,7), "This script requires at least Python 3.7" #checks to make sure the user is using the right version of python print('Greetings!') #prints the string colors = ['red','orange','yellow','green','blue','violet','purple'] #creates the variable colors with the following colors play_again = '' #creates the variable "play again" best_count = sys.maxsize # the biggest number while (play_again != 'n' and play_again != 'no'): #creates a loops that only ends when the player responds with no or n to play again match_color = random.choice(colors) #creates the variable "match_color" count = 0 #creates the variable count color = '' #creates the variable "color" while (color != match_color): #creates another loop that doesnt end until color = match_color color = input("\nWhat is my favorite color? ") #\n is a special code that adds a new line #ask the player "what is my favorite color" and waits for an input from the user color = color.lower().strip() #sets the variable color so that whatever the player inputs will become lower case and will remove spaces before and after the input count += 1 #adds plus 1 to the count variable whenever the user makes a guess if (color == match_color): #creates an if statement that is only true when the color variable = the match_color variable print('Correct!') #prints out "correct" else: #creates an else statement that only happens if the if statement is false print('Sorry, try again. You have guessed {guesses} times.'.format(guesses=count)) #tells the user they were wrong and how many guesses they've tried print('\nYou guessed it in {} tries!'.format(count)) #prints this if the user was correct and tells them how many guesses they got it in if (count < best_count): #creates an if statement that is only true if the current amount of guesses is smaller than the lowest amount of guesses the user has gotten the correct answer in so far print('This was your best guess so far!') #prints the string best_count = count #makes best_count the new lowest amount of guesses play_again = input("\nWould you like to play again (yes or no)? ").lower().strip() #asks the user if they want to play again, and it waits for their input print('Thanks for playing!') #if the player says no to the previous question, it prints this string
true
0ee872b1e2d8de754f81a91e4351c762cd5b6ec4
vitorefigenio/python-exercises
/exercicio_loop2.py
558
4.125
4
''' Exercício 1 Imprima os número pares entre 0 e um número fornecido usando if ''' numero = int(input('(1) Digite um número: ')) x = 0 while x <= numero: if x % 2 == 0: print(x) x = x + 1 ''' Exercício 2 Imprima os números pares entre 0 e um número fornecido sem utiliza o if ''' numero = int(input('(2) Digite um número: ')) x = 0 while x <= numero: while x % 2 == 0: print(x) x = x + 1 x = x + 1 ''' Resolução do Professor Massa ''' fim = int(input('Digite o último número: ')) x = 0 while x <= fim: print(x) x = x + 2
false
dde10b66e01d5ee8fc9c7aa6cd97919b4607cb10
Easterok/leetcode.problems
/reverse.py
915
4.1875
4
# Given a signed 32-bit integer x, return x with its digits reversed. # If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0. # Assume the environment does not allow you to store 64-bit integers (signed or unsigned). # Example 1: # Input: x = 123 # Output: 321 # Example 2: # Input: x = -123 # Output: -321 # Example 3: # Input: x = 120 # Output: 21 # Example 4: # Input: x = 0 # Output: 0 # Constraints: # -2^31 <= x <= 2^31 - 1 class Solution: def reverse(self, x: int) -> int: hight_boundary = pow(2, 31) low_boundary = -(hight_boundary - 1) if x >= 0: reversed_x = int(str(x)[::-1]) return 0 if reversed_x > hight_boundary else reversed_x else: reversed_x = -int(str(x)[::-1][:-1]) return 0 if reversed_x < low_boundary else reversed_x Solution().reverse(0)
true
3d988a1d2ef4180bb88e5a781ae0f7374ca7eeca
ronak007mistry/Python-programs
/anagram.py
314
4.25
4
str1 = input("Enter string1: ") str2 = input("Enter string2: ") sorted_str1 = sorted(str1) sorted_str2 = sorted(str2) if len(str1) == len(str2): if sorted_str1 == sorted_str2: print("Given strings are Anagrams") else: print("Given strings are not Anagrams") else: print("Given strings are not Anagrams")
true
6949220f297a3fe21e27438fdd596103492a118d
abiodunsam/codepy
/python-data-structure-exercises-master/exam_results.py
1,111
4.53125
5
# This program interactively asks about your exam marks, and reports the # corresponding grades. # # Usage: # # $ python exam_results.py # # A session with the program might look like the following: # # $ python exam_results.py # What marks did you get in Maths? # > 63 # What marks did you get in Philosophy? # > 54 # What marks did you get in Geography? # > 71 # What marks did you get in Music? # > 68 # # Your grades: # # Maths: B # Philosophy: C # Geography: A # Music: B subjects = ['Maths', 'Philosophy', 'Geography', 'Music'] grade_boundaries = { 'A': [70, 100], 'B': [60, 69], 'C': [50, 59], 'D': [40, 49], 'E': [30, 39], 'F': [0, 29], } print('This program will ask you your marks in the following subjects:') for subject in subjects: print(' * {}'.format(subject)) # TODO: # * Implement the program as described in the comments at the top of the file. # TODO (extra): # * Modify the program to handle the case where the user enters an invalid mark # (such as 150, or -25.5, or "bananas") # * Modify the program to ask the user for the subjects that they've taken.
true
73ff5d78d8728bfa39ac1e53649983e5fabf46d5
KeeTC/cci_python
/Chapter_1/1_1.py
325
4.1875
4
# QUESTION: Implement an algorithm to determine if a string has all unique characters. # Assuming ASCII (non-extended) 128 max unique characters def uni_char2(str): if len(str) > 128: return False char = set() for var in str: if var in char: return False else: char.add(var) return True uni_char2('abc')
true
eb05a0f5c90011458e68f6cc8718dfa2c2f56ec5
kemicode/personalcodes
/kemi_python_print_function.py
931
4.1875
4
#Name: Oluwakemi LaBadie #Student ID Number: 00002489343 #Write a program that prints the follwing lines replacing the (?) with the correct answers # #Pseudocode #start Program #input the python float data type is for numeric values with decimal #input the str data type is for numeric data like names and addresses #input the python operator for exponent arithmetic is ** # input the 'end ="" ' operator suppresses the print function' newline #input ':nf' function is used to control the output of decimal places # #End program #start program print ('The python {float} data type is for numeric values with decimal.') print ('The {str} data type is for numeric data like names and addresses.') print ('The python operator for exponeent arithmetic is {**}.') print ('The {end = ""} operator suppresses the print function newline.') print ('{:nf) function is used to control the output of decimal placs.') #End Program
true
b6439e0ca8e48061b0013a11c7580a304f725959
DevelopedByAnurag/python-ML-Training
/dictionaries.py
1,220
4.21875
4
groceries={'bananas':5,'oranges':3} #dictionary-organize data in more organized form . Dictionaries are unorderd # in python 3.7 and onwards dictionaries can relied to be in order.Ordered Dicts by default # from collections import OrderedDict (in Python <3.7 versions print(groceries['bananas']) #print(groceries['hello']) print(groceries.get('bananas')) print(groceries.get('hello')) contacts={ 'Joe':['12345672','jkrt.ngh69@gmail.com'], 'Jane':['98127361','Jane@gmail.com'] } contacts={ 'Joe':{'phone':'12345672','email':'jkrt.ngh69@gmail.com'}, 'Jane':{'phone':'12345672','email':'jkgh69@gmail.com'} } print(contacts['Joe']) sentence="I like the name Aaron because the name Aaron is the best " word_counts={ 'I':1, 'like':1, 'the':3, 'likew':1, 'th2e':3 } print(word_counts.items()) print(list(word_counts.items())) print(list(word_counts.keys())) print(list(word_counts.values())) print(word_counts.pop('I')) # returns the value print(word_counts) word_counts.popitem() # pop the last key-value pair print(word_counts) word_counts['Aaron']=2 # add the key valu pair in dictionary print(word_counts) print(sorted(list(word_counts.values()))) word_counts.clear() print(word_counts)
true
17e07fab4f6850f7354f1aa4ed34b8e526846e08
georgeteo/Coding_Interview_Practice
/chapter_4/4.7.py
1,756
4.15625
4
''' CCC 4.7: Design an algorithm to find the first common ancestor of a binary tree. Solution: make path two two nodes into a list of left/right moves. Then look at sequence of left, right moves. Left/left or right/right the common ancestor until left/right difference. ''' from binary_tree import binary_tree def path_from_root(bt, node): ''' Base Cases ''' if bt is None: return None if bt.id == node: return [] ''' Recursive Step ''' left_return_list = path_from_root(bt.left_child, node) right_return_list = path_from_root(bt.right_child, node) ''' Another Base Case''' if left_return_list is not None: return_list = left_return_list t = "Left" elif right_return_list is not None: return_list = right_return_list t = "Right" else: return None ''' Recursive Step continues ''' return_list.insert(0, [bt, t]) return return_list def common_ancestor(bt_root, node1, node2): node1_path = path_from_root(bt_root,node1) node2_path = path_from_root(bt_root, node2) for i in range(min(len(node1_path), len(node2_path))): node1_element = node1_path[i] node2_element = node2_path[i] if node1_element[1] != node2_element[1]: return node1_element if len(node1_path) == len(node2_path): return None elif len(node1_path) < len(node2_path): return node1_path[-1] else: return node2_path[-1] if __name__ == "__main__": bt = binary_tree(0, 0, binary_tree(1,1, binary_tree(3,2), binary_tree(4,2)), binary_tree(2,1, binary_tree(5,2), binary_tree(6,2))) print "Test" print "Expect 2 - got ",common_ancestor(bt, 5, 6)[0].id
true
f2bc93c3a142cb38eb33001214589fcb09fe17da
tabdansby/newRepo
/nightclass/lists.py
782
4.4375
4
"""lists are iterable and positional. Tuples and sets are in parentheses. Can't do reassignments to tuples after they are created. They're immutable. If a list is in a tuple, you can change the items in the list inside the tuple, not the tuple itself.""" x = 5 y = ['the', 42, ['Bye']] lst = [23, 53, 3, 7, 19] #print(lst[3][2][0]) #for thing in lst: # print(thing) #print(len(lst)) """for loop: it will run a function on a given list of items until it stops. in loops, you can call an item in a list anything. Don't name it the same as a variable you've already defined. This is called (variable) shadowing, and can get confusing and possibly break your program for index in range(len(lst)): lst[index]+= 5 print('index:{}, value: {}'.format(index, lst[index]))"""
true
8b9a6e6171f85f674d0d6f10da8ea8097cb72a27
tabdansby/newRepo
/nightclass/Pseudo_CC_checker.py
1,613
4.3125
4
"""# Lab: Pseudo-Credit Card Validation ###### Delivery Method: Doctests -------------- ##### Goal Write a function which returns whether a string containing a credit card number is valid as a boolean. Write as many sub-functions as necessary to solve the problem. -------------------- ##### Instructions 1. Slice off the last digit. That is the **check digit**. 2. Reverse the digits. 3. Double every other element in the reversed list. 4. Subtract nine from numbers over nine. 5. Sum all values. 6. Take the second digit of that sum. 7. If that matches the check digit, the whole card number is valid. For example, the worked out steps would be: ``` 1. `4 5 5 6 7 3 7 5 8 6 8 9 9 8 5 5` 2. `4 5 5 6 7 3 7 5 8 6 8 9 9 8 5` 3. `5 8 9 9 8 6 8 5 7 3 7 6 5 5 4` 4. `10 8 18 9 16 6 16 5 14 3 14 6 10 5 8` 5. `1 8 9 9 7 6 7 5 5 3 5 6 1 5 8` 6. 85 7. 5 8. Valid!""" from functools import reduce cc = [9, 21, 53, 69, 39, 41, 23, 62, 16, 60, 54, 66, 11, 31] new_cc = cc[::] def number_check(): cc_copy = new_cc[::] del cc_copy[13] new_cc.append(cc_copy) a = (cc_copy[::-1]) a[0::2] = [i*2 for i in a[0::2]] a = [i-9 for i in a if i > 9] new_cc.append(a) a = str(sum(a)) new_cc.append(a) if cc[13] == a[1]: print('Credit card successfully validated!') else: print('Credit card not valid!') number_check() ##your_list[::2] = [x*2 for x in your_list[::2]] #b = [] """ data = [1,2,3,4,5,6] for i,k in zip(data[0::2], data[1::2]): print str(i), '+', str(k), '=', str(i+k)"""
true
a7f2e335194887eeb0307ae69c8840a068358028
DenisLamalis/cours-python
/lpp101-work/index_28.py
1,128
4.1875
4
# Conditionals: if, else, elif # is_raining = True # print('Good morning!') # if is_raining: # print('Bring umbrella') # is_raining = False # print('Good morning!') # if is_raining: # print('Bring umbrella') # else: # print('Umbrella is optional') # is_raining = True # is_cold = True # print("Good Morning") # if is_raining or is_cold: # or # print("Bring Umbrella or jacket or both") # else: # print("Umbrella is optional") # is_raining = True # is_cold = False # print("Good Morning") # if is_raining and is_cold: # and # print("Bring Umbrella and jacket") # else: # print("Umbrella is optional") # is_raining = False # is_cold = True # print("Good Morning") # if is_raining and is_cold: # print("Bring Umbrella and jacket") # elif is_raining and not(is_cold): # and not() # print("Bring Umbrella") # elif not(is_raining) and is_cold: # print("Bring Jacket") # else: # print("Shirt is fine!") amount = 10 if amount <= 50: print("Purchase approved") else: print("Please enter your pin!")
false
21d91d217de5225b8209441a628831b7bac668fe
jamiemc-ai/P-S-Problem-Sheet-2020
/BMI.PY
265
4.3125
4
# This program calculate BMI Weight = float(input("enter your weight in KG;")) Height = float(input("enter height in cm;")) Heightsquared = (Height*Height) BMI= Weight / Heightsquared print("Your BMI is",BMI,"based on the figures you have been provided")
true
6c9834218257b7013ad5552a4b2a20f3b15b5611
Patel-Jenu-1991/SQLite3_basics
/cars_stock.py
961
4.15625
4
#!/usr/bin/env python3 # Output the car's make and model on one line # The quantity on another line # The order count on the next line import sqlite3 with sqlite3.connect("cars.db") as connection: cursor = connection.cursor() # retrieve data cursor.execute(""" SELECT * FROM inventory """) # fetchall retrieves all records from the query rows = cursor.fetchall() # output the rows to the screen, row by row for row in rows: # output the car make, model and quantity ot screen print(f"{row[0]} {row[1]} \n{row[2]}") # retrieve order_date for the current car make and model cursor.execute("""SELECT count(order_date) FROM orders WHERE make = ? and model = ?""", (row[0], row[1])) # fetchone() retrieves one record from the query order_count = cursor.fetchone()[0] # output the order count to the screen print(order_count) print()
true
1109d0ba614842d1d06be3ac4919955f39deb83c
otaviov/python3.modulo1
/Desafios/005.py
311
4.3125
4
''' Faça um programa que leia um número inteiro e mostre na tela o seu sucessor e eu antecessor. ''' print('{:*^30}'.format('DESAFIO 5')) num = int(input('Digite um número: ')) print('O sucessor do número {} é {}'.format(num,num+1)) print('O antecessor do número {} é {}'.format(num, num-1))
false
c00eb0f801d2fc33058ee39ff0a56f0ba3bf5e6f
jmcguire/learning
/design_patterns/composite/menu.py
2,859
4.125
4
from abc import abstractmethod # our new tree classes class MenuComponent(object): """An abstract class to define an implementation""" @abstractmethod def print_(self): pass @abstractmethod def add(self, component): pass @abstractmethod def remove(self, component): pass @abstractmethod def get_child(self, i): pass class MenuItem(MenuComponent): """a leaf node, of our menu tree""" def __init__(self, name, desc, price, is_veggie): self.name = name self.price = price self.desc = desc self.is_veggie = is_veggie def print_(self): # turn the boolean is_veggie into a print-friendly string veggie_string = "" if self.is_veggie: veggie_string = " (v)" print "\t%s. %s%s -- %.2f" % (self.name, self.desc, veggie_string, self.price) class MenuComposite(MenuComponent): """a composite node, that holds more MenuComponents""" def __init__(self, name, desc): self.name = name self.desc = desc self.components = [] def add(self, component): self.components.append(component) def remove(self, component): self.components.remove(component) def get_child(self, i): return self.components[i] def print_(self): print "\n%s: %s\n%s" % (self.name, self.desc, "-"*20) # python iterators interact with the for command, we don't have to # explicitly create and manage them, like in Java for component in self.components: component.print_() # a simple waitress class, simpler than anything we had in "Iterator" class Waitress(object): def __init__(self, menu): self.menu = menu def print_menu(self): self.menu.print_() # testing def create_test_data(): pancake_house = MenuComposite("Breakfast", "Pancakes and breakfast items") cafe = MenuComposite("Lunch", "Classic cafe lunch items") dessert = MenuComposite("Dessert", "Simple desserts") pancake_house.add(MenuItem("Pancakes", "Regular pancakes", 2.99, True)) pancake_house.add(MenuItem("Trucker Pancakes", "Pancakes with eggs", 3.99, None)) pancake_house.add(MenuItem("Waffles", "Waffles with Maple Syrup", 4.99, True)) cafe.add(MenuItem("Soup", "Soup of the Day", 3.29, True)) cafe.add(MenuItem("BLT", "Bacon, Lettuce, Tomato, with optional Mutton", 2.99, None)) cafe.add(MenuItem("Hot Dog", "World famously cheap-ass hot dog", 0.25, None)) dessert.add(MenuItem("Apple Pie", "Homemade Grandma-approved apple pie", 1.59, True)) dessert.add(MenuItem("Ice Cream", "Two scoops of our ice cream of the day", 1.00, True)) cafe.add(dessert) restaurant_menu = MenuComposite("Restaurant Menu", "Welcome to our restaurant") restaurant_menu.add(pancake_house) restaurant_menu.add(cafe) return restaurant_menu if __name__ == '__main__': restaurant_menu = create_test_data() waitress = Waitress(restaurant_menu) waitress.print_menu()
true
eba7d52faabe9a58b470afed0370fcdafd628200
jmcguire/learning
/design_patterns/iterator/menu_original.py
2,341
4.125
4
# general-use classes class MenuItem(object): def __init__(self, name, desc, veggie, price): self.name = name self.desc = desc self.veggie = veggie self.price = price def get_name(self): return self.name def get_desc(self): return self.desc def get_veggie(self): return self.veggie def get_price(self): return self.price # incompatible collection classes class PancakeHouse(object): """a collection based on a linked list""" def __init__(self): self.menu_items = [] self.add_menu_item("Pancakes", "Regular pancakes", 2.99, True) self.add_menu_item("Trucker Pancakes", "Pancakes with eggs", 3.99, None) self.add_menu_item("Waffles", "Waffles with Maple Syrup", 4.99, True) def add_menu_item(self, name, desc, price, veggie): menu_item = MenuItem(name, desc, veggie, price) self.menu_items.append(menu_item) def get_menu_items(self): return self.menu_items class Diner(object): """an collection based on an array, which is pretty hard to do in python""" def __init__(self): self.menu_items = [None, None, None, None, None, None] self.max_items = 6 self.number_of_items = 0 self.add_menu_item("Soup", "Soup of the Day", 3.29, True) self.add_menu_item("BLT", "Bacon, Lettuce, Tomato, with optional Mutton", 2.99, None) self.add_menu_item("Hot Dog", "World famously cheap-ass hot dog", 0.25, None) def add_menu_item(self, name, desc, price, veggie): if self.number_of_items < self.max_items: menu_item = MenuItem(name, desc, veggie, price) self.menu_items[self.number_of_items] = menu_item self.number_of_items += 1 else: raise Exception("maximum number of items reached!") def get_menu_items(self): return self.menu_items # testing if __name__ == '__main__': breakfast_menu = PancakeHouse() breakfast_items = breakfast_menu.get_menu_items() lunch_menu = Diner() lunch_items = lunch_menu.get_menu_items() def print_menu_item(menu_item): print "\t%s. %s -- %.2f" % (menu_item.get_name(), menu_item.get_desc(), menu_item.get_price()) print "Breakfast Menu:" for menu_item in breakfast_items: print_menu_item(menu_item) print "\nLunch Menu:" for i in range(len(lunch_items)): if not lunch_items[i]: continue menu_item = lunch_items[i] print_menu_item(menu_item)
true
bcdab39d6ff39162aa79b8826e0e25ed5c50ddf1
jmcguire/learning
/data_structures/queue.py
683
4.125
4
from linked_list import LinkedList, Node class Queue(LinkedList): """a FIFO list""" # these two methods are just aliases for the regular LinkedList methods, but # are given the names we'd expect for a Queue def push_e(self, e): self.add_e(e) def push_node(self, node): self.add_node(node) def next_(self): """queues don't have a notion of next, the user only gets the first""" pass def shift(self): """return the first element of the list""" if self.size == 0: return None node = self.first self.first = node.next_ self.size -= 1 if self.is_empty(): self.current = None self.last = None return node
true
15b3d064749b24e5b43685f800f443f81a53785d
OarabileMokgalagadi/package-root
/hackathonproject/sorting.py
1,206
4.3125
4
def bubble_sort(items): """Return array of items, sorted in ascending order""" for i in range(len(items)): for j in range(i, len(items)): if items[i] > items[j]: items[i], items[j] = items[j], items[i] return items def merge_sort(items): """ Return array of items, sorted in ascending order """ if len(items) < 2: return items mid = len(items) // 2 left_items = merge_sort(items[:mid]) right_items = merge_sort(items[mid:]) return merge(left_items, right_items) def merge(left, right): result = [] i = j = 0 while i < len(left) and j < len(right): if left[i] < right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 result += left[i:] result += right[j:] return result def quick_sort(items): """Return array of items, sorted in ascending order""" if not items: return [] pivots = [x for x in items if x == items[0]] lesser = quick_sort([x for x in items if x < items[0]]) greater = quick_sort([x for x in items if x > items[0]]) return lesser + pivots + greater
true
a4d97ee06e4a2642f85968ced00b065beae97c12
AparnaDR/LearnPython
/Functions/lambdas.py
1,875
4.78125
5
# Lambda expressions are simply another way to create functions # it can be assigned to a variable # passed as an argument to another function # The "body" of a lambda is limited to a single expression # regular function using def def sq(x): return x ** 2 print(type(sq)) f = sq print(id(f), id(sq)) # both are pointing to same memory location print(f(2)) print(sq(2)) print(f) # still points to sq # same using lambda print('---lambda-------') f1 = lambda x: x ** 2 print(f1) print(f1(2)) # f1 is callable print('---lambda with default values-------') g =lambda x, y=10: x+y print(g(1)) print(g(1,2)) print('---lambda with positional and keyword arguemnts-------') f2 = lambda x, *args, y, **kwargs: (x + y, *args, kwargs) print(f2(10, 'a', 'b', a1=10, b2=20, y=10)) print('---passing lambdas as functions-------') def apply_fun(x, fn): return fn(x) print(apply_fun(3, sq)) print(apply_fun(5, lambda x: x**3)) print('---passing lambdas as functions which has starred postional and keyword arguments-------') def apply_func_star(fn, *args, **kwargs): return fn(*args, **kwargs) print('------- passing existing normal function--------') print(apply_func_star(sq, 4)) print('------- passing lambda expression with only 1 positional arg--------') print(apply_func_star(lambda x: x**2, 6)) print('------- passing lambda expression with 2 positional arg--------') print(apply_func_star(lambda x, y: x+y, 2, 3)) print('------- passing lambda expression with 1 positional arg and 1 keyword arg--------') print(apply_func_star(lambda x, *, y: x+y, 1, y=100)) print('------- passing lambda expression with many positional arg to calculate sum of those arguments-------') print(apply_func_star(lambda *args: sum(args),1, 2, 3, 4, 5)) print('------- passing inbuilt function to calcualte sum-------') print(apply_func_star(sum,(1, 2, 3, 4, 5)))
true
3771dfba4a9dd8be316d984d151b181d1b74705b
mjurk456/mini-snakes
/fibonacci.py
479
4.28125
4
#!/usr/bin/env python3 """Counting Fibonacci numbers without recursion""" def fibonacci(n): #returns a list of n Fibonacci numbers array = [1, 1] for i in range(2, n): array.append(array[i-2] + array[i-1]) return array def main(): userInput = "" while not userInput.isdigit(): userInput = input("How many Fibonacci numbers do you want to get? ") print(fibonacci(int(userInput))) if __name__ == "__main__": main()
true
fe960da4a88d7fc0a82c841385930e689e68ea9b
Angie-0901/AngieDeLaCruzRamos-AlvaroRojasOliva
/verificador13.py
612
4.1875
4
print("EJERCICIO N°13 ") #Este programa hallara el Tiempo de encuentro #INPUT V_a=float(input("la veloc. a es: ")) V_b=float(input("la veloc. b es: ")) distancia=int(input("la distancia es: ")) #PROCESSING tiempo_encuentro= d/(Va-Vb) #VERIFICADOR tiempo_encuentro_verificado=(tiempo_encuentro <200) #output print("La velocidad a es: " + str(V_a)) print("La velocidad b es: " + str(V_b)) print("La distancia es: " + str(distancia)) print("El tiempo de encuentro es: " + str(tiempo_encuentro)) print("El tiempo de encuentro hallado es menor que 200?: " + str(tiempo_encuentro_verificado))
false
3cec7d97117844ed2f508501768635ad0e3b3e6f
Angie-0901/AngieDeLaCruzRamos-AlvaroRojasOliva
/Boleta5.py
1,532
4.1875
4
print("BOLETA N°5") #INPUT empresa=input("Nombre de la empresa es: ") R_U_C=int(input("El numero de R.U.C es:")) caja=int(input("El numero de caja es: ")) cajero=input("El nombre de la cajera es: ") cliente=input("El nombre del cliente es:") radio=int(input("Cantidad de radios comprados: ")) costo_radio=float(input("El costo de la radio por unidad es: ")) tv=int(input("La cantidad de tv comprados es : ")) costo_tv=float(input("El precio del tv por unidad es: ")) #PROCESSING total_costo_radio=(radio* costo_radio) total_costo_tv=(tv*costo_tv) total_venta=(total_costo_radio+total_costo_tv) print(" ") #OUTPUT print("#####################" + " " + empresa +" ######################") print(" calle Pedro Ruiz") print("R.U.C " + str(R_U_C)) print("cliente " + cliente + " caja " + str(caja) + " cajero " + cajero) print("################BOLETA DE VENTA#####################") print(" ") print("electrodomestico " + " cantidad " + " precio " + " total") print("radio " + " " + str(radio) + " " + str(costo_radio) + " " + str(total_costo_radio)) print("tv " + str(tv) + " " + str(costo_tv) + " " + str(total_costo_tv)) print("monto total: s/ " + str(total_venta)) print("_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _") print("Donde todo es más barato! ")
false
7346c5868dfa1e763d1120d3d74f1030e9d5dc8d
Meenaashutosh/PythonAssignment
/Assignment20.py
655
4.46875
4
#20.Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.) def palindrome_no(s): if len(s)<1: return true else: if s[0]==s[-1]: return palindrome(s[1:-1]) else: return false a=str(input("Enter string")) if(palindrome(a)==true): print("string is palindrome..") else: print("string is not a palindrome") #output -error ''' Enter string abba Traceback (most recent call last): File "Assignment20.py", line 10, in <module> a=str(input("Enter string")) File "<string>", line 1, in <module> NameError: name 'abba' is not defined '''
true
7365fe4f627961e01896ec5a5ab15a1024d1a6a9
ewarlock/ITEC-2905-80-Lab-01
/01_Birthmonth.py
1,693
4.5625
5
#prompt user to input name name = input('Your name is: ') #make sure name with at least 1 character has been entered while len(name) == 0: print('Please enter at least one character.') name = input('Your name is: ') #prompt user to input birth month month = input('Your birth month is: ') #make sure they enter something for birth month while len(month) == 0: print('Please enter at least one character.') month = input('Your birth month is: ') #print name print(f'Hello, {name}!') #check if month is august or August and print happy birthday month if true #I commented this out in favor of the 'compare to current month' method below! #if month == 'August' or month == 'august': # print('Happy birthday month!') #print number of letters in name print(f'There are {len(name)} letters in your name.') #next 3 lines found here: https://www.geeksforgeeks.org/get-current-date-using-python/ from datetime import date today = date.today() #get the current date current_month_number = today.month #get just the month from current date #next 3 lines found here: https://www.studytonight.com/python-howtos/how-to-get-month-name-from-month-number-in-python import calendar current_month = calendar.month_name[current_month_number] #get the month name from the month number current_month_abbr = calendar.month_abbr[current_month_number] #get the abbreviation #convert to uppercase so user entry can be case insensitive #see if this month is birthday month, print bday message if true if month.upper() == current_month.upper() or month.upper() == current_month_abbr.upper(): print('Happy birthday month!') #note to self: go to strftime library for different method
true
fb37d43d17618b702efc741d1567065625d9dd9e
PhilippeJanssens/challenge-card-game-becode
/utils/game.py
1,861
4.375
4
"""A class called Board that contains: - An attribute players that is a list of Player. It will contain all the players that are playing. - An attribute turn_count that is an int. - An attribute active_cards that will contain the last card played by each player. - An attribute history_cards that will contain all the cards played since the start of the game, except for active_cards. -- A method start_game() that will: - Start the game, - Fill a Deck, - Distribute the cards of the Deck to the players. - Make each Player play() a Card, where each player should only play 1 card per turn, and all players have to play at each turn until they have no cards left. -- At the end of each turn, print: - The turn count. - The list of active cards. - The number of cards in the history_cards.""" class Board: def __init__(self, players, turn_count, active_cards, history_cards): self.players = players # a list that contains all the players that are playing self.turn_count = turn_count self.active_cards = active_cards self.history_cards = history_cards def __str__(self): return "{} {} {} {}".format(self.player, self.turn_count, self.active_cards, self.history_cards) def start_game(): # fill a deck fill_deck() # distribute the cards of the "Deck" to the players distribute() # make each Player play() a Card, where each player should only play 1 ## card in turn until they have no cards left play() # at the end of each turn, print: ## - the turn count print(turn_count) ## - the list of active cards print(" ... list of active cards ... ") ## - the number of cards in the history_cards print(history_cards) return
true
8a40ff34b489d1cbf96b24d1e6bdc753c9d95ef4
bradleecrockett/Geometry-Lab
/geometry.py
2,617
4.40625
4
# Name: # Date: # Period: # Description: Define the functions described in comments below. # Functions should should pass all tests. Proper # pep-8 formatting should be used and comments should # be added or updated where appropriate import math def rect_area(length, width): # rect_area returns the area of a rectangle with a given length and width # It takes 2 params, the length and width of the rectangle # TODO Complete the rect_area function to return the proper area return 0 def rect_perimeter(length, width): # rect_perimeter returns the perimeter of a rectangle with a given length and width # It takes 2 params, the length and width of the rectangle # TODO Complete the rect_perimeter function to return the proper perimeter return 0 def triangle_area(base, height): # triangle_area returns the area of a triangle with a given base and height # it takes two parameters (base and height) that represents the base and height of the triangle # TODO Complete the triangle_area function to return the proper area return 0 def circle_area(radius): # circle_area returns the area of a circle with a given radius # it takes one parameter (radius) that represents the radius of the circle # TODO Complete the circle_area function to return the proper area return 0 def circle_circumference(radius): # circle_perimeter returns the perimeter of a circle with a given radius # it takes one parameter (radius) that represents the radius of the circle # TODO Complete the circle_perimeter function to return the proper perimeter return 0 def calculate_slope(x1, y1, x2, y2): # calculate_slope returns the slope between the 2 points (x1, y1) and (x2, y2) # it takes in 4 params, x1 and y1 that represent the x and y coordinates of point 1 # and x2 and y2 that represent the x and y coordinates of point 2 # TODO Complete the calculate_slope function to return the proper slope between 2 points return 0 def main(): print("A rectangle with sides 10 and 5 have an area of:", rect_area(10,5)) print("A rectangle with sides 10 and 5 have a perimeter of:", rect_perimeter(10, 5)) print("A triangle with base 10 and height 5 have an area of:", triangle_area(10,5)) print("A circle with radius 5 has an area of:", circle_area(5)) print("A circle with radius 5 has an circumference of:", circle_circumference(5)) print("The slope of the line between (1,1) and (5,3) is:", calculate_slope(1,1,5,3)) if __name__ == '__main__': main()
true
e40456d9b2778a4b8315a3ba9753734c036fc90a
nbngc/insight_workshop
/Assignment_3/8.py
548
4.21875
4
# # 8. Write a function, is_prime, that takes an integer and returns True if thenumber is prime and False if the # number is not prime. def is_prime(number): if number < 2: return False elif number == 2: return True elif not number & 1: return False for n in range(3, int(number ** 0.5) + 1, 2): if number % n == 0: return False return True print(1, "is prime", is_prime(1)) print(2, "is prime", is_prime(2)) print(3, "is prime", is_prime(7)) print(29, "is prime", is_prime(29))
true
e6610fadf10cad7033580eb21e24b112726f2766
nbngc/insight_workshop
/assignment_2/1.py
381
4.5
4
# 1. Write a Python program to count the number of characters (character frequency) in a string. # Sample String : google.com' # Expected Result : {'o': 3, 'g': 2, '.': 1, 'e': 1, 'l': 1, 'm': 1, 'c': 1} stringA = 'google.com' print("Given String:", stringA) count_dict = {i: stringA.count(i) for i in list(stringA)} print("Frequency of each character :\n ", count_dict)
true
5080d2adfc01bf424b7a3ab0c7837a4a75f64765
LeakyBucket/LPTHW
/ex11/ex11.py
482
4.4375
4
print "How old are you?", age = raw_input() print "How tall are you?", height = raw_input() print "How much do you weigh?", weight = raw_input() print "So, you're %r old %r tall and %r heavy." % (age, height, weight) # raw_input takes an optional string argument which will be displayed as a prompt # it then reads from STDIN until it sees a new line. The stream is converted # to a string. The trailing newline is stripped from the input. print raw_input('echo chamber: ')
true
5a56471becea2bfcf12a4aacf74a370fe1fa0551
LeakyBucket/LPTHW
/ex19/ex19.py
1,549
4.21875
4
# define the cheese_and_crackers method def cheese_and_crackers(cheese_count, boxes_of_crackers): # print the value of the cheese_count argument print "You have %d cheeses!" % cheese_count # print the value of the boxes_of_crackers argument print "You have %d boxes of crackers!" % boxes_of_crackers # print a static message print "Man that's enough for a party!" # print another static message print "Get a blanket.\n" def echo(repeat): print repeat # print a static message print "We can just give the function numbers directly:" # call cheese_and_crackers setting cheese_count to 20 and boxes_of_crackers to 30 cheese_and_crackers(20, 30) # print a static message print "OR, we can use variables from our script:" # set amount_of_cheese to 10 amount_of_cheese = 10 # set amount_of_crackers to 50 amount_of_crackers = 50 # call cheese and crackers with the values of amount_of_cheese and amount_of_crackers as parameters cheese_and_crackers(amount_of_cheese, amount_of_crackers) # Python basically creates new references to the data so is passing a reference # print a static message print "We can even do math inside too:" # call cheese and crackers with 30 for cheese_count and 11 for boxes_of_crackers cheese_and_crackers(10 + 20, 5 + 6) # print static message print "And we can combine the two, variables and math:" # call cheese_and_crackers with 110 for cheese_count and 1050 for boxes_of_crackers cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) for x in range(10): echo(raw_input('... '))
true
00ae8dc2424ad91e745fd1865d6f2112f0b723cb
ragvri/machine-learning
/Deep_Learning/keras/1_intro.py
2,051
4.65625
5
""" Here we will be looking at the sequential model in keras. The Sequential model is a linear stack of layers""" from keras.models import Sequential from keras.layers import Dense, Activation import keras import numpy as np model = Sequential() # add new layers using .add # Dense implements operation : activation(dot(input,weights)+bias) model.add(Dense(32, input_dim=100, activation='relu')) # output array is of the shape(*,32) model.add(Dense(10, activation='softmax')) # output is of the shape (*,10), now we don't need to specify input anymore """The model needs to know what input shape it should expect. For this reason, the first layer in a Sequential model needs to receive information about its input shape. 1) pass input_shape to first layer: It should be a tuple: None indicates any positive integer may be expected. In input_shape, the batch dimension is not included. 2) Some 2D layers, such as Dense, support the specification of their input shape via the argument input_dim, 3) If you ever need to specify a fixed batch size for your inputs (this is useful for stateful recurrent networks), you can pass a batch_size argument to a layer. If you pass both batch_size=32 and input_shape=(6, 8) to a layer, it will then expect every batch of inputs to have the batch shape (32, 6, 8) """ # Before training the model it needs to be compiled model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) # Now we train the model # Keras models are trained on Numpy arrays of input data and labels data = np.random.random((1000, 100)) # 1000 rows and 100 cols labels = np.random.randint(10, size=(1000, 1)) # output can be of 10 classes so random number between 0 to 10 and # since 1000 inputs so 1000 outputs # now we need to convert the labels to one hot encoding one_hot_labels = keras.utils.to_categorical(labels, num_classes=10) # Train the model, iterating through the data in batch size of 32 model.fit(data, one_hot_labels, epochs=10, batch_size=32)
true
7cf53b2ca3704a556d258a24ef9bf3efb8e00624
ragvri/machine-learning
/Deep_Learning/1_Intro.py
1,293
4.21875
4
""" Our brain has neurons. It has dendrites which are the branches. The long portion is the axon. The dendrites are inputs. Our model of a neuron: We have our input eg X1,X2,X3 These values are passed to a function which gives the weighted sum of the inputs + biases i.e sum(input*weight + bias) Bias is important for the case when all the inputs are zero This then gets passed through a threshold(Sigmoid/Activation) function and checks if output needs to be passed or not depending upon if value is greater than threshold or not. 0 means value less than threshold. 1 means greater than threshold. This might go to another input. Output Y = f(x,w) where the w are the weights Model of a neural network: Consider layers of neurons. eg the first layer may have 3 neurons, the second 2, and so on. We also have our input x1,x2,x3. Each input is fed to all the neurons of the first layer and each connection has a unique weight. The output from the neurons of the first layer becomes the input for the second layer and so on. x1,x2,x3 -> Input layer Layers inbetween ->Hidden Layers Last layer ->Output Layer. If we have one hidden layer, it is a regular neural network. If > one layer, then "deep" neural network. """ # Datasets available at : ImageNet, Wiki dumps, Tatoba, CominCrawl
true
c9e68b1086362b557eaabd5b1d9175aed892af0b
IvayloSavov/Fundamentals
/final_exams/03_August_2019_Group_2/String_Manipulator.py
1,102
4.125
4
string = input() while True: tokens = input() if tokens == "Done": break tokens = tokens.split() command = tokens[0] if command == "Change": char = tokens[1] replacement = tokens[2] while char in string: string = string.replace(char, replacement) print(string) elif command == "Includes": string_to_check = tokens[1] if string_to_check in string: print("True") else: print("False") elif command == "End": string_to_check = tokens[1] if string.endswith(string_to_check): print("True") else: print("False") elif command == "Uppercase": string = string.upper() print(string) elif command == "FindIndex": char = tokens[1] if char in string: index = string.index(char) print(index) elif command == "Cut": start_index = int(tokens[1]) length = int(tokens[2]) string = string[start_index: start_index + length] print(string)
false
4fc041c7f3b188fd54357c6900b1b0becc7992da
IvayloSavov/Fundamentals
/final_exams/03_August_2019_Group_1/String_Manipulator.py
1,108
4.15625
4
string = input() while True: token = input() if token == "End": break token = token.split() command = token[0] if command == "Translate": char = token[1] replacement = token[2] while char in string: string = string.replace(char, replacement) print(string) elif command == "Includes": string_to_check = token[1] if string_to_check in string: print("True") else: print("False") elif command == "Start": string_to_check = token[1] if string.startswith(string_to_check): print("True") else: print("False") elif command == "Lowercase": string = string.lower() print(string) elif command == "FindIndex": char = token[1] if char in string: index = string.rindex(char) print(index) elif command == "Remove": start_index = int(token[1]) count = int(token[2]) string = string[0:start_index] + string[start_index + count:] print(string)
true
0fdb3a423c05f5153e344a4427e1a553615a0257
IvayloSavov/Fundamentals
/final_exams/07_December_2019_Group_1/Email_Validator.py
1,083
4.28125
4
email = input() while True: tokens = input() if tokens == "Complete": break tokens = tokens.split() command = tokens[0] if command == "Make": upper_lower = tokens[1] if upper_lower == "Upper": email = email.upper() else: email = email.lower() print(email) elif command == "GetDomain": count = int(tokens[1]) print(email[-count:]) elif command == "GetUsername": if "@" not in email: print(f"The email {email} doesn't contain the @ symbol.") else: ch_to_print = "" for ch in email: if ch == "@": break else: ch_to_print += ch print(ch_to_print) elif command == "Replace": char = tokens[1] while char in email: email = email.replace(char, "-") print(email) elif command == "Encrypt": values_of_characters = [str(ord(ch)) for ch in email] print(" ".join(values_of_characters))
false
47494a2d70220ff61d90d0c0372d0aa78fba2235
IvayloSavov/Fundamentals
/final_exams/9_August_2019/username.py
1,343
4.28125
4
username = input() while True: tokens = input() if tokens == "Sign up": break tokens = tokens.split() command = tokens[0] if command == "Case": lower_upper = tokens[1] if lower_upper == "upper": username = username.upper() else: username = username.lower() print(username) elif command == "Reverse": start_index = int(tokens[1]) end_index = int(tokens[2]) if start_index in range(len(username)) and end_index in range(len(username)): substring = username[start_index:end_index+1] # substring = "".join((list(reversed(username)))) substring = substring[::-1] print(substring) elif command == "Cut": substring = tokens[1] if substring in username: username = username.replace(substring, "") print(username) else: print(f"The word {username} doesn't contain {substring}.") elif command == "Replace": char = tokens[1] while char in username: username = username.replace(char, "*") print(username) elif command == "Check": char = tokens[1] if char in username: print("Valid") else: print(f"Your username must contain {char}.")
true
c10b5aecb51dd7ada89f08500edd306cf82da1a2
gvnsai/python_practice
/sample_codes/pattern-3.py
447
4.28125
4
#Python Program to Print an Identity Matrix n=int(input("Enter a number: ")) for i in range(0,n): for j in range(0,n): if(i==j): print("1",sep=" ",end=" ") else: print("0",sep=" ",end=" ") print() """ #output:-- Enter a number: 8 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 """
false
bb140ca795b32df2174f64676ea657a8674258b9
gvnsai/python_practice
/sample_codes/check-whether-number-positive-negative.py
209
4.46875
4
#To Reverse a Given Number. n=int(input("Enter number: ")) if(n>0): print("Number is positive") else: print("Number is negative") """ #output:-- Enter number: 6 Number is positive """
true
f3fef6642c6b7057c60d46889ed337b54942afac
Armando101/Curso-Python
/1-2-ejerciciosBasicos.py
2,669
4.4375
4
# Ejercicios conceptos básicos Python """ Los siguientes, son una serie de ejercicios que tienen como finalidad el que tu practiques los conocimientos adquiridos a lo largo de este segundo bloque. """ # Ejercicio 1: Dado de los valores ingresados por el usuario (base, altura) calcular y mostrar en pantalla el área de un triángulo. base = float(input("Ingrese la base de un triangulo\n")) altura = float(input("Ingrese la altura de un triangulo\n")) area = base*altura print("El area del triangulo es: ", area) print() # Convertir la cantidad de dólares ingresados por un usuario a pesos colombianos y mostrar el resultado en pantalla. dolar_pesoColombiano = 3298 dolares = float(input("Ingrese una cantidad en dolares\n")) pesos_colombianos = dolar_pesoColombiano*dolares print(dolares, " dolares son: ", pesos_colombianos, " pesos colombianos") print() # Convertir los grados centígrados ingresados por un usuario a grados Fahrenheit y mostrar el resultado en pantalla centigrados = float(input("Ingrese una cantidad de grados centigrados ")) fahrenheit = centigrados*(9/5) + 32 print(centigrados, " grados centigrados son: ", fahrenheit, " grados farenheit") print() # Mostrar en pantalla la cantidad de segundos que tiene un lustro. segundos_hora = 3600 print("Un lustro tiene ", segundos_hora*24*30*12*5, " segundos") print() # Calcular la cantidad de segundos que le toma a la luz viajar del sol a Marte y mostrar el resultado en pantalla. distancia_sol_marte = 227940000000 velocidad_luz = 3e8 tiempo_sol_marte = distancia_sol_marte/velocidad_luz print("La luz tarda ", tiempo_sol_marte, " segundos en viajar del sol a marte") print() # Calcular el número de vueltas que da una llanta en 1 km, dado que el diámetro de la llanta es de 50 cm, mostrar el resultado en pantalla. distancia = 1000 diametro = 0.5 numero_vueltas = distancia/diametro print("Una llanta da ", numero_vueltas, " vueltas en ", distancia, " metros") print() # Mostrar en pantalla True o False si la edad ingresada por dos usuarios es la misma. edad1 = int(input("Ingrese la edad del primer usuario ")) edad2 = int(input("Ingrese la edad del segundo usuario ")) print(edad1 == edad2) print() # Mostrar en pantalla la cantidad de meses transcurridos desde la fecha de nacimiento de un usuario. from datetime import date from datetime import datetime # Dia actual today=date.today() # Fecha actual now = datetime.now() month = int(input("En qué número de mes naciste? ")) year = int(input("¿En qué año naciste? ")) meses_transcurridos = (today.year-year)*12+today.month-month print("Han pasado ", meses_transcurridos, " meses desde que naciste")
false
6f96c9353738bbc1a0503f60d85d60a65e2934d6
vipal31/python_practice
/code_challenge2.py
366
4.5
4
# Small programme to check if its a leap year or not year = int(input("Which year do you want to check? ")) ## There are different methods to check if given year is leap year or not. if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print("Leap year") else: print("Not leap") else: print("Leap year") else: print("Not Leap")
true
e106dac64df3fe60e3ca115cd7b3e25b20d4e32c
EliasPapachristos/Python-Udacity
/iterators_generators.py
1,281
4.3125
4
lessons = ["Why Python Programming", "Data Types and Operators", "Control Flow", "Functions", "Scripting"] def my_enumerate(iterable, start=0): # Implement your generator function here count = start for el in iterable: yield count, el count += 1 for i, lesson in my_enumerate(lessons, 1): print("Lesson {}: {}".format(i, lesson)) """ If you have an iterable that is too large to fit in memory in full (e.g., when dealing with large files), being able to take and use chunks of it at a time can be very valuable. Implement a generator function, chunker, that takes in an iterable and yields a chunk of a specified size at a time. """ def chunker(iterable, size): # Implement function here for el in range(0, len(iterable), size): yield iterable[el:el + size] for chunk in chunker(range(25), 4): print(list(chunk)) """ Generator Expressions Here's a cool concept that combines generators and list comprehensions! You can actually create a generator in the same way you'd normally write a list comprehension, except with parentheses instead of square brackets. """ sq_list = [x**2 for x in range(10)] # this produces a list of squares sq_iterator = (x**2 for x in range(10)) # this produces an iterator of squares
true
a86f84274fb7cc32b10da5ee8e2e3b68a486c7dd
Jonpy1/python-para-zumbis-list02
/ex05 python para zumbis list02.py
625
4.125
4
#faça um programa que leia três numeros e mostre o maior e o menor deles a1 = int(input('Digite um numero: ')) a2 = int(input('Digite outro numero: ')) a3 = int(input('Digite mais um numero: ')) if (a1 < a2) or (a1 < a3): print('O menor valor é {}'.format(a1)) elif (a2 < a1) and (a2 < a3): print('O menor valor é {}'.format(a2)) elif (a3 < a1) and (a3 < a2): print('O menor valor é {}'.format(a3)) if (a1 > a2) or (a1 > a3): print('O maior valor é {}'.format(a1)) elif (a2 > a1) and (a2 > a3): print('O maior valor é {}'.format(a2)) elif (a3 > a1) and (a3 > a2): print('O maior valor é {}'.format(a3))
false
344c22526d8977db3bb97290e29f52cd8cc9dd03
svyatoslavn1000/algorithms_and_data_structures
/les_2/les_2_task_5.py
467
4.125
4
# Задание 5. # Вывести на экран коды и символы таблицы ASCII, # начиная с символа под номером 32 и заканчивая 127-м включительно. # Вывод выполнить в табличной форме: по десять пар «код-символ» в каждой строке. for p in range(32, 128): print(f'\t {p} - {chr(p)}', end = "") if p % 10 == 1: print()
false
b0991e8b9173dadd6ca5db32b67530d544dddcd8
svyatoslavn1000/algorithms_and_data_structures
/les_3/les_3_task_2.py
855
4.28125
4
# Задание 2. # Во втором массиве сохранить индексы четных элементов первого массива. Например, е # сли дан массив со значениями 8, 3, 15, 6, 4, 2, # второй массив надо заполнить значениями 0, 3, 4, 5 # (помните, что индексация начинается с нуля), # т. к. именно в этих позициях первого массива стоят четные числа. import random dim = 20 interval = 10 arr = [random.randint(-interval, interval) for _ in range(dim)] result = [] for p in range(len(arr)): if arr[p] % 2 == 0: result.append(p) print(f"Исходный массив: {arr}") print(f"Массив индексов четных элементов: {result}")
false
e68b843c55d899a69ec4c74583030604a4853444
MeisterKeen/Python-Projects
/pysql1.py
1,752
4.375
4
# # Author: KEEN LITTLE # # Date: 29 March 2021 # # Assignment Step 214, Python Course # The Tech Academy Software Development Bootcamp # # Purpose: to practice with python3 and sqlite3, showing how SQL queries can be # written and automated with Python. # ################################################################################ import sqlite3 fileList = ('information.docx', 'hello.txt', 'myImage.png', \ 'myMovie.mpg', 'World.txt', 'data.pdf', 'myPhoto.jpg') # Here are the file names that we're pulling into the database. def createTable(): conn = sqlite3.connect('pysql.db') with conn: cur = conn.cursor() # Creating a database with two fields: cur.execute("CREATE TABLE IF NOT EXISTS tbl_textFiles( \ ID INTEGER PRIMARY KEY AUTOINCREMENT, \ col_fileName VARCHAR(50) \ )") # We have a primary key and a varchar (string) for the names. conn.commit() conn.close() """ txtFileList = () def sortFiles(): # I'm just gonna grab the files I want for i in fileList: if i.endswith('.txt'): txtFileList.append(i) # And dump 'em into a new list! Easier. """ # Better idea: sort this with an if statement when I populate the table def filesToTable(): conn = sqlite3.connect('pysql.db') for item in fileList: # Iterating through the tuple, if item.endswith('.txt'): # Here we grab only the .txt files with conn: cur = conn.cursor() cur.execute("INSERT INTO tbl_textFiles (col_fileName) VALUES (?)", (item,)) print(item) conn.commit() conn.close() if __name__ == "__main__": createTable() # sortFiles() filesToTable()
true
a0527b825e8c3a041ef7c7b01373a8d40769ae7e
laudaccurate/Algosandbox
/Python/mastertickets.py
666
4.3125
4
TICKET_PRICE = 10 ticket_remaining = 100 #Output the number of tickets remaining print('There are {} tickets remaining'.format(ticket_remaining)) #Take the user's name and assign it to a variable username = input("Please enter your name? ") #Prompt the user by name for the nnumber of tickets needed number_of_tickets = int(input("Welcome {}, how many tickets do you want to purchase? ".format(username))) #Calculate the cost of the tickets and store it in a variable tickets_cost = number_of_tickets * TICKET_PRICE #Output the cost of the tickets to the user print("Okay {}, the cost of {} tickets is ${} .".format(username, number_of_tickets, tickets_cost))
true
1c08b4e9cfc2b0a2c3e82ddbfa91dad214b13588
Jingo88/Learning_Python
/exercises/fibonacci.py
756
4.125
4
########################################################################################### # Pass in a number. # Print out the fibonacci sequence up to that number # The sequence will start at "1" and continue to add the next value to the sum of the previous two values # [0,1,2,3,5,8,13,21,34] ########################################################################################### # # List # def fibo(n): # x = 0 # y = 1 # my_numbers = [] # for n in range(n): # my_numbers.append(x) # prev = x # x = y # y = prev + x # return my_numbers # print(fibo(10)) # Generator def fibo(n): x = 0 y = 1 for n in range(n): yield x prev = x x = y y = x + prev for num in fibo(10): print(num)
true
dc6428741b2d310a6ccb653e993c4f06f159a862
IanWafer/pands-problem-set
/Solution-7.py
1,070
4.34375
4
# Ian Wafer 03-03-2019 # Solution to problem 7 # Output approximate square root of an input positive floating point number # Info source https://stackoverflow.com/questions/6649597/python-decimal-places-putting-floats-into-a-string # Info source https://stackoverflow.com/questions/2440692/formatting-floats-in-python-without-superfluous-zeros import math # Import the math module for the square root function x = float(input("Please enter a positive number: ")) # User must input a value to begin solution if x <= 0: # Value needs to be positive for calculation x = float(input("Negative numbers not accepted. Please enter a positive integer: ")) # Reminder for a positive value is required assert x >= 0 # Check for true/false condition after x value input print("The square root of %f is approx. %.1f." % (x,math.sqrt(x))) # Print text with the %f function being a floating number and %.1f being the floating number to 1 decimal point.
true
a6604369345fa9142c0fad166788f08de6b904f8
haruka443/Fibonacci-number
/FIbonacciNumber.py
1,014
4.15625
4
amountOfNumbers = int(input('How many numbers of Fibonacci number do you want to list? ')) previousNumber = 1 currentNumber = 1 i = 0 FibonacciNumbers = [i, previousNumber, currentNumber] if amountOfNumbers > 3: while i < amountOfNumbers - 3: nextNumber = currentNumber + previousNumber previousNumber = currentNumber currentNumber = nextNumber i += 1 FibonacciNumbers.append(nextNumber) elif amountOfNumbers == 3: pass elif amountOfNumbers == 2: FibonacciNumbers.remove(FibonacciNumbers[-1]) elif amountOfNumbers == 1: del(FibonacciNumbers[1:3]) print(FibonacciNumbers) # amountOfNumbers = float(input('How many numbers of Fibonacci number do you want to list? ')) # lst = [0, 1, 1] # while len(lst) < amountOfNumbers: # newNumber = lst[len(lst) - 1] + lst[len(lst) - 2] # newNumber = lst[-1] + lst[-2] # lst.append(newNumber) # i = 1 # for number in lst: # print("%d, %d." % (i, number), end = ' ') # i += 1
false
6345d8b90c83b1979b3274d8b098a51502e178e7
khuongdang/python-practice
/ex19.py
1,256
4.25
4
# defines the function cheese_and_crackers with its argument variables def cheese_and_crackers(cheese_count, boxes_of_crackers): # displays how many cheeses # string formatter %d print "You have %d cheeses!" % cheese_count # displays how many boxes of crackers one # string formatter %d print "You have %d boxes of crackers!" % boxes_of_crackers # print print "Man, that's enough for a party!" print "Get a blanket.\n" print "We can just give the function numbers directly." # calls the function with cheese_count 20, boxes_of_crackers 30 cheese_and_crackers(20, 30) print "OR, we can use variables from our script:" # a variable holding the number 10 amount_of_cheese = 10 # another variable holding the number 50 amount_of_crackers = 50 # calls the function with the variable above cheese_and_crackers(amount_of_cheese, amount_of_crackers) print "We can even do math inside too:" # Calls the function and does the math for each argument variable cheese_and_crackers(10 + 20, 5 + 6) print "And we can combine the two, variables and math:" # Adds 100 to amount_of_cheese variable which was set at 10 # And adds 1000 to amount_of_crackers which was set at 50. cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
true
47f31bc4af0d19b6175d422168e7c3500b9463a9
zhangzheng888/Python
/Python 3/001 Numbers.py
837
4.1875
4
""" Data Types: Numbers We can use the type() function to know which class a variable or a value belongs to and isinstance() function to check if it belongs to a particular class. """ # Data Type Integer number = 8 # Output: <class 'int'> print(type(number)) # Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length. # Data Type Float number = -8.0 # Output: <class 'float'> print(type(number)) # Float, or "floating point number" is a number, positive or negative, containing one or more decimals. # Float can also be scientific numbers with an "e" to indicate the power of 10. # Data Type Complex complex_number = 5 + 3j # Output: (8+3j) print(complex_number + 3) # Output: True print(isinstance(complex_number, complex)) # Complex numbers are written with a "j" as the imaginary part.
true