blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
a806dad256f648f42532c9cf866a3c0e9caf48e7
Sasha1152/Training
/def_value_by_default.py
1,360
4.25
4
def foo(x, l=[]): l.append(x) print(x, l) foo(1) # 1 [1] foo(2) # 2 [1, 2] foo(3) # 3 [1, 2, 3] print('------'*3) def foo(x, l): l.append(x) print(x, l) l = [] foo(1, l) # 1 [1] foo(2, l) # 2 [1, 2] foo(3, l) # 3 [1, 2, 3] print('------'*3) def f(a = 0): a += 1 # Операція присвоєння по замовчуванню створює змінну у локальній області видимості print(a) f() # 1 f() # 1 f() # 1 print('------'*3) def unique(iterable, seen=set()): acc = [] for item in iterable: if item not in seen: seen.add(item) acc.append(item) return acc print(unique.__defaults__) # (set(),) l = [1, 1, 2, 3] print(unique(l)) # [1, 2, 3] print(unique.__defaults__) # ({1, 2, 3},) print(unique(l)) # [] print(unique.__defaults__) # ({1, 2, 3},) print('------'*3) def unique_better(iterable, seen=None): seen = set(seen or []) # equivalent: seen = set() acc = [] for item in iterable: if item not in seen: seen.add(item) acc.append(item) return acc print(unique_better.__defaults__) # (None,) l = [1, 1, 2, 3] print(unique_better(l)) # [1, 2, 3] print(unique_better.__defaults__) # (None,) print(unique_better(l)) # [1, 2, 3] print(unique_better.__defaults__) # (None,)
false
4fe99da9a59cc213e6a1f1e2d4cc83064118852e
Sasha1152/Training
/classes/circle_Raymond.py
2,119
4.125
4
# https://www.youtube.com/watch?v=tfaFMfulY1M&feature=youtu.be import math class Circle: """An advanced circle analitic toolkit""" __slots__ = ['diameter'] # flyweight design pattern suppresses the instance dictionary version = '0.1' # class variable def __init__(self, radius): self.radius = radius # instance variable @property # convert dotted access to method calls def radius(self): """Radius of a circle""" return self.diameter / 2 @radius.setter def radius(self, radius): self.diameter = radius * 2 def area(self): """Perform quadrature on a shape of uniform radius""" return math.pi * self.radius ** 2 def perimeter(self): return 2.0 * math.pi * self.radius @classmethod # alternative constructor def from_bbd(cls, bbd): """Construct a circle form a bounding box diagonal""" radius = bbd / 2.0 / math.sqrt(2.0) return cls(radius) # or Circle(radius) @staticmethod # attach functions to classes def angle_to_grade(angle): """Convert angle in degree to a percentage grade""" return math.tan(math.radians(angle)) * 100 cuts = [0.1, 0.5, 0.8] circles = [Circle(r) for r in cuts] for c in circles: print( f'A circlet with a radius of {c.radius}\n' f'has a perimeter {c.perimeter()}\n' f'and a cold area of {c.area()}' ) c.radius *= 1.1 # attribute was changed! print(f'and a warm area of {c.area()}\n') с = Circle.from_bbd(25.1) print( f'A circlet with a bbd of 25.1\n' # f'has a radius {c.radius()}\n' # TypeError: 'float' object is not callable f'and an area of {c.area()}\n' ) class Tire(Circle): """Tires are circles with a corected perimeter""" def perimeter(self): """Circumference corrected for rubber""" return Circle.perimeter(self) * 1.25 t = Tire(22) print( f'A tire of radius {t.radius}\n' f'has an inner area of {t.area()}\n' f'and an odometer corrected perimeter of {t.perimeter()}' )
true
a5a57b64d94b05d9d17fb70835b7957caa2eff62
cihangirkoral/python-rewiew
/homework_02.py
1,834
4.71875
5
# ################ HOMEWORK 02 ###################### # 4-1. Pizzas: Think of at least three kinds of your favorite pizza Store these # pizza names in a list, and then use a for loop to print the name of each pizza # • Modify your for loop to print a sentence using the name of the pizza # instead of printing just the name of the pizza For each pizza you should # have one line of output containing a simple statement like I like pepperoni # pizza # • Add a line at the end of your program, outside the for loop, that states # how much you like pizza The output should consist of three or more lines # about the kinds of pizza you like and then an additional sentence, such as # I really love pizza! # 4-2. Animals: Think of at least three different animals that have a common characteristic Store the names of these animals in a list, and then use a for loop to # print out the name of each animal # • Modify your program to print a statement about each animal, such as # A dog would make a great pet. # • Add a line at the end of your program stating what these animals have in # common You could print a sentence such as Any of these animals would # make a great pet! ############################ P İ Z Z A ########################### pizza_list = ["margarita" , "pepperoni" , "cheddar"] for pizza in pizza_list: print (pizza + " is great" + ". I love it soooo much.") print ("me and my best friend Köksal, we love pizza so much, the best pizza is margarita\n") ############################ A N İ M A L S ####################### animal_list = ["dog" , "cat" , "hamster"] for animal in animal_list: print ("A " + animal + " is very cute") print ("These animals would make great pets!!!")
true
efe029dfb58aa46842ed74b76c21914d988a802e
SyedAltamash/AltamashProgramming
/Fibonacci_Sequence.py
393
4.15625
4
#from math import e #result = input('How many decimal places do you want to print for e: ') #print('{:.{}f}'.format(e, result)) def fibonacci_sequence(number): list = [] a =1 b = 1 for i in range(number): list.append(a) a,b = b,a+b print(list) result = int(input('Hey enter a number for the Fibonacci Sequence: ')) fibonacci_sequence(result)
true
539949c601098bf6ee18857023a80eb440d06426
6reg/data_visualization
/visualize.py
1,899
4.1875
4
""" Image Visualization Project. This program creates visualizations of data sets that change over time. For example, 'child-mortality.txt' is loaded in and the output is a vsualization of the change in child mortality around the world from 1960 until 2017. Red means high and green means low. """ from simpleimage import SimpleImage DATA_SET = 'data-illiteracy.txt' GREEN = 127 BLUE = 127 MAX_RED_VALUE = 255 CANVAS_WIDTH = 1100 CANVAS_HEIGHT = 200 def main(): canvas = SimpleImage.blank(CANVAS_WIDTH, CANVAS_HEIGHT) red_values = get_red_values() canvas = make_image(red_values, canvas) canvas.show() def get_red_values(): red_values = [] with open(DATA_SET) as file: for i in range(2): next(file) for line in file: line = line.strip() red_values.append(round(float(line) * MAX_RED_VALUE)) return red_values def get_pixel_color(red_value, pixel): pixel.red = red_value pixel.green = GREEN pixel.blue = BLUE return pixel def make_image(red_values, canvas): # Get width each stripe should be stripe_width = CANVAS_WIDTH // len(red_values) # 100 // 11 = 100 # Create blank canvas as wide as length of data set new_canvas = SimpleImage.blank(stripe_width * len(red_values), CANVAS_HEIGHT) # For each stripe on canvas.. for each_stripe in range(len(red_values)): for x in range(stripe_width): for y in range(CANVAS_HEIGHT): # Get starting point of each "each_stripe" start_x = stripe_width * each_stripe + x pixel = canvas.get_pixel(start_x, y) # Update pixel with red value from data set pixel = get_pixel_color(red_values[each_stripe], pixel) new_canvas.set_pixel(start_x, y, pixel) return new_canvas if __name__ == '__main__': main()
true
b98da74f144dc5cb6a3f6e691f9a0f2e41a8cb03
frisomeijer/ProjectEuler100
/Problem_020/Solution_020.py
660
4.15625
4
''' Problem 20: n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! ''' import time start_time = time.time() def factorial_digit_sum(n): factorial=1 fact_sum=0 for number in range(1,n+1): factorial*=number for digit in str(factorial): fact_sum+=int(digit) return fact_sum print(factorial_digit_sum(100)) # calculation time: 0.0030336380004882812 seconds print("calculation time: %s seconds" % (time.time() - start_time))
true
a82368543cd9c132cf1b7be409942c718b2e6d54
luissalgueiro/curso_iot
/codigos_py/dog.py
1,267
4.15625
4
## AUTHOR= Luis Salgueiro ## DATE= 21/10/2019 ## DESCRIPTION = CODE FOR ACTIVITY 2 OF PLA3 class Dog: species="caniche" def __init__(self, name, age): self.name = name self.age = age bambi = Dog("Bambi", 5) mikey = Dog("Rufus", 6) boby = Dog("Boby",15) rino = Dog("Rino", 5) oli = Dog("Oli", 8) oto= Dog("Oto", 3) #print("{} is {} and {} is {}".format(bambi.name, bambi.age, mikey.name, mikey.age)) #print("{} is {} and {} is {}".format(bambi.name, bambi.age, mikey.name, mikey.age)) #print("{} is {} and {} is {}".format(bambi.name, bambi.age, mikey.name, mikey.age)) print("I had three dogs") print("{} and pased away at the age of {} ".format(boby.name, boby.age)) print("{} and pased away at the age of {} ".format(rino.name, rino.age)) print("{} and pased away at the age of {} ".format(oli.name, oli.age)) print("Know I have other dog which name is {}, it`s totally crazy".format(oto.name)) if bambi.species=="dcaniche": print("{0} is a {1}!".format(bambi.name, bambi.species)) def get_biggest_number(): print("Please insert the list of integer numbers") s = input() a = list(map(int, s.split())) print("You inserted this list", a) a.sort() print("The biggest value is: ",a[-1]) get_biggest_number()
false
cf39769061e619e9a3edf87688327e97f96ccf26
prasanna1695/python-code
/1-2.py
474
4.34375
4
#Write code to reverse a C-Style String. #(C-String means that abcd is represented as five characters # including the null character.) def reverseCStyleString(s): reversed_string = "" for char in s: reversed_string = char + reversed_string return reversed_string print "Test1: hello" print reverseCStyleString("hello") == "olleh" print "Test2: ob" print reverseCStyleString("ob") == "bo" print "Test3: ''" print reverseCStyleString('') == '' ## To do later, utf-8?
true
487b0fedc3b0d970786718cf9034254afbf0d8b4
prasanna1695/python-code
/4-1.py
2,695
4.40625
4
#Implement a function to check if a tree is balanced. For the purposes of this question, #a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one class Tree(object): def __init__(self): self.left = None self.right = None self.data = None #not necessarily a binary tree so I'll implement it as binary and comment how to extend it def isTreeBalenced(tree): if abs(maxDistance(tree) - minDistance(tree)) < 2: return True else: return False def maxDistance(tree): #keep adding and "tree.direcrection == None" for non-binary case if tree == None or tree.left == None and tree.right == None: return 0 #seems messy to have to do this type of checking if the tree is more than binary. elif cases grow exponentially... :( elif tree.left == None and tree.right != None: return 1 + maxDistance(tree.right) elif tree.right == None and tree.left != None: return 1 + maxDistance(tree.left) else: #keep adding and ", maxDistance(tree.direction)" for non-binary case return 1 + max(maxDistance(tree.left), maxDistance(tree.right)) def minDistance(tree): #keep adding and "tree.direcrection == None" for non-binary case if tree == None or tree.left == None and tree.right == None: return 0 #seems messy to have to do this type of checking if the tree is more than binary. elif cases grow exponentially... :( elif tree.left == None and tree.right != None: return 1 + minDistance(tree.right) elif tree.right == None and tree.left != None: return 1 + minDistance(tree.left) else: #keep adding and ", minDistance(tree.direction)" for non-binary case return 1 + min(minDistance(tree.left), minDistance(tree.right)) root = Tree() root.data = "root" print "Test 0: empty tree" print isTreeBalenced(root) == True root.left = Tree() root.left.data = "left" root.left.left = Tree() root.left.left.data = "left left" root.left.right = Tree() root.left.right.data = "left right" root.right = Tree() root.right.data = "right" root.right.left = Tree() root.right.left.data = "right left" root.right.right = Tree() root.right.right.data = "right right" print "Test 1: full binary tree of depth 2" print isTreeBalenced(root) == True root.left.left.left = Tree() root.left.left.left.data = "left, left, left" print "Test 2: add a leaf on the left" print isTreeBalenced(root) == True root.left.left.left.left = Tree() root.left.left.left.left.data = "left, left, left, left" print "Test 3: add a leaf too many on the left" print isTreeBalenced(root) == False root.left.left.left.left = None root.right.left = None print "Test 4: trim too long left & also clip right>left" print isTreeBalenced(root) == True
true
f98cea48e5ef2da1ddd158c9cab3e2102f4a2fa0
johnsonl7597/CTI-110
/P2HW2_ListSets_JohnsonLilee.py
1,190
4.34375
4
#This program will demonstrate the students understanding of lists and sets. #CTI-110, P2HW2 - List and Sets #Lilee Johnson #05 Oct 2021 #----------------------------------------------------------------------------- #pesudocode #prompt user for 6 indivual numbers #store the numbers in a list called List6 #display lowNum, highNum, total, average #set(List6) #display List6, set #----------------------------------------------------------------------------- num1 = int(input("Enter number 1 of 6 > ")) num2 = int(input("Enter number 2 of 6 > ")) num3 = int(input("Enter number 3 of 6 > ")) num4 = int(input("Enter number 4 of 6 > ")) num5 = int(input("Enter number 5 of 6 > ")) num6 = int(input("Enter number 6 of 6 > ")) list6 = [num1, num2, num3, num4, num5, num6] print("\nList6 list:\n", list6) lowNum = min(list6) highNum = max(list6) total = num1 + num2 + num3 + num4 + num5 + num6 average = total / 6 listSix = {num1, num2, num3, num4, num5, num6} print("smallest number in List6: ", lowNum) print("LARGEST number in List6: ", highNum) print("Sum of numbers in List6: ", total) print("The average in List6: ", average) print("\nListSix set:\n", listSix)
true
124651b1e5621e7b54ff62ce933226a778393798
hnhillol/PythonExercise
/HwAssignment7.py
1,903
4.125
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 7 02:34:40 2019 @author: hnhillol Homework Assignment #7: Dictionaries and Sets Details: Return to your first homework assignments, when you described your favorite song. Refactor that code so all the variables are held as dictionary keys and value. Then refactor your print statements so that it's a single loop that passes through each item in the dictionary and prints out it's key and then it's value. Extra Credit: Create a function that allows someone to guess the value of any key in the dictionary, and find out if they were right or wrong. This function should accept two parameters: Key and Value. If the key exists in the dictionary and that value is the correct value, then the function should return true. In all other cases, it should return false. """ MyFavSong={"Song Name":"Here comes the Sun","Band Name":"The Beatles", "Artist":"George Harrison","Album" : "Abbey Road", "Publisher":"Harrisongs","Released Date":"26" ,"Release Months":"September","Release Year":"1969", "Recorded Period":"7th July-19th August","Genre":"Folk pop , Pop Rock","Length":"3.06","Lable":"Apple", "Writter":"George Harrison","Producer":"George Martin"} print("Here is the song Data") print("*********************") for key in MyFavSong : print(key,":",MyFavSong[key]) print ("\n") print("Cross Checking the input data") print("*****************************") def FindSongInfo(key,value): if key in MyFavSong: if MyFavSong[key]==value: print("You are Correct !!") return True else: print("Attribute Data is incorrect !!") return False else: print("Attribute Doesn't Exist") return False key=input("Please enter the Attribute to check: ") value=input("Guess the Data of the Attribute: ") print(FindSongInfo(key,value))
true
f2962e714e32fc1ce26a388eb416ccd20f72fa36
diegoarielsimonelli/variables_python
/ejercicios_profunidzacion/profundizacion_1.py
1,598
4.375
4
# Tipos de variables [Python] # Ejercicios de profundización # Autor: Inove Coding School # Version: 2.0 # NOTA: # Estos ejercicios son de mayor dificultad que los de clase y práctica. # Están pensados para aquellos con conocimientos previo o que dispongan # de mucho más tiempo para abordar estos temas por su cuenta. # Requiere mayor tiempo de dedicación e investigación autodidacta. # IMPORTANTE: NO borrar los comentarios en VERDE o NARANJA # Ejercicios de práctica con números ''' Enunciado: Realice un calculadora, se ingresará por línea de comando dos números reales y se deberá calcular todas las operaciones entre ellos: A) Suma B) Resta C) Multiplicación D) División E) Exponente/Potencia - Para todos los casos se debe imprimir en pantalla el resultado aclarando la operación realizada en cada caso y con que números se ha realizado la operación ej: La suma entre 4.2 y 6.5 es 10.7 ''' # Empezar aquí la resolución del ejercicio print("bienvenido/a a la calculadora") print("Ingrese un numero") valor1 = int(input()) print("Ingrese un segundo numero") valor2 = int(input()) # Suma Suma= valor1 + valor1 print("La suma de", valor1, "y", valor2, "es",Suma) # Resta Resta= valor1- valor2 print("La resta de", valor1, "y", valor2, "es",Resta) #Multiplicación Multiplicacion= valor1 * valor2 print("La multiplicación de", valor1, "y", valor2, "es",Multiplicacion) #Division Division= valor1 / valor2 print("La división de", valor1, "y", valor2, "es",Division) #Potencia Potencia= valor1 ** valor2 print("La potencia de", valor1, "y", valor2, "es",Potencia)
false
7f3cf610dffccafa759a59ce287ffc73ee2a9639
SyriiAdvent/Intro-Python-I
/src/13_file_io.py
967
4.28125
4
""" Python makes performing file I/O simple. Take a look at how to read and write to files here: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files """ # Open up the "foo.txt" file (which already exists) for reading # Print all the contents of the file, then close the file # Note: pay close attention to your current directory when trying to open "foo.txt" with open('foo.txt', mode="r") as f: print(f.read()) # Open up a file called "bar.txt" (which doesn't exist yet) for # writing. Write three lines of arbitrary content to that file, # then close the file. Open up "bar.txt" and inspect it to make # sure that it contains what you expect it to contain with open('bar.txt', 'a') as f: f.write("I am line 1 \n") f.write("I am line 2 \n") f.write("I am line 3 \n") # Using python to create python script files! with open('bar.py', 'a') as f: f.write("for ltr in 'Tuna ate the goldfish!':") f.write(f"\n \t print(ltr)")
true
48d2d40bb733d33b57da20111b607832579a9aee
cs-fullstack-2019-fall/python-loops-cw-rjrobins16
/classwork.py
1,507
4.5625
5
# ### Exercise 1: # Print -20 to and including 50. Use any loop you want. # for x in range(-20,51,1): print(x) # ### Exercise 2: # Create a loop that prints even numbers from 0 to and including 20. # Hint: You can find multiples of 2 with (whatever_number % 2 == 0) for x in range(0,21,2): if x % 2 == 0: print(x) # ### Exercise 3: # Prompt the user for 3 numbers. Then print the 3 numbers along with their average after the 3rd number is entered. # Refer to example below replacing ```NUMBER1```, ```NUMBER2```, ```NUMBER3```, and ```THEAVERAGE``` with the actual values. # # Ex.Output # ``` # The average of NUMBER1, NUMBER2, and NUMBER3 is THEAVERAGE num1 = int(input("Enter a number.")) num2 = int(input("Enter a second number.")) num3 = int(input("Enter a third number.")) average = (num1 + num2 + num3) / 3 print(average) # ### Exercise 4: # Use any loop to print all numbers between 0 and 100 that are divisible by 4. # #for x in range(0,100,1): #print (100 % 4 == 0) for x in range(0,100,1): if x % 4 == 0: print (x) # ### Challenge: # Password Checker - Ask the user to enter a password. Ask them to confirm the password. # If it's not equal, keep asking until it's correct or they enter 'Q' to quit. userpassword=input("Enter a password.") userpassword2=input("Re-enter a password.") while userpassword != userpassword2 and userpassword2 != 'q': print ("Passwords do not match. Please re-enter your password:") userpassword2=input() ###
true
3325662f01c1766dc3c42943e6a1e12c56c354ef
jarvis-1805/Simple-Python-Projects
/theGuessingGame.py
900
4.15625
4
import random print("\t\t\tThe Guessing Game!") print("WARNING!!! Once you enter the game you have to guess the right number!!!\n") c = input("Still want to enter the game!!! ('y' or 'n'): ") print() while c == 'y': true_value = random.randint(1, 100) while True: chosed_value = int(input("Choose a number between 1 and 100: ")) if (chosed_value == true_value): print("\nYou guessed it right!!! Good job!!!") break elif (chosed_value > 100 or chosed_value < 0): print("\nYou did not choose the number within range!!!") elif (chosed_value < true_value): print("\nYour number is low...Try again!!!") elif (chosed_value > true_value): print("\nYour number is high...Try again!!!") c = input("\nDo you want to play again? ('y' or 'n'): ")
true
f1f869c390877cfc42bcd25dbec63137b46e3533
kaizer1v/ds-algo
/datastructures/matrix.py
1,797
4.125
4
class Matrix: ''' [[1, 2], [2, 1]] is a matrix ''' def __init__(self, arr): self.matrix = arr self.height = self.calc_height() self.width = self.calc_width() def calc_height(self): return len(self.matrix) def calc_width(self): if self._is_valid(): return len(self.matrix[0]) else: raise Exception('Size of all rows must be same') def _is_valid(self): ''' checks if size of each row of the matrix is the same ''' f = len(self.matrix[0]) for a in self.matrix: if len(a) != f: return False return True def get_dimension(self): return (self.width, self.height) def _is_square(self): ''' compute if height & widht of matrix is the same ''' return self.width == self.height def __repr__(self): print( '\n'.join([ ' '.join(list(map(lambda x: str(x), a))) for a in self.matrix ]) ) def __add__(self, m): ''' adds current matrix with `m` | 1 2 | | 2 1 | | . . | | 2 1 | + | 1 2 | = | . . | ''' # if not self.get_dimension(m): # return False pass def __sub__(self, m): ''' substracts current matrix with `m` ''' pass def __mul__(self, m): ''' multiplies current matrix with `m` ''' pass def eq_size(self, m): ''' checks if current matrix and given matrix are of same dimensions ''' return self.get_dimension() == m.get_dimension() def __eq__(self, m): ''' checks if current matrix == `m` ''' pass
true
5dd783701c899fae07a094a2e2fce4094e370942
kaizer1v/ds-algo
/datastructures/priority_queue.py
1,388
4.40625
4
''' Priority Queue Prioritiy queue operates just like a queue, but when `pop`-ing out the first element that was added, it instead takes out the highest (max) element from the queue. Thus, the items in the priority queue should be comparable. When you add a new item into the queue, it will automatically remove the min value so that the size of the queue remains fixed. WHY? One could always use a normal queue, sort it (desc) and then pop the first one (max). NO - this isn't efficient because, doing that the memory required will be `N` (size of the items in the queue) and the sorting time will take `n log(n)` time, but using a Priority Queue will do that in `n log(m)` and the space required will be `m` only where m < n IMPLEMENTATION The implementation can be done using a linked list or a binary tree. Either way, the data structure (DS) will always be sorted as soon as you insert an item in the DS. ''' class PriorityQueueUsingLinkedList: pass class PriorityQueueUsingBinaryTree: def __init__(self): pass def swim(self): ''' Moves the item up in order of the tree ''' pass def sink(self): ''' Moves the item down in order of the tree ''' pass def xchange(self, a, b): ''' Exchanges a with b ''' a, b = b, a return self
true
acd3f5a7488cfaf4a3ee5df935eb200f85f3e98d
Hafidzmhmmd/PurwadhikaDataScience
/EXAM_MODUL_1_MUHAMMAD_HAFIDZ_JAKARTA.py
1,913
4.15625
4
# ---------------------------------------------<1>--------------------------------------------- kata = 'hello there how are you doing' def hastag(string): if string == '': output = 'False' else: word = string.split(' ') output = '#' for x in range(len(word)): txt = word[x] txt = txt.capitalize() output += txt if len(output) - 1 > 140 or output == '#': output = 'False' return print(output) hastag(kata) # ---------------------------------------------<2>--------------------------------------------- pon = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] def create_phone_number(number): output = '(xxx) xxx-xxxx' for num in number: output = output.replace('x', str(num), 1) return print(output) create_phone_number(pon) # ---------------------------------------------<3>--------------------------------------------- number = [5, 3, 2, 8, 1, 4] def sort_odd_even(num): indexOdd = [] indexEven = [] # tracing for each in num: if each % 2 == 0 or each == 0: indexEven.append(num.index(each)) else: indexOdd.append(num.index(each)) # sorting for odd in range(len(indexOdd)-1): for oddx in range(odd+1, (len(indexOdd))): if num[(indexOdd[odd])] > num[(indexOdd[oddx])]: num[(indexOdd[odd])], num[(indexOdd[oddx])] = num[( indexOdd[oddx])], num[(indexOdd[odd])] for even in range(len(indexEven)-1): for evenx in range(even+1, (len(indexEven))): if num[(indexEven[even])] < num[(indexEven[evenx])]: num[(indexEven[even])], num[(indexEven[evenx])] = num[( indexEven[evenx])], num[(indexEven[even])] return print(num) sort_odd_even(number)
false
803aa2044f18114b72acaa66d0412cdcb61a3d48
Arsenault-CMSC201-Fall2019/Spring_2020_code_samples
/February_17_coding.py
985
4.28125
4
# Examples of code using while loops # from Monday, Feb. 17 age = 0; while (age < 18): age = input("enter your age in years: ") print ("If you’re 18 or older you should vote") print ("that's the end of our story") # compute 10! Using a while loop product = 1 factor = 1 while factor <= 10: product *= factor #or product = product * factor factor += 1 print("our answer is ", product) num = 1 while num % 2 == 0: print(num) num += 2 age = int(input("please enter your age in years: ")) while (age < 0) or (age > 100): print("Age must be between 0 and 100 inclusive ") age = int(input("please enter your age in years: ") grade = "" name = "" while name != "Hrabowski": # get the user's grade grade = input("What is your grade? ") print("You passed!") cookiesLeft = 50 while cookiesLeft > 0: # eat a cookie cookiesLeft = cookiesLeft + 1 #print all the positive odd numbers #less than 100 num = 1 while num != 100: print(num) num = num + 2
true
e7f171ee421609f0c28813cb89cb8869ca9510fe
Arsenault-CMSC201-Fall2019/Spring_2020_code_samples
/February_5_code.py
408
4.1875
4
###################### # # This is one way to write a block # of comments # ######################## """ This is another way to write a block of comments """ ''' This will work too ''' verb = input("please enter a verb") new_verb = verb + "ing" print(new_verb) principal = 10000 rate = 0.03/12 n_payments = 72 cost = (principal * rate * (1 + rate)**n_payments)/((1 + rate)**n_payments -1) print(cost)
true
864d5005fbc7a132a7ee970d006bbf40503496e6
Arsenault-CMSC201-Fall2019/Spring_2020_code_samples
/February_19_coding.py
1,230
4.125
4
#coding for Wednesday, February 19 # Printing new lines, or not print("this produces two lines", "\n", "of output") print("this produces one line", end="") print("of output") # printing out an integer print("{:d} is the answer to the question".format(42)) #printing the same value as a float print("{:f} is the answer to the question".format(42)) #limiting the number of decimal places print("{:6.2f} is the answer to the question".format(42)) if roll == 7 or roll == 11: print ("you win") elif roll == 2 or roll == 3 or roll == 12: print("you lose") else: print("roll again") CRAPS_WINNING_VALUES = [7,11] CRAPS_LOSING_VALUES = [2,3,12] if roll in CRAPS_WINNING_VALUES: print("you win") elif roll in [2,3,12]: print ("you lose") else: print("roll again") str = 'Hey diddle diddle the cat and the fiddle”' str_list = str.split() #this will split on whitespace, and the whitespace will be deleted str_list = str.split("e") #what does this do? What happened to the “e” ? int_str = "3 1 4 5 6 7 8 9 10" int_list = int_str.split() actual_int_list = [] for num in int_list: actual_int_list.append(int(num)) print("now is the time", end="this is where we stop") print("and now we start again")
true
3892ee83ecc247e92abac626cad19c4d8285f715
arizala13/interview_cake
/hash_map_example.py
333
4.125
4
def return_true_or(s): count_chars = {} for char in s: if char in count_chars: count_chars[char] += 1 else: count_chars[char] = 1 print(count_chars) return_true_or("racecar") # practice of adding a value to a dictionary # and keeping track of how many times its been seen #
false
b987f123317a7f8e3feaf6dac464732e13fec601
Spideyboi21/jash_python_pdxcode
/python learning/test.py
350
4.125
4
if -4 < -6: print("True") else: print('False') if "part" in "party!!!1": print("True") else: print("False") age = input('how old are you?') if int(age)< 28 and int(age) >=0: print("this is valid") else: print("not valid") name = input('What is my name? ') if name == "Jash": print("that is correct congratulations")
true
022bddfcc020eb7273a2180a8d391d3fd383ecea
jldupont/jldupont.com
/trunk/Tests/PYTHON/TestClassMethods.py
521
4.15625
4
class X: def m(cls, p): print "X: cls=%s , p=%s" % (cls,p) # required for X.m() to work m = classmethod(m) class Y(X): def m(cls,p): print "Y: cls=%s , p=%s" % (cls,p) X.m(p) # required for X.m() to work m = classmethod(m) if (__name__ == "__main__" ): x=X() x.m(666) X.m(999) print "" y=Y() print "y.m(333): %s" % y.m(333) print "Y.m(555): %s" % Y.m(555) """ cls=__main__.X , y=666 cls=__main__.X , y=999 """
false
82b473b6d4b8ce07c42b92870b91fee3fb5c8da5
soonebabu/firstPY
/first.py
318
4.21875
4
def checkPrime(num): if num==1 or num==2 or prime(num): return False else: return True def prime(num): for i in range(3,num-1): if (num%i)==0: return True value = input('enter the value') print(value) if checkPrime(value): print('prime') else: print('not')
true
aa5377b9f0a11e32cde4fa8c7ac47ca3bbb9f659
BigBoiTom/Hangman-Game
/Hangman_Game.py
2,686
4.15625
4
import random, time def play_again(): answer = input('Would you like to play again? yes/no: ').lower() if answer == 'y' or answer == 'yes': play_game() elif answer == 'n' or answer == 'no': print("Thanks for Playing!") time.sleep(2) exit() else: pass def get_word(): words = ['pear', 'apple', 'banana', 'grape', 'pineapple', 'orange', 'apricot', 'grapefruit', 'eggplant', 'cabbage', 'broccoli', 'lavender', 'spinach', 'cauliflower', 'lettuce', 'onions', 'pepper', 'carrot', 'tomato', 'strawberry', 'mango', 'pumpkin', 'celery', 'cucumber', 'garlic', 'avocado', 'kiwi', 'blueberry', 'raspberry', 'mandarin'] return random.choice(words) name = input("Please enter your name: ") print("Hello", name, "let's Begin!") time.sleep(1) print("Try to guess the word chosen by the computer!") time.sleep(1) print("You can only guess 1 letter at a time") print("Press Enter after typing a letter") time.sleep(2) print("Let's Start!!") time.sleep(1) def play_game (): alphabet = 'abcdefghijklmnopqrstuvwxyz' word = get_word() letters_guessed = [] tries = 10 guessed = False print('The word contains ', len(word), ' letters.') print(len(word) * '*') while guessed == False and tries > 0: print("You have " + str(tries) + ' tries left') guess = input("Please enter one letter. ").lower() if len(guess) == 1: if guess not in alphabet: print("You have not entered a letter!") elif guess in letters_guessed: print("You already guessed this letter, try another!") elif guess not in word: print("That letter is not part of the word!") letters_guessed.append(guess) tries -=1 elif guess in word: print("Good Job, You guessed a letter!") letters_guessed.append(guess) else: print("How did you even get this message? Go away!") if len(guess) != 1: print("Please only put in 1 letter!") status = '' if guessed == False: for letter in word: if letter in letters_guessed: status += letter else: status += '*' print(status) if status == word: print("Great Job ", name, " You guessed the word") guessed == True play_again() elif tries == 0: print("You are out of tries, better luck next time!") print("The word was: ", word) play_again() play_game()
true
1e9b87bca4f32738e79e1dec5654589374328125
juancoan/python
/Basic/WtihASDemo.py
989
4.125
4
""" WITH / AS keywords """ # print("Normal WRITE start") # File2 = open("File_IO.txt", "w") # File2.write("Trying to write to the file2.") # File2.close() #If I do not write the close() statement, nothing will happen. ALWAYS write it # # print("Normal READ start") # File3 = open("File_IO.txt", "r") # for line in File3: # print(line) print("WITH AS WRITE start") #no need to use CLOSE statement with open("WtihASDemo.txt", 'w') as VariableName: #start using 'with' keybord, variable object at the end 'as Variable name' print("Writting to file...") VariableName.write("Writting with WITH_AS function.") # same write function print('#*'*20) print("WITH AS READ start") #no need to use CLOSE statement with open("WtihASDemo.txt", 'r') as VariableName2: for lines in VariableName2: print(lines) print('#*'*20) print("Using .READ() function") #no need to use CLOSE statement with open("WtihASDemo.txt", 'r') as VariableName2: print(VariableName2.read())
true
3a136144b49f4e564b98cd44b97e77cf73866e93
juancoan/python
/Basic/File2Read.py
795
4.1875
4
my_file2 = open("File2Read.txt", 'r') #use the 'r' mode to read print(str(my_file2.read())) #prints the read method, all the content of the file my_file2.close() print('#*'*20) print("LINE BY LINE EXAMPLE......... Will print the first line only, unless I call that print method twice") my_file_BY_LINE = open("File2Read.txt", 'r') #use the 'r' mode to read print(str(my_file_BY_LINE.readline())) #prints the read method, all the content of the file my_file_BY_LINE.close() print('#*'*20) print("LINE BY LINE EXAMPLE with FOR LOOP.........") my_file_withFOR = open("File2Read.txt", 'r') #use the 'r' mode to read for line in my_file_withFOR: Mayuscula = line.upper() #guardo el cambio en una variable y le aplico el metodo print(Mayuscula)#imprimo la variable my_file_withFOR.close()
true
80a1b64a82ff503d1d41333e893f449881ee87c6
CircleZ3791117/CodingPractice
/source_code/717_1BitAnd2BitCharacters.py
1,646
4.25
4
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'circlezhou' ''' Description: We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11). Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero. Example 1: Input: bits = [1, 0, 0] Output: True Explanation: The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character. Example 2: Input: bits = [1, 1, 1, 0] Output: False Explanation: The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character. Note: 1 <= len(bits) <= 1000. bits[i] is always 0 or 1. ''' class Solution(object): def isOneBitCharacter(self, bits): """ :type bits: List[int] :rtype: bool """ if len(bits) < 2: return True nums_of_1 = 0 current_index = -2 while(abs(current_index) <= len(bits)): if bits[current_index] == 0 and nums_of_1 % 2 == 0: return True if bits[current_index] == 0 and nums_of_1 % 2 == 1: return False if bits[current_index] == 1: nums_of_1 += 1 current_index -= 1 if nums_of_1 % 2 == 0: return True else: return False ## Super cool, the above method beats 100.00% of python3 submissions. # A more elegant expression using Greedy class Solution(object): def isOneBitCharacter(self, bits): """ :type bits: List[int] :rtype: bool """ parity = bits.pop() while bits and bits.pop(): parity ^= 1 return parity == 0
true
ff935fe0a87fbe0539bce9c276773eacbd9d06ed
yourspleenfell/python_fundamentals
/dictionary/dict.py
831
4.1875
4
# Create a dictionary containing information about yourself. Keys should include name, age, country of birth and favorite language. # Write a function that will print something about the dictionary. def aboutMe(): me = { "first_name":"Dylan", "last_name":"Arbuthnot", "age":"26", "birthplace":"Phoenix, AZ, USA", "fav_lang":"Python!" } for val in me.itervalues(): if val == me["first_name"]: print "My first name is " + val elif val == me["last_name"]: print "My last name is " + val elif val == me["age"]: print "I am " + val + " years old" elif val == me["birthplace"]: print "I was born in " + val elif val == me["fav_lang"]: print "My favorite language is " + val aboutMe()
false
ad79baa9bd795e7e28ba7df8db472be9725d86de
amitauti/HelloWorldPython
/ex02.py
1,019
4.25
4
# http://www.practicepython.org/exercise/2014/02/05/02-odd-or-even.html # Ask the user for a number. Depending on whether the number is even or # odd, print out an appropriate message to the user. import sys def main(): askuser () def askuser(): #part one str = input("Enter a number: ") num = int(float(str)) newnum = num % 2 if newnum == 0: print ("It is even number") else: print ("It is odd number") #part two num = num % 4 if num == 0: print (" and divisible by 4 as well!") #part three str1 = input("Give me a number as numerator ") str2 = input("Give me a number as denomitor ") num_one = int(float(str1)) num_two = int(float(str2)) # this is comment this if num_two == 0: print("We can not devide by zero") sys.exit() else: if num_one % num_two == 0: print("It is a even number") else: print ("It is a odd number") if __name__ == '__main__': main()
true
2f7f8cb23eb74c9046769b6200a49147384375cd
nasirmajid29/Anthology-of-Algorithms
/Algorithms/sorting/mergeSort/mergeSort.py
972
4.28125
4
def mergeSort(array): if len(array) > 1: middle = len(array) // 2 # Finding the middle of the array left = array[:middle] # Split array into 2 right = array[middle:] mergeSort(left) # sorting the first half mergeSort(right) # sorting the second half # Copy data to temp arrays L[] and R[] merge(array, left, right) def merge(array, left, right): i = j = k = 0 while i < len(left) and j < len(right): if left[i] < right[j]: array[k] = left[i] i += 1 else: array[k] = right[j] j += 1 k += 1 # Checking if any element are left from either array while i < len(left): array[k] = left[i] i += 1 k += 1 while j < len(right): array[k] = right[j] j += 1 k += 1 if __name__ == "__main__": alist = [54,26,93,17,77,31,44,55,20] mergeSort(alist) print(alist)
true
2929f49be61557f3233c7c68291711c9426c4638
huchen086/web-caesar
/caesar.py
1,154
4.1875
4
def alphabet_position(letter): """receives a letter (that is, a string with only one alphabetic character)""" """and returns the 0-based numerical position of that letter""" """within the alphabet.""" letter = letter.upper() position = ord(letter) - 65 return position def rotate_character(char, rot): """receives a character char (that is, a string of length 1),""" """and an integer rot. Your function should return a new string of length 1,""" """ the result of rotating char by rot number of places to the right.""" newchar = "" if char.isalpha(): position = alphabet_position(char) if position + rot <= 25: newposition = position + rot else: newposition = (position + rot) % 26 newchar = chr(newposition+65) if char.islower(): newchar = newchar.lower() else: newchar = newchar.upper() else: newchar = char return newchar def encrypt(text, rot): rot = rot newtext = "" for char in text: newchar = rotate_character(char, rot) newtext += newchar return newtext
true
9afee39db5f15d957c60df0a1c50213b73d888aa
ciccolini/Python
/Function.py
2,459
4.46875
4
#to create a function #by using def keyword def my_function(): print("Hello from a function") #to call a function my_function() #to add as many parameters as possible def my_function(fsurname): print(fsurname + " " + "Name") my_function("Anthony") my_function("Romain") my_function("MP") #improvement def my_function(fsurname, fname): print(fsurname + " " + fname) my_function("Anthony","Da Mota") my_function("Romain", "Alexandre") my_function("MP", "Ciccolini") #to set up a default parameter value def my_country(country = "France"): print("I am from " + country) my_country("UK") my_country("Spain") my_country() my_country("Singapore") #to let the function return a value def my_result(x): return 5 * x print(my_result(3)) print(my_result(4)) print(my_result(5)) #to create a recursion of a function #It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result #example 1 def tri_recursion(k): if k > 0 : result = k + tri_recursion(k - 1) print(result) else: result = 0 return result print("\nRecursion example result") tri_recursion(6) #example 2; find all final values from each node world = { "Africa": { "Waganda": 7000 }, "Europe": { "France": { "PACA": { "Nice": 1520 } } }, "America": { "United States": { "New York": 142 } } } def display_population(node): for key in node.keys(): next_value = node[key] if type(next_value) is dict: display_population(next_value) else: print(f"\n{next_value}") display_population(world) #example 3; sum from world def sum_population(node): result = 0 for key in node.keys(): next_value = node[key] if type(next_value) is dict: result += sum_population(next_value) else: return next_value return result print(sum_population(world)) #LAMBDA FUNCTION; small anonymous function with any number of arguments, but can only have one expression x = lambda a : a + 10 print(f"\n{x(5)}") x = lambda a, b : a * b print(x(4, 5)) x = lambda a, b, c : a + b + c print(x(1, 2, 3)) #to combine a function and a lambda function def my_func(n): return lambda a : a * n mydoubler = my_func(2) mytripler = my_func(3) print(mydoubler(6)) print(mytripler(6)) exit()
true
e09d88413f22afee9604ef82652ba6a367214362
idan0610/intro2cs-ex3
/decomposition.py
897
4.25
4
###################################################################### # FILE: decomposition.py # WRITER: Idan Refaeli, idan0610, 305681132 # EXERCISE: intro2cs ex3 2014-2015 # DESCRIPTION: # Find the number of goblets Gimli drank of each day ####################################################################### num_Of_Goblets = int(input("Insert composed number:")) num_Of_Days = 1 DECIMAL_BASE = 10 if num_Of_Goblets == 0: #Gimli has not drank nothing print("The number of goblets Gimli drank on day", num_Of_Days, "was",\ num_Of_Goblets) while num_Of_Goblets != 0: #Check whats the last digit and prints with the current day last_Digit = num_Of_Goblets % 10 print("The number of goblets Gimli drank on day", num_Of_Days, "was",\ last_Digit) #Change for next day and divide (integer) the number by 10 num_Of_Days += 1 num_Of_Goblets //= DECIMAL_BASE
true
625086292e7df6169fd0029150706ea71f67c7bc
Nermeen3/Python-Practice
/Merge Sort Recursion.py
1,444
4.40625
4
### Merge sort: works by dividing the array into halves and each half into another half ### until we're left with n arrays each holds one element from the original array ### then we go back up by comparing arrays and sorrting them as we go up ### time complexity is O(nlogn) ### Auxillary space is O(n) from random import randint def RandomGenerator(size): return [randint(0, 50) for x in range(size)] def Merge(array1, array2): #print(array1, array2) newArray = [] index1, index2 = 0, 0 for i in range(len(array1)+len(array2)): if index1 == len(array1): newArray.extend(array2[index2:]) break elif index2 == len(array2): newArray.extend(array1[index1:]) break elif array1[index1] < array2[index2]: newArray.append(array1[index1]) index1+= 1 else: newArray.append(array2[index2]) index2+= 1 #print(len(array1)+len(array2), len(newArray)) #print('merged array: ', newArray) return newArray def MergeSort(array): # Base Case when we reach last step of dividing the original array's elements if len(array) <= 1: return array # next is recusiveley divide the array into halves LArray, RArray = MergeSort(array[:int(len(array)/2)]), MergeSort(array[int(len(array)/2):]) #print(LArray, RArray) return Merge(LArray, RArray) print(MergeSort(RandomGenerator(14)))
true
761d028f12ce52d7b4893506879955c25c7037b0
ThushanthaSanju/Algorithm-Python
/BubbleSort.py
374
4.46875
4
array1 = [] for v in range(8): array1.append(int(input("Enter the number : "))) print(array1) def bubbleSort(array): n=len(array) for i in range (0,n): for j in range(n-1,i,-1): if array[j]<array[j-1]: array[j],array[j-1] = array[j-1],array[j] bubbleSort(array1) print("sorted array") print(array1)
false
cc35fdcb39ec8d8d70e9bbc4d325fadfecba12cb
thaynagome/teste_python_junior
/teste_1015.py
656
4.15625
4
#!/usr/bin/env python # -- coding: utf-8 -- #Importa a biblioteca para a raiz quadrada import math #Solicitará em uma linha a inserção dos valores em uma linha x1,y1 = input("Digite os valores de x1 e y1: ").split(" ") # Converte os valor para flutuantes x1 = float(x1) y1 = float(y1) #Solicitará em uma linha a inserção dos valores em uma linha x2,y2 = input("Digite os valores de x2 e y2: ").split(" ") # Converte os valor para flutuantes x2 = float(x2) y2 = float(y2) #Faz a conta necessária dist = math.sqrt(((x2-x1)**2)+((y2-y1)**2)) #Mostra para o usuário o resultado com duas casas decimais após a virgula print ("%.4f" %dist)
false
f46ab39b3d768e73922c1d09ec115c9e92c566b8
arriolac/Project-Euler
/problem19.py
1,318
4.25
4
def is_leap_year(year): return year % 4 == 0 and ((year % 400 == 0) or (year % 100 != 0)) def num_days_for_year(year): num_days_in_feb = (29 if is_leap_year(year) else 28) return (4 * 30) + (31 * 7) + num_days_in_feb def num_days_for_month(month, year): if month == 2: return (29 if is_leap_year(year) else 28) elif month == 4 or month == 6 or month == 9 or month == 11: return 30 else: return 31 def num_of_sundays_in_year(year, start_day): total = 0 for month in range(1, 12 + 1): if start_day == 0: total += 1 num_days = num_days_for_month(month, year) #print "Number of days for month {}: {}".format(month, num_days) start_day = (start_day + num_days) % 7 #print "Day for new month: {}".format(start_day) return total, start_day def main(): total_days_in_1900, current_day = num_of_sundays_in_year(1900, 1) print "Number of Sundays in first of month in 1900: {}".format(total_days_in_1900) total = 0 for year in range(1901, 2000 + 1): result = num_of_sundays_in_year(year, current_day) total += result[0] current_day = result[1] print "Number of Sundays in first of month from 1901 - 2000: {}".format(total) if __name__ == '__main__': main()
false
39351a74c9a0e7e20d2fd64e10982fdd2cd0611b
ospupegam/for-test
/Processing_DNA_in_file .py
570
4.28125
4
''' Processing DNA in a file The file input.txt contains a number of DNA sequences, one per line. Each sequence starts with the same 14 base pair fragment – a sequencing adapter that should have been removed. Write a program that will trim this adapter and write the cleaned sequences to a new file print the length of each sequence to the screen. ''' my_file=open(r"input.txt") f=my_file.read() lines=f.split("\n") seq_line=[] lenght_line=[] for line in lines: seq_line.append(line[15:]) lenght_line.append(len(line[15:])) print(seq_line) print(lenght_line)
true
566e05e99024a9a86095738523f5ad0522c41da1
DanglaGT/code_snippets
/pandas/operations_on_columns.py
303
4.15625
4
import pandas as pd # using a dictionary to create a pandas dataframe # the keys are the column names and the values are the data df = pd.DataFrame({ 'x': [1, 3, 5], 'y': [2, 4, 6]}) print(df) # adding column x and column y in newly created # column z df['z'] = df['x'] + df['y'] print(df)
true
c6dd52dc9c6f3ff0711c27cfe6acc4f4eaedffdd
jmccutchan/python_snippets
/generator.py
1,386
4.1875
4
#This example uses generator functions and yields a generator instead of returning a list #use 'yield' instead of 'return' - yield a generator instead of returning a list, this consumes less memory def index_words(text): if text: yield 0 for index, letter in enumerate(text): if letter == ' ': yield index + 1 ipsum = "is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book." it = index_words(ipsum) print(it) #returns a generator (iterator) object print(next(it)) #returns each consecutive iterable def index_file(handle): offset = 0 for line in handle: if line: yield offset for letter in line: offset += 1 if letter == ' ': yield offset address = """ Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all are created equal.""" with open('/tmp/address.txt', 'w') as f: f.write(address) with open('/tmp/address.txt') as f: it = index_file(f) print(next(it)) #returns the next index print(next(it)) #returns the next index print(list(it)) #returns everything in a list
true
01a3983ad06be499932f3b89cf27a63d49239c6a
FabianoBill/Estudos-em-Python
/Curso-em-video/115-exerciciospython/d103_ficha_jogador.py
444
4.34375
4
# Exercício Python 103: Faça um programa que tenha uma função chamada ficha(), que receba dois parâmetros opcionais: o nome de um jogador e quantos gols ele marcou. O programa deverá ser capaz de mostrar a ficha do jogador, mesmo que algum dado não tenha sido informado corretamente. def ficha(j="<desconhecido>", g=0): print(f"O jogador {j} fez {g} gols.") j = input("Nome: ") g = int(input("Nº de gols: ")) print(ficha(j, g))
false
5d25b7f11594efecde8c32383658f942ce0b8f37
FabianoBill/Estudos-em-Python
/Exercicios/Contagem-caracteres-dicionario.py
1,370
4.125
4
def contar_caracteres(s): """Função que conta os caracteres de uma string Ex: >>> contar_caracteres('banana') {'b': 1, 'a': 3, 'n': 2} :param s: string a ser contada """ resultado = {} for caracter in s: # contagem = resultado.get(caracter, 0) # contagem += 1 # resultado[caracter] = contagem resultado[caracter] = resultado.get(caracter, 0) + 1 return resultado # digitando main o python já sugere --> if __name__ == '__main__': if __name__ == '__main__': print(contar_caracteres('banana')) # def contar_caracteres(s): # """Função que conta os caracteres de uma string # Ex: # >>> contar_caracteres('banana') # {'a': 3, 'b': 1, 'n': 2} # # :param s: string a ser contada # """ # caracteres_ordenados = sorted(s) # caracter_anterior = caracteres_ordenados[0] # cont = 1 # resultado = {} # for caracter in caracteres_ordenados[1:]: # if caracter == caracter_anterior: # cont += 1 # else: # resultado[caracter_anterior] = cont # caracter_anterior = caracter # cont = 1 # resultado[caracter_anterior] = cont # return resultado # # # # digitando main o python já sugere --> if __name__ == '__main__': # if __name__ == '__main__': # print(contar_caracteres('banana'))
false
bd190ff7638072ae4befb62e0c73c880d61bb371
FabianoBill/Estudos-em-Python
/Curso-em-video/115-exerciciospython/d073_times.py
576
4.21875
4
# Exercício Python 73: Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de Futebol, na ordem de colocação. Depois mostre: a) Os 5 primeiros times.b) Os últimos 4 colocados.c) Times em ordem alfabética.d) Em que posição está o time da Chapecoense. times = ("a", "e", "i", "o", "u", "b", "c", "d", "f", "g") print("Os 5 primeiros colocados são: ", times[:5]) print("Os 4 últimos colocados são: ", times[-4:]) print("Times em ordem alfabética: ", sorted(times)) print(f"O time c está na {times.index('c') + 1}ª posição.")
false
42fd336b56a83f68c5d05f22818c28d39b67f195
FabianoBill/Estudos-em-Python
/Curso-em-video/115-exerciciospython/d095_futebol2.py
1,561
4.125
4
# Exercício Python 093: Crie um programa que gerencie o aproveitamento de um jogador de futebol. O programa vai ler o nome do jogador e quantas partidas ele jogou. Depois vai ler a quantidade de gols feitos em cada partida. No final, tudo isso será guardado em um dicionário, incluindo o total de gols feitos durante o campeonato. # Exercício Python 095: Aprimore o desafio 93 para que ele funcione com vários jogadores, incluindo um sistema de visualização de detalhes do aproveitamento de cada jogador. jog = {} time = [] while True: jog['nome'] = input("Nome: ") jog['partidas'] = int(input("Partidas jogadas: ")) gpart = [] for p in range(0, jog['partidas']): gpart.append(int(input(f"Gols na {p + 1}ª partida: "))) jog['gols'] = gpart jog['total'] = sum(gpart) time.append(jog.copy()) continua = input("Deseja continuar? [S/N] ").strip()[0] if continua in "Nn": break if continua not in "Ss": input("Digite apenas S ou N").strip()[0] print(time) print("-=" * 30) for k in jog.keys(): print(f'{k:^10}', end="") print() print("-=" * 30) for c , d in enumerate(time): print(f"{c}", end="") for v in d.values(): print(f"{str(v):^10}", end="") print() print("-=" * 30) while True: j = int(input("Mostrar detalhes de qual jogador? (999 parar) ")) if j == 999: break print(f"Gols feitos em cada partida por {time[j]['nome']}.") for i, g in enumerate(time[j]['gols']): print(f"No {i + 1}º jogo fez {g} gols.") print("Obrigado. Fim.")
false
b5a4675e7b252d58079c48e760ebfe623a8cbecd
FabianoBill/Estudos-em-Python
/Curso-em-video/115-exerciciospython/d099_maior.py
477
4.25
4
# Exercício Python 099: Faça um programa que tenha uma função chamada maior(), que receba vários parâmetros com valores inteiros. Seu programa tem que analisar todos os valores e dizer qual deles é o maior. def maior(* prmt): c = max = 0 for valor in prmt: if c == 0: max = valor else: if valor > max: max = valor c += 1 print(max) maior(2, 5, 8, 3, 9) maior(1, 3, 2, 7) print(max(3, 2, 5))
false
58bd82ac0a4eb5331736225afcb3e1ec9865f0a7
Stheycee/Exerc-cio
/stheyce_q2_tuplas.py
1,325
4.625
5
''' é comum no jogo de dominó ter uma rodada antes de iniciar o jogo na qual todos os integrantes escolhem apenas uma pedra e quem retirar o maior valor inicia o jogo, outra situação é quando o jogo fecha e inicia a contagem de pontos, aquele que tiver a menor pontuação vence. simule um jogo de dominó com quatro jogadore onde deve entrar na tupla os valores para iniciar e outra para a contagem de pontos no final deve mostrar a maior e menor peça, os valor ordenados. ''' n = (int(input('Digite o número escolhido para iniciar a partida: ')), int(input('Digite o número escolhido: ')), int(input('Digite o número escolhido: ')), int(input('Digite o número escolhido: '))) print(f'Os números escolhidos foram: {n}') print('') print('Os números ordenados: ') print(sorted(n)) print('') print('o maior número foi:',max(n)) print('') b = (int(input('Digite o número escolhido para a contagem de pontos: ')), int(input('Digite o número escolhido para a contagem de pontos: ')), int(input('Digite o número escolhido para a contagem de pontos: ')), int(input('Digite o número escolhido para a contagem de pontos: '))) print(f'Os números escolhidos foram: {b}') print('') print('Os números ordenados: ') print(sorted(b)) print('') print('o menor número foi:',min(b))
false
5b4d8c87bdac439f9129969434726c5f1d988172
jeffalstott/powerlaw
/testing/walkobj.py
2,106
4.21875
4
"""walkobj - object walker module Functions for walking the tree of an object Usage: Recursively print values of slots in a class instance obj: walk(obj, print) Recursively print values of all slots in a list of classes: walk([obj1, obj2, ...], print) Convert an object into a typed tree typedtree(obj) A typed tree is a (recursive) list of the items in an object, prefixed by the type of the object """ from collections.abc import Iterable BASE_TYPES = [str, int, float, bool, type(None)] def atom(obj): """Return true if object is a known atomic type. obj : Object to identify Known atomic types are strings, ints, floats, bools & type(None). """ return type(obj) in BASE_TYPES def walk(obj, fun): """Recursively walk object tree, applying a function to each leaf. obj : Object to walk fun : function to apply A leaf is an atom (str, int, float, bool or None), or something that is not a dictionary, a class instance or an iterable object. """ if atom(obj): fun(obj) elif isinstance(obj, dict): for keyobj in obj.items(): walk(keyobj, fun) elif isinstance(obj, Iterable): for item in obj: walk(item, fun) elif '__dict__' in dir(obj): walk(obj.__dict__, fun) else: fun(obj) def typedtree(obj): """Convert object to a typed nested list. obj : Object to walk Returns the object if it's an atom or unrecognized. If it's a class, return the list [type(obj)] + nested list of the object's slots (i.e., typedtree(obj.__dict__). If it's iterable, return the list [type(obj)] + nested list of items in list. Otherwise, it's unrecognized and just returned as if it's an atom. """ if atom(obj): return obj if isinstance(obj, dict): return (dict, [typedtree(obj) for obj in obj.items()]) if isinstance(obj, Iterable): return (type(obj), [typedtree(obj) for obj in obj]) if '__dict__' in dir(obj): return (type(obj), typedtree(obj.__dict__)) return obj
true
dea24af2de89866d3a77fce75b268f6be6306b8d
AntGrimm/180bytwo_home_assignment
/app.py
1,881
4.21875
4
# Functions are commented out at the bottom, remove comment to run each function import itertools # Removing a character in a loop and checking word against dictionary def check_super_word(check_str, dictionary): for i in range(0, len(check_str)): # Removing each character in loop new_str = ''.join([check_str[j] for j in range(len(check_str)) if j != i]) if new_str in dictionary: # Checking if each iteration of word is in the dictionary return True # print(check_str + " is a super word") else: continue # Combining integers and interlacing strings def combine_integers(a, b): c = ''.join(map(''.join, itertools.zip_longest(str(a), str(b), fillvalue=""))) return int(c) # Python program for implementation of MergeSort def merge_sort(arr): if len(arr) > 1: mid = len(arr) // 2 # Finding the mid of the array left = arr[:mid] # Dividing the array elements right = arr[mid:] # into 2 halves merge_sort(left) # Sorting the first half merge_sort(right) # Sorting the second half i = j = k = 0 # Copy data to temp arrays left[] and right[] 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 print("count") k += 1 # Checking if any element was left while i < len(left): arr[k] = left[i] i += 1 k += 1 while j < len(right): arr[k] = right[j] j += 1 k += 1 return arr # Remove below comment to run function print(check_super_word("print", ["pint", "pit", "hat"])) # print(combine_integers(123, 456)) # print(merge_sort([1, 2, 6, 5, 4, 7, 8]))
true
41d2b009044c0725c83d588cc15700d4775a48a6
KKEIO1000/Sorting-Algorithms
/Bubble Sort (Optimized Ω(n)).py
707
4.3125
4
import random def bubble_sort(lst): """Function to sort a list via optimized bubble sort, O(n^2), Ω(n) if the list is already sorted""" #Sets a flag so if no swap happened, the loop exits sort = True #Main body of the iterative loop while sort: sort = False for i in range(len(lst)-1): if lst[i] > lst[i+1]: lst[i], lst[i+1] = lst[i+1], lst[i] sort = True return lst #Test the algorithm using a randomly generated list of 10 numbers lst = list(random.randint(0,1000) for i in range(10)) print("Original: ", lst) print("Python's sort function: ", sorted(lst)) print("Bubble sort: ", bubble_sort(lst))
true
a55e7da40409b9160df98169b4bf7ac36eb7735b
sajay/learnbycoding
/learnpy/capital_city_loop.py
1,449
4.5625
5
#Review your state capitals along with dictionaries and while loops! #First, finish filling out the following dictionary with the remaining states and their #associated capitals in a file called capitals.py. Or you can grab the finished file directly from the exercises folder in the course repository #on Github. #capitals_dict = { #'Alabama': 'Montgomery', #'Alaska': 'Juneau', #'Arizona': 'Phoenix', #'Arkansas': 'Little Rock', #'California': 'Sacramento', #'Colorado': 'Denver', #'Connecticut': 'Hartford', #'Delaware': 'Dover', #'Florida': 'Tallahassee', #'Georgia': 'Atlanta', #} #Next, write a script that imports the capitals_dict variable along with the 'random' #package: #from capitals import capitals_dict #import random #This script should use a while loop to iterate through the dictionary and grab a random #state and capital, assigning each to a variable. The user is then asked what the capital of #the randomly picked state is. The loop continues forever, asking the user what the #capital is, unless the user either answers correctly or types "exit".#If the user answers correctly, "Correct" is displayed after the loop ends. #However, if the user exits without guessing correctly, the answer is displayed along with "Goodbye." #NOTE: Make sure the user is not punished for case sensitivity. In other words, a guess of "Denver" is the same as "denver". The same rings true #for exiting - "EXIT" and "Exit" are the same as "exit".
true
3fe028c17fbe2be2504d6caee35ada09f9c008d2
sajay/learnbycoding
/dailycodeproblems/car-cdr.py
944
4.34375
4
#This problem was asked by Jane Street. #cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. #For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. # Given this implementation of cons: # def cons(a, b): # def pair(f): # return f(a, b) # return pair # Implement car and cdr. #This is a really cool example of using closures to store data. # We must look at the signature type of cons to retrieve its first and last elements. # cons takes in a and b, and returns a new anonymous function, which itself takes in f, # and calls f with a and b. # So the input to car and cdr is that anonymous function, which is pair. # To get a and b back, we must feed it yet another function, one that takes in two parameters # and returns the first (if car) or last (if cdr) one. def car(pair): return pair(lambda a, b: a) def cdr(pair): return pair(lambda a, b: b)
true
5196bf1716062f91599b7fd2456156aaa5ef3e8f
Davidsaemund/TileTraveller_Assign_8
/TileTraveller.py
2,521
4.15625
4
# Assignment 8 # Tile Traveler # Program that moves NORTH, SOUTH, WEST and EAST in a 3v3 tile plan. #Function that gets your current loc and tells you what options you have def tile_traveller(x,y): if (x == 1 and y == 1) or (x == 2 and y == 1): print("You can travel: (N)orth.") elif (x == 1 and y == 2 ) : print("You can travel: (N)orth or (E)ast or (S)outh.") elif (x == 2 and y == 2) or (x == 3 and y == 3): print("You can travel: (S)outh or (W)est.") elif (x == 1 and y == 3 ) : print("You can travel: (E)ast or (S)outh.") elif (x == 2 and y == 3 ) : print("You can travel: (E)ast or (W)est.") elif (x == 3 and y == 2 ) : print("You can travel: (N)orth or (S)outh.") return x,y #Function that gets current loc and wanted movement returns the resulting position def wanted_movement(x,y,movement) : if (x == 1 and y == 1) or (x == 2 and y == 1): if movement == 'n' or movement == 'N' : y = y + 1 return x , y elif (x == 1 and y == 2 ) : if movement == 'n' or movement == 'N' : return x , y + 1 if movement == 's' or movement == 'S' : return x , y - 1 if movement == 'e' or movement == 'E' : return x + 1 , y elif (x == 2 and y == 2) or (x == 3 and y == 3): if movement == 'w' or movement == 'W' : return x - 1 , y if movement == 's' or movement == 'S' : return x , y - 1 elif (x == 1 and y == 3 ) : if movement == 's' or movement == 'S' : return x , y - 1 if movement == 'e' or movement == 'E' : return x + 1 , y elif (x == 2 and y == 3 ) : if movement == 'e' or movement == 'E' : return x + 1 , y if movement == 'w' or movement == 'W' : return x - 1 , y elif (x == 3 and y == 2 ) : if movement == 's' or movement == 'S' : return x , y - 1 if movement == 'n' or movement == 'N' : return x , y + 1 print("Not a valid direction!") return x,y # Main Program x = 1 y = 1 while x != 3 or y != 1 : x,y = tile_traveller(x,y) movement_str = input("Direction: ") x,y = wanted_movement(x,y, movement_str) print("Victory!") # Starts in 1,1 # while not winnging # ask function where we are and get directions # Tell program where you want to go # function that performs action if possible and return the resulting position
false
1030840b3ca5e98c70aa8d878c41a3bffed72114
niqaabi01/Intro_python
/Week2/Perimter2.py
577
4.1875
4
width1 = float(input("enter width one : ")) height1 =float(input("enter height one : ")) width2 = float(input("enter width two : ")) height2 = float(input("enter height two :")) cost_mp =float(input(" enter price per meter :")) height = 2 * float(height1) width = float(width1) + (width2) def multiply(width): result = 2 for index in range(1): result = result * width return result total = height + multiply(width) result = total * cost_mp print("The total amount fencing per meter : " + str(total)) print(" The total cost of fencing R" + str(result))
true
2551c03e063d0cd16da6e3e0ee2881f5279faaae
ewang14/hello-world
/pizza.py
2,399
4.1875
4
# pizzaQuiz2 # tell the user what's going on print ("What Type of Pizza Are You?") print (" ") print ("Take our quiz to find out what type of pizza you are!") print (" ") # player information on the player player = { "name": "unknown", "superpower": "unknown", "faveColor" : "unknown", "drink" : "unknown" } # name = raw_input("What is your name? ") player ["name"] = name # the chosen superpower will be the players superpower # pepperoniType = super strength/invisitibility and red/yellow # cheeseType = super strength/invisibility and blue/orange # anchovyType = flying/telekinesis and water/tea # marinaraType = flying/telekinesis and wine/coffee print (" ") # spacing superpower = raw_input("Hi, " + player["name"] + "! Choose one superpower: super strength, invisibility, flying, telekinesis: ") player ["superpower"] = superpower # if the player chooses super strength or invisibility we will give them a color prompt. Red/yellow is Pepperoni. Blue/orange is Cheese. if (player["superpower"] == "super strength") or (player["superpower"] == "invisibility"): print (" ") faveColor = raw_input("Woaaaaah, interesting choice. Now that you have " + superpower + "," "which of the following colors speaks to you the most: red, blue, yellow, orange: ") player ["faveColor"] = faveColor if (player["faveColor"] == "red") or (player["faveColor"] == "yellow"): print(" ") print("Everyone loves you, except ve getarians. " + name + ", you are a Pepperoni Pizza!") elif (player["faveColor"] == "blue") or (player["faveColor"] == "orange"): print(" ") print("Some might say you're a little vanilla, but tell those haters, you are timeless - you're a Cheese Pizza!") # if the player chooses flying or telekinesis we will give them a drink prompt else: drink = raw_input("Cool! Now that you have " + superpower + "choose one type of drink: water, wine, coffee, tea. ") player ["drink"] = drink # water or tea is anchovy. wine or coffee is marinara. if (drink == "water") or (drink == "tea"): print(" ") print("Not many understand you, but when they do, they LOVE you. You are an Anchovy Pizza!!") else: print(" ") print(name + ", no need to be cheesy here. You are who you are, you're a Marinara Pizza!!") # if (player["superpower"] == pepperoniType[0]) and (player["faveColor"] == pepperoniType[1]): # print "You are Pepperoni Pizza"
true
4058a599a844f012a9a8367d8cce7c3fbad2cdea
StephanieTabosa/estudo-python
/aula07desafio008.py
520
4.21875
4
# Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros metros = float(input('Digite um valor em metros: ')) centimetros = metros*100 milimetros = metros*1000 dm = metros*10 dam = metros/10 hm = metros/100 km = metros/1000 print('\n O valor {} está em metros.\n Sua conversão em centímetros fica {:.0f}cm, e em milímetros fica {:.0f}mm!'.format(metros,centimetros,milimetros)) print(' Também possui {:.0f} dm, {} dam, {} hm e {} km.'.format(dm,dam,hm,km))
false
fa1e91ecda206b22c8e5f78feda5caf988b0fe5e
StephanieTabosa/estudo-python
/aula10desafio033.py
429
4.125
4
# Faça um programa que leia três números e mostre qual é o maior e qual é o menor. import math numero = float(input('Digite o primeiro número: ')) numero2 = float(input('Digite o segundo número: ')) numero3 = float(input('Digite o terceiro número: ')) lista = [numero, numero2, numero3] print('O MENOR número é {}.'.format(min(lista))) print('O MAIOR número é {}.'.format(max(lista)))
false
735db79beeb3cb7c513e97a79f5aa846b15d46d2
rspurlock/SP_Online_PY210
/students/rspurlock/lesson4/dict_lab.py
2,290
4.5625
5
#!/usr/bin/env python3 def printDictionary(dictionary): """ Function to display a dictionary in a nice readable fashion Positional Parameters :param dictionary: Dictionary to print key/value pairs for """ # Loop thru all the dictionary items (key/value pairs) printing them for key, value in dictionary.items(): print(f'{key} = {value}') # Print a blank line for readability print() # Dictionaries 1 print('Dictionaries 1') dictionary = {'name' : 'Chris', 'city' : 'Seattle', 'cake' : 'Chocolate'} printDictionary(dictionary) del dictionary['cake'] printDictionary(dictionary) dictionary['fruit'] = 'Mango' printDictionary(dictionary) print('Keys') for key in dictionary.keys(): print(f'{key}') print() print('Values') for value in dictionary.values(): print(f'{value}') print() # Dictionaries 2 print('Dictionaries 2') # Create and print the original dictionary dictionary = {'name' : 'Chris', 'city' : 'Seattle', 'cake' : 'Chocolate'} printDictionary(dictionary) # Copy original dictionary and update values to number of letter t's newDictionary = dictionary.copy() for key, value in newDictionary.items(): newDictionary[key] = value.lower().count('t') # Print the updated dictionary printDictionary(newDictionary) # Sets 1 print('Sets 1') # Create the 'empty' sets to build s2 = set() s3 = set() s4 = set() # Loop through the number 0 - 20 building the sets for n in range(0, 21): if ((n % 2) == 0): s2.add(n) if ((n % 3) == 0): s3.add(n) if ((n % 4) == 0): s4.add(n) # Print all of the created sets print('s2 = ' + str(s2)) print('s3 = ' + str(s3)) print('s4 = ' + str(s4)) print() # Check for subsets print('Is s3 a subset of s2? ' + str(s3.issubset(s2))) print('Is s4 a subset of s2? ' + str(s4.issubset(s2))) print() # Sets 2 print('Sets 2') # Create the python and marathon sets pythonSet = set('Python') marathonSet = frozenset('marathon') # Display these two sets print('Python set - ' + str(pythonSet)) print('marathon set - ' + str(marathonSet)) print() # Display the union and intersection of these sets print("Python union marathon is " + str(pythonSet.union(marathonSet))) print("Python intersect marathon is " + str(pythonSet.intersection(marathonSet))) print()
true
0ff5d9ba153ea7e0cf4b5e246199f6ee4a825a76
danilocecci/CEV-Python3
/ex063.py
226
4.125
4
sequence = int(input('Digite a quantidade de números fibonacci que deseja: ')) numbers = [0, 1] counter = 2 while counter < sequence: numbers.append(numbers[counter-1]+numbers[counter-2]) counter += 1 print(numbers)
false
63af36128dff39515a0ae170f713e96b44d26e9a
danilocecci/CEV-Python3
/ex005.py
258
4.21875
4
print('Vamos verificar o antecessor e o sucessor de um número!') numero = int(input('Para isso, preciso que digite um número: ')) print('O antecessor de "{}" é {}!'.format(numero, (numero-1))) print('O sucessor de "{}" é {}!'.format(numero, (numero+1)))
false
50c346bdbdbd12de77a6f3c92e0928e027440cf9
emurph1/ENGR-102-Labs
/CFUs/CFU3.py
1,304
4.125
4
# By submitting this assignment, I agree to the following: # “Aggies do not lie, cheat, or steal, or tolerate those who do” # “I have not given or received any unauthorized aid on this assignment” # Emily Murphy # ENGR 102-552 # CFU 3 # 10/03/2018 homework = int(input('Enter homework grade: ')) # user inputs homework grade exam = int(input('Enter exam grade: ')) # user inputs exam score outside = input('Enter Yes if you did an outside project and No if you didn\'t: ') # user inputs outside project numGrade = 0 # starting numGrade numGrade += exam * 0.6 # adding homework score to overall with the weight of exam (60%) numGrade += homework * 0.4 # adding homework score to overall with the weight of homework (40%) # conditional to add 5 extra points with outside project if outside == 'Yes': numGrade += 5 # Conditionals that find letter grade and print the letter grade if numGrade >= 90 and outside == 'Yes': print('You get an A') elif numGrade >= 90 and outside == 'No': print('You would\'ve gotten an A, but did not do the outside project. You get a B.') elif 80 <= numGrade < 90: print('You get an B') elif 70 <= numGrade < 80: print('You get an C') elif 60 <= numGrade < 70: print('You get an D') else: print('You get an F')
true
65699bd59c477e72c32d3b57072b08750c07724b
RyanRosvall/program-arcade-games
/Lab 01 - Calculator/lab_01_part_a.py
238
4.1875
4
#!/usr/bin/env python3 #Fahrenheit to Celsius conversion #Ryan Rosvall #11/1/17 temperature = int(input("Enter temperature in Fahrenheit: ")) conversion = ((temperature - int(32)) * 5/9) print('The temperature in Celsius: ' + str(conversion))
false
bc2cebe6671e920cb68096f6222ff5a24846a32e
greenfox-zerda-lasers/hvaradi
/week-04/day-4/trial.py
380
4.25
4
# def factorial(number): # product=1 # for i in range(number): # product=product * (i+1) # return product # # print(factorial(3)) def factorial(number): if number <= 1: return 1 else: return number * factorial(number-1) print(factorial(3)) # product = 1 # for i in range (number): # product = product * (i+1) # # print(product)
true
76459e26f6290338ca907294bc7d5daf660e2491
greenfox-zerda-lasers/hvaradi
/week-05/day-1/helga_work.py
834
4.1875
4
#Write a function, that takes two strings and returns a boolean value based on #if the two strings are Anagramms or not. from collections import Counter word1="hu la" word2="hoop" def anagramm(word1, word2): letters1=[] letters2=[] for i in range(len(word1)): letters1.append(word1.lower()[i]) letters1.sort() for i in range(len(word2)): letters2.append(word2.lower()[i]) letters2.sort() if " " in letters1: letters1.remove(" ") if " " in letters2: letters2.remove(" ") if letters1 == letters2: return True else: return False anagramm(word1, word2) def count_letters(string): result = list(string.lower()) if " " in result: result.remove(" ") result = Counter(result) return result print(count_letters("babbala"))
true
19e59384dc5e93fe24c6be1d883c441b6de1a7e7
greenfox-zerda-lasers/hvaradi
/week-03/day-3/circle_area_circumference.py
618
4.3125
4
# Create a `Circle` class that takes it's radius as cinstructor parameter # It should have a `get_circumference` method that returns it's circumference # It should have a `get_area` method that returns it's area class Circle(): radius = 0 def __init__(self, radius, pi): self.radius = radius self.pi = 3.14 def get_circumference(self): return self.radius * 2 * self.pi def get_area(self): return self.pi * self.radius ** 2 HelgaCircle = Circle(100, 3.14) print("The circumference of the circle:",(HelgaCircle.get_circumference())) print("The area of the circle:",(HelgaCircle.get_area()))
true
b881fe869bdf97f6da563415c2b3a7bd7da23434
Amar-Ag/PythonAssignment
/Functions3.py
1,623
4.8125
5
""" 11) Python program to create a lambda function that adds 15 to a given number passed in as an argument, also create a lambda function that multiplies argument x with argument y and print the result. """ fifteen = lambda num: num + 15 multiplyTwo = lambda num1, num2: num1 * num2 print(fifteen(15)) print(multiplyTwo(15, 15)) """ 12) Python program to create a function that takes one argument, and that argument will be multiplied with an unknown given number. """ def unknownMultiply(num): return lambda random: random * num result = unknownMultiply(2) print("Calling the function with random number:", result(12)) """ 13) Python program to sort a list of tuples using Lambda. """ tupleList = [(0, 'c'), (1, 'a'), (2, "b")] print("Tuple before sorting:", tupleList) tupleList.sort(key=lambda x: x[1]) print("Tuple after sorting:", tupleList) """ 14) Python program to sort a list of dictionaries using Lambda """ sampleDict = [{'number': '0', 'spelling': 'zero'}, {'number': '2', 'spelling': 'two'}, {'number': '1', 'spelling': 'one'}] print("Existing list:", sampleDict) sampleDict.sort(key=lambda x: x['spelling']) print("After sorting:", sampleDict) """ 15) Python program to filter a list of integers using Lambda """ sampleList = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5] print("Original List:", sampleList) positiveList = list(filter(lambda x: x > 0, sampleList)) negativeList = list(filter(lambda x: x < 0, sampleList)) neutralList = list(filter(lambda x: x == 0, sampleList)) print("Positive List", positiveList) print("Negative List", negativeList) print("Neutral List", neutralList)
true
c1c57774c47113e39d38d942341708aff20135af
TomMarquez/Evolutionary-Programming
/Final_Project/Main.py
1,391
4.125
4
from Population import Population from Window import Window import tkinter as tk from tkinter import * import random import time import random import matplotlib.pyplot as plt def main(): pop_size = 100 iteration = 10000 max_fit = 0 top_fit = 0 average_fit = 0 pop = Population(pop_size, 10, 10) pop.init_pop() road = 1 iterations = [] top_fits = [] max_fits = [] for i in range(iteration): iterations.append(i) obstacle = -1 while(not pop.done()): if random.randint(0, 10) == 0: obstacle = random.randint(0, 9) road_move = random.randint(0,2) -1 pop.make_move(road, obstacle, road_move) #road = road + road_move pop.rank_fitness() fit_sum = 0 top_fit = pop.fit[0][1] if max_fit < top_fit: max_fit = top_fit for j in range(pop_size): fit_sum += pop.fit[j][1] average_fit = fit_sum / pop_size top_fits.append(top_fit) max_fits.append(max_fit) pop.breed(pop_size, 95, 2) print("Iteration: " + str(i)) print("Max Fitness: " + str(max_fit)) print("Top Fitness: " + str(top_fit)) print("Average Fitness: " + str(average_fit)) plt.plot(top_fits, label= 'Top Fit') plt.plot(max_fits, label = 'Max Fit') plt.title("Fitness vs Time(Population: 100)") plt.ylabel('Fitness') plt.xlabel('Iterations') plt.legend(); plt.show() if __name__=='__main__': main()
true
490b325247e485c5f28db97b58f4b255be2c04b2
RomanKV-1/lesson1
/hard1.py
370
4.125
4
#Пользователь вводит число определите, является ли данное число простым. Делится только на себя и на единицу n = int(input('Введите число')) d = 2 while n % d != 0: d += 1 if d == n: print('Число простое') else: print('Число составное')
false
f15086d8e41223760acc5830fe0051e5b6edaa75
chay360/learning-python
/ex3.py
519
4.3125
4
#.............Numbers and Math..........# print("I will count my chickens:") print("Hens", 25 + 30/6) print("Roosters",100 -25 * 3 % 4) print("Now i will count eggs:") print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) print("Is it true that 2 + 3 < 5 - 7?") print(2 + 3 < 5 - 7) print("What is 3 + 2?", 3 + 2) print("What is 5 - 7?", 5 - 7) print("Oh that's why it's FALSE.") print("How about some more.") print("Is it greater ", 5 > -2) print("Is it greater or equal?", 5 >= -2) print("Is it less or equal?", 5 <= -2)
true
dbf2ad366c7b4cdb31587c9f352a24b1f9e41252
MLGNateDog/untitledPycharmProject
/Comparison Operators.py
222
4.34375
4
# Here are the different types of Comparison Operators # > Greater than # >= Greater than or equal to # < Less than # <= Less than or equal to # == equal to # != not equal to # Example of use x = 3 != 2 print(x)
true
b9f5a15e8e0af0c669f2b4f1623b0927fa2a1375
KnowledgeMavens/Science-Tech
/Pandas9-30-17/DataFrames2.py
629
4.1875
4
'''https://pythonprogramming.net/basics-data-analysis-python-pandas-tutorial/ ''' import pandas as pd import matplotlib.pyplot as plt from matplotlib import style style.use('ggplot') style.use('fivethirtyeight') web_stats = {'Day':[1,2,3,4,5,6], 'Visitors':[43,34,65,56,29,76], 'Bounce Rate':[65,67,78,65,45,52]} df = pd.DataFrame(web_stats) #print(df.head()) #print(df.tail()) #print(df.tail(2)) #df.set_index('Day', inplace=True) #df = df.set_index('Day') #print(df['Visitors']) #print(df.Visitors) #df['Visitors'].plot() #plt.show() df.plot() plt.show() print(df[['Visitors','Bounce Rate']])
false
1f2a525543983b83a41d64c22b57ff3c2286541b
Momolunar/mypackage
/recsort/recursion.py
1,537
4.5
4
def sum_array(array): ''' Return sum of all items in array Args: array (array): list or array-like object containing numerical values. Returns: int: sum of items. Examples: >>> sum_array([1,2,3,4,5]) 15 ''' if len(array)==1: #if one item in list, return the item return array[len(array)-1] else: return array[len(array)-1]+sum_array(array[:len(array)-1]) def fibonacci(n): ''' Return nth term in fibonnaci sequence Args: n (int): positive integer n Returns: int: nth number in fibonacci sequence Examples: >>> fibonacci(14) 377 >>> fibonacci(7) 13 ''' if n==0: return 0 elif n==1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) def factorial(n): ''' Return factorial n Args: n (int): positive integer n Returns: int: nth factorial Examples: >>> factorial(5) 120 >>> factorial(10) 3628800 ''' if n <= 1: return 1 else: return n * factorial(n-1) def reverse(word): ''' Return word in reverse Args: word (str): string characters to be reversed Returns: str: reversed string Examples: >>> reverse('hello') 'olleh' >>> reverse('hello there') 'ereht olleh' ''' if len(word)==1: return(word) else: return word[-1] + reverse(word[:-1])
false
cb1d0c79331de9a64c5973e7db253ac42f783265
omogbolahan94/Budget-App
/main.py
2,024
4.3125
4
class Budget: """ Create a Budget class that can instantiate objects based on different budget categories(class instances) like food, clothing, and entertainment. These objects should allow for: 1. Depositing funds to each of the categories 2. Withdrawing funds from each category 3. Computing category balances 4. Transferring balance amounts between categories """ def __init__(self): self.amount = 200 def deposit(self, deposit_amount): """ Deposit money to budget :param deposit_amount: :return: None """ self.amount += deposit_amount def withdraw(self, withdraw_amount): """ Withdraw money from budget :param withdraw_amount: :return: None """ self.amount -= withdraw_amount def balance(self): """ To check budget balance :return: None """ return f"${self.amount}" def transfer(self, category_budget, amount): """ Transfer money from this this category to the category_budget class composition is a way of instantiating instant method parameter with another class object :param: category_budget, amount: :return: None """ self.amount -= amount category_budget.amount += amount print("\n") print("==" * 5, "Food Budget", "==" * 5) food = Budget() food.deposit(100) food.withdraw(50) print(f"Food balance after depositing $100 and Withdrawing $50 is: {food.balance()}") print("\n") print("==" * 5, "Clothing Budget", "==" * 5) clothing = Budget() food.transfer(clothing, 100) print(f"Clothing balance after receiving $100 from food budget balance: {clothing.balance()}") print(f"Food budget balance after transferring $100 to clothing budget balance: {food.balance()}") print("\n") print("==" * 5, "Entertainment Budget", "==" * 5) entertainment = Budget() print(f"Entertainment budget balance is untouched and it is: {entertainment.balance()}")
true
2440ddb0f0e2bc3873f11d0fe7bee65d50b55365
zhianwang/Python
/Regression/A02Module_G33419803.py
2,852
4.125
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 24 16:53:56 2016 @author: Zhian Wang GWID: G33419803 This program is define 3 function to to compute the regression coefficients for the data in an input csv file and plot the regression. """ import pandas as pd import matplotlib.pyplot as plt import numpy as np from sklearn import linear_model import argparse as ap from mpl_toolkits.mplot3d import * # Part1 Read data def fileInput(filename): """ Input = name of csv text file with comma separated numbers Output = nunmpy array """ myData = np.loadtxt(filename, delimiter = ',', dtype = float) return(myData) # Part 2 Compute the regression coefficients def regress(myData): """ Input = numpy array with three columns Column 1 is the dependent variable Column 2 and 3 are the independent variables Returns = a colum vector with the b coefficients and """ # In order to do multiple regression we need to add a column of 1s for x Data = np.array([np.concatenate((xi,[1])) for xi in myData]) x = Data[:,1:4] y = myData[:,0] # Create linear regression object linreg = linear_model.LinearRegression() # Train the model using the training sets linreg.fit(x,y) # We can view the regression coefficients B = np.concatenate(([linreg.intercept_], linreg.coef_), axis=0) b = B[0:3].reshape(3,1) from sklearn.metrics import r2_score pred = linreg.predict(x) r2 = r2_score(y,pred) return(b,r2) # Part 3 Plot the regression def myPlot(myData,b): """ Input = numpy array with three columns Column 1 is the dependent variable Column 2 and 3 are the independent variables and a cloumn vector with the b coefficients Reurns = Nothing Output = 3D plot of the actual data and the surface plot of the linear model """ import matplotlib.pyplot as plt import numpy as np from matplotlib import cm fig = plt.figure() ax = fig.gca(projection='3d') # to work in 3d plt.hold(True) x_max = max(myData[:,1]) y_max = max(myData[:,2]) b0 = float(b[0]) b1 = float(b[1]) b2 = float(b[2]) x_surf=np.linspace(0, x_max, 100) # generate a mesh y_surf=np.linspace(0, y_max, 100) x_surf, y_surf = np.meshgrid(x_surf, y_surf) z_surf = b0 + b1*x_surf +b2*y_surf # ex. function, which depends on x and y ax.plot_surface(x_surf, y_surf, z_surf, cmap=cm.hot, alpha=0.2); # plot a 3d surface plot x=myData[:,1] y=myData[:,2] z=myData[:,0] ax.scatter(x, y, z); # plot a 3d scatter plot ax.set_xlabel('x1') ax.set_ylabel('y2') ax.set_zlabel('y') plt.show()
true
0ff2439b7a7ced2ab34e6f91b0eb9fbe8f2122ce
Aqua5lad/CDs-Sample-Python-Code
/ListForRange.py
1,315
4.53125
5
# Colm Doherty 2018-02-21 # These are chunks of code I've written to test the List, For & Range functions # they are tested & proven to work! # here are some Lists, showing indexing & len(gth) (ie. number of items) Beatles = ['John', 'Paul', 'George', 'Ringo'] print ("the third Beatle was", Beatles[-2]) print ("the number of Beatles was:", len(Beatles)) homes = [55,13,19,58,7,21,86,190,2,49,219,55] print ("the numbers of homes I've lived in are:", homes) print ("the number of the third home I lived at was", homes[2]) for j in homes: print ("my home numbers, in sequence:", j) for i in range(2,219,11): print (i) for k in range(len(Beatles)): print (k, Beatles[k]) for s in Beatles: print (s) for s in homes: print (s) # script will go through the list and give the index position, then value, of each list in sequence l = 0 while l < len(homes): print (l, homes[l]) l = l + 1 # script will go through the list and, for the word it's currently at, will give the length of that word for m in Beatles: print(m,len(m)) # unlike using "while" - it cannot show the index position of each word, because as it loops through, the value of 'm' keeps changing # but there is a way to do it: for m in range(len(Beatles)): print(m, Beatles[m], len(Beatles[m]))
true
852c089e789383369c2b5f7a58efeacd1142aab6
mwenz27/python_onsite_2019
/week_01/05_lists/Exercise_01.py
568
4.15625
4
''' Take in 10 numbers from the user. Place the numbers in a list. Using the loop of your choice, calculate the sum of all of the numbers in the list as well as the average. Print the results. ''' num = []# create a list of numbers count = 0 try: print('Input numbers 10 times \n') for i in range(10): count += 1 x = int(input(f'Enter a number for number {count}: ')) num.append(x) except ValueError: print('there is no number in one input, please just enter just numbers') print('\nThe sum of numbers you entered is', sum(num))
true
437962b8b376a8148dd7848d5aeebc836f08a188
mwenz27/python_onsite_2019
/week_03/02_exception_handling/04_validate.py
562
4.59375
5
''' Create a script that asks a user to input an integer, checks for the validity of the input type, and displays a message depending on whether the input was an integer or not. The script should keep prompting the user until they enter an integer. ''' flag = True while flag: try: user_input = input('Enter a Number : ') user_input = float(user_input) except ValueError as err: print(err) print('Your still in the loop') else: print('congrats this is a number!, your out of the loop') flag = False
true
d2ba4e9f40f018006ef974c6a2a1624120ff5aff
mwenz27/python_onsite_2019
/week_01/04_strings/01_str_methods.py
938
4.40625
4
''' There are many string methods available to perform all sorts of tasks. Experiment with some of them to make sure you understand how they work. strip and replace are particularly useful. Python documentation uses a syntax that might be confusing. For example, in find(sub[, start[, end]]), the brackets indicate optional arguments. So sub is required, but start is optional, and if you include start, then end is optional. For this exercise, demonstrate the following string methods below: - strip - replace - find ''' sentence = ' This is a string to test bbb bb ' print((sentence.strip())) print((sentence.rstrip())) print(sentence.lstrip()) print(sentence.replace('s', 'SS')) print(len(sentence)) print('\tFind', sentence.find('b')) # find fines the first position on the argument to be seen print(sentence[27]) print('\tFind R', sentence.rfind('b')) # finds the first position on the right hand side print(sentence[32])
true
5b9ca8cd066392ae59f20e6e311ccefb363bebc0
mwenz27/python_onsite_2019
/week_01/04_strings/05_mixcase.py
840
4.40625
4
''' Write a script that takes a user inputted string and prints it out in the following three formats. - All letters capitalized. - All letters lower case. - All vowels lower case and all consonants upper case. ''' sentence = "If real is what you can feel, smell, taste and see, then real is simply electrical signals interpreted by your brain." vowels = ['a', 'e', 'i', 'o', 'u'] print(sentence.upper()) print(sentence.lower()) reconstructed_list = [] for letter in sentence.lower(): #print(letter, end='') if letter in vowels: # membership operator #print('passed through here') x = letter.lower() reconstructed_list.append(x) else: x = letter.upper() reconstructed_list.append(x) print('\n') #print(reconstructed_list) for i in reconstructed_list: print(i, end='')
true
1eeaf888fcb40efb3cce79e2143649c269314c97
JaredFlomen/LearningPython
/conditionals.py
732
4.25
4
a = -1 if a > 0: print('A is a positive number') elif a < 0: print('A is a negative number') else: print('A is zero') b = -1 print('B is positive') if b > 0 else print('B is negative') a = 3 if a > 0 and a % 2 == 0: print('A is an even and positive integer') elif a > 0 and a % 2 != 0: print('A is a positive integer') elif a == 0: print('A is zero') else: print('A is negative') #IF and OR user = 'Jared' access_level = 4 if user == 'admin' or access_level >= 4: print('Access granted!') else: print('Access denied!') age = int(input('How old are you: ')) if age > 16: print('You are old enough to drive') else: years_to_drive = 16 - age print(f'You need {years_to_drive} more years to learn to drive')
false
2e6f49c33c863d56f3270f10ffb4d2467b8074cd
standrewscollege2018/2021-year-11-classwork-RyanBanks1827
/List playground.py
569
4.28125
4
# For lists we use square brackets # Items must be split by comma # Items = ["Item1", "Item2"] # print(Items[0]) # To add something to the end of a list, use append() # Items.append("Dr Evil") # To add something directly into a list, use the Items.insert() or list.insert() # Items.insert(1, "Dr good") # Lists are mutable, they can be written to and deleted from # You can override a value of an item in the list, like this! # Items[1]= "Not any doctor here!" # print(Items) List = [["Tobias", 15]] Listoprint=List Listoprint.append(["Gavith", 15]) print(List)
true
838fdf5d8d24feaa89d08ef78f434be1247e5756
spohlson/Linked-Lists
/circular_linked.py
1,557
4.21875
4
""" Implement a circular linked list """ class Node(object): def __init__(self, data = None, next = None): self.data = data self.next = next def __str__(self): # Node data in string form return str(self.data) class CircleLinkedList(object): def __init__(self): self.head = None self.tail = None self.length = 0 def addNode(self, data): # Add node to end of linked list to point to the head node to create/connect circle node = Node(data) node.data = data node.next = self.head if self.head == None: self.head = node if self.tail != None: self.tail.next = node self.tail = node self.length += 1 def __str__(self): # String representation of circular linked list list_length = self.length node = self.head node_list = [str(node.data)] i = 1 # head node has already been added to the list while i < list_length: node = node.next node_list.append(str(node.data)) i += 1 return "->" + "->".join(node_list) + "->" ## Function to determine if a linked list has a loop ## def circularLink(linked_list): fast = linked_list.head slow = linked_list.head while fast != slow and fast != None: fast = fast.next.next slow = slow.next if fast == slow: return True else: return False """ Create the Circular Linked List """ def main(): circle_ll = CircleLinkedList() # Create empty circular linked list for x in range(1, 101): # Populate with 100 nodes circle_ll.addNode(x) print circle_ll # Display list as string if __name__ == '__main__': main()
true
56fcf653effc79c4b8371d94f5102088b7253dcb
ParkerCS/ch-tkinter-sdemirjian
/tkinter_8ball.py
2,493
4.59375
5
# MAGIC 8-BALL (25pts) # Create a tkinter app which acts as a "Magic 8-ball" fortune teller # The user asks a yes/no question that they want an answer to. # Then the user clicks a button, and your program displays # the "magic" random answer to their question. # Your program will have the following properties: # - Use an App class to create the tkinter app # - Add a proper title (appears in the window tab) # - Add a Label widget at the top to give the user instructions/intro. # - Add an Entry widget so the user can enter their question. # - Add a Button widget which will trigger the answer. # - Add a Label widget to display the answer (set to a initial value of "Your Fortune Here" or "--" or similar) # - Get your random answer message from a list of at least 10 possible strings. (e.g. ["Yes", "No", "Most Likely", "Definitely", etc...]) # - Add THREE or more other style modifications to make your app unique (font family, font size, color, padding, image, borders, justification, whatever you can find in tkinter library etc.) Make a comment at the top or bottom of your code to tell me your 3 things you did. (Just to help me out in checking your assignment) from tkinter import * from tkinter import font import random class App(): def __init__(self, master): #variables self.response = StringVar() self.list = ["Sure, why not", "Who cares?", "There can be no question.", "Definitely not", "Probably", "Try again later", "Only on Tuesdays", "Yes", "No", "It is certain", "That's the dumbest question I've ever been asked don't even think about asking that again or I swear to God I'll find where you live and make sure it never happens again."] #Labels self.intro_label = Label(master, text="Ask the 8-Ball a question!", bg="gold").grid(row=1, column=1, columnspan=4, sticky="e" + "w") self.response_label = Label(master, textvariable=self.response).grid(row=4, column=1, columnspan=4, sticky="e" + "w") #Entry: self.entry = Entry(master, text="Enter your question here.").grid(row=2, column=1, columnspan=4, sticky="e" + "w") #Buttons self.receive_fortune = Button(master, text="Receive Fortune", relief="raised", bg="blue", fg="yellow", command=lambda:self.response.set(self.list[random.randrange(len(self.list))])).grid(row=3, column=1, columnspan=4, sticky="e" + "w") if __name__ == "__main__": root = Tk() root.title("Magic 8-Ball") my_app = App(root) root.mainloop()
true
e39e0dcff94b1416043dd5124c81bf8186e95809
otisscott/1114-Stuff
/Lab 6/sqrprinter.py
269
4.125
4
inp = int(input("Enter a positive integer: ")) for rows in range(inp): row = "" for columns in range(inp): if columns < rows: row += "#" elif rows < columns: row += "$" else: row += "%" print(row)
true
ad608cd56dd0019920087c779e26f69e97d9882a
otisscott/1114-Stuff
/Lab 2/simplecalculator.py
490
4.25
4
firstInt = int(input("Please enter the first integer:")) secondInt = int((input("Please enter the second integer:"))) simpSum = str(firstInt + secondInt) simpDif = str(firstInt - secondInt) simpProd = str(firstInt * secondInt) simpQuot = str(firstInt // secondInt) simpRem = str(firstInt % secondInt) print("This sum is: " + simpSum + ", their difference is: " + simpDif + ", their product is: " + simpProd + ", their quotient is: " + simpQuot + ", their remainder is " + simpRem)
true
6f0cb2d42343987c32067f038502547114b46511
aleckramarczyk/project-euler
/smallestmultiple.py
839
4.125
4
#2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. # #What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? def main(): found = False num = 2520 #any number that is divisible by 1 through 20 will be a multiple of 2520, which is given to us in the problem #therefore, by checking only multiples of 2520 we save a massive amount of computing power compared to bruteforcing every number while found == False: print("Testing: " + str(num),end="\r") test = [num%n for n in range(11, 21)] if sum(test) == 0: print("\nThe smallest number that is divisible by 1-20 is: " + str(num)) found = True else: num = num + 2520 if __name__ == "__main__": main()
true
53bfe4d2a4a989302f4dae54d7fa4bb106da5d9d
anastasiiavoronina/python_itea2020
/py_itea2020_classes/lesson01/lesson01_task02.py
376
4.21875
4
dict_countries = { 'Ukraine': 'Kiev', 'Poland' : 'Warsaw', 'Great Britain' : 'London', 'France' : 'Paris', 'Belarus': 'Minsk' } list_countries = ['Spain', 'Poland', 'Ukraine', 'France', 'Italy', ' Norway', 'Greece'] for country in list_countries: if country in dict_countries: print(dict_countries[country] + ' is the capital of ' + country)
false
ee9d9d9256c74a84275211c616b8e4f1bf3b22b9
jeremy-wischusen/codingbat
/python/logicone/caught_speeding_test.py
819
4.1875
4
""" You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday -- on that day, your speed can be 5 higher in all cases. """ """ Solution """ def caught_speeding(speed, is_birthday): if is_birthday: u = 85 l = 65 else: u = 80 l = 60 if speed <= l: return 0 if speed > u: return 2 return 1 """ Tests """ def test_exercise(): assert caught_speeding(60, False) == 0 assert caught_speeding(65, False) == 1 assert caught_speeding(65, True) == 0 """ """
true
af1ef8b6837deec2de38278564e515bb854d92d8
sandeep-skb/Data-Structures
/Python/Trees/diameter.py
1,465
4.25
4
class Node: def __init__(self, val): self.data = val self.left = None self.right = None def height(node): if node == None: return 0 return (max(height(node.left), height(node.right))+1) def diameter(node): ''' The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two end nodes. The diagram below shows two trees each with diameter nine, the leaves that form the ends of a longest path are shaded (note that there is more than one path in each tree of length nine, but no path longer than nine nodes). https://www.geeksforgeeks.org/diameter-of-a-binary-tree/ ''' if node == None: return 0 lheight = height(node.left) rheight = height(node.right) ldiameter = diameter(node.left) rdiameter = diameter(node.right) #diameter will be the max of the following: #1. diameter through the root Node #2. diameter of the left subtree #3. diamter of the right subtree return(max((lheight+rheight+1), max(ldiameter, rdiameter))) def main(): t1 = Node(1) t1.left = Node(2) t1.right = Node(3) t1.left.left = Node(4) t1.left.right = Node(5) t1.right.left = Node(6) t1.right.right = Node(7) t1.right.right.right = Node(9) ''' 1 / \ 2 3 / \ / \ 4 5 6 7 \ 9 ''' print("Printing the diameter of tree: ") print(diameter(t1)) if __name__ == "__main__": main()
true
04b293e819b642b0755f35e10fd270879f0b5a32
sandeep-skb/Data-Structures
/Python/Linked-list/Singly-Linked-List/exchange_by_2.py
879
4.1875
4
def traverse(node): if node != None: print(node.data) traverse(node.next) def exchange(node): prev = Node(0) prev.next = node head = prev while((node != None) and (node.next != None)): prev.next = node.next temp = node.next.next node.next.next = node node.next = temp prev = node node = temp return head class Node: def __init__(self, data): self.data = data self.next = None def main(): e1 = Node(1) e2 = Node(2) e1.next = e2 e3 = Node(3) e2.next = e3 e4 = Node(4) e3.next = e4 e5 = Node(5) e4.next = e5 print("Original order of the linked list:") traverse(e1) print() node = exchange(e1) print("After reversing the order of the linked list:") traverse(node.next) if __name__ == "__main__": main()
true
4a04175c4580b1f1045f0697e6f2aaf43cabd164
JSisques/Python-Toolbox
/Seccion 03 - Estructuras de datos/01-Listas.py
2,418
4.59375
5
''' Una lista es una variable que contiene varios datos o variables de cualquier tipo Se puede crear una lista vacia utilizando [] Los elementos de las tienen posiciones, siendo la primera posicion la 0 y la ultima la longitud de la lista menos 1 ''' miLista = ["Javi", "Perro", 6, True, 7.5] listaVacia = [] ''' Para recorrer listas lo mejor es usar un bucle for aunque se puede utilizar cualquier tipo de bucle Para acceder a un valor de la lista ponemos el nombre de la variable seguido de dos [] y dentro la posicion del elemento a acceder lista[0] --> Sacamos el primer elemento de la lista ''' posicion2 = miLista[2] print("El elemento que hay en la posicion 2 es: " + str(posicion2)) #Ejemplo while print("Ejemplo bucle while") contador = 0 while contador < miLista.__len__(): print(miLista[contador]) contador += 1 #Ejemplo for print("Ejemplo bucle for") for elemento in miLista: print(elemento) ''' Se pueden usar varios metodos para trabajar con listas: 1. append() --> Añadir elementos a la lista 2. remove() --> Eliminar un elemento de la lista 3. sort() --> Ordenar una lista 4. index() --> Obtiene el indice del primer valor encontrado ''' pares = [] print("La lista antes del bucle: " + str(pares)) for i in range(0,10, 2): pares.append(i) print("La lista despues del bucle: " + str(pares)) pares.remove(4) print("La lista despues del borrado: " + str(pares)) valoresRepetidos = [0,2,4,4,6,8] print("La lista antes del borrado: " + str(valoresRepetidos)) valoresRepetidos.remove(4) print("La lista despues del borrado: " + str(valoresRepetidos)) listaDesordenada = [1,6,3,2,9,4,5,7,20] print("La lista antes del ordenado: " + str(listaDesordenada)) listaDesordenada.sort() print("La lista despues del ordenado: " + str(listaDesordenada)) listaIndex = ["Pepe", "Juan", "Elisa", "Kyle"] print("Pepe se encuentra en la posicion: " + str(listaIndex.index("Elisa"))) ''' Ejercicio lista de la compra. Hacer un menu que tenga las siguientes opciones: 1. Añadir elemento a la lista de la compra 2. Quitar un elemento de la lista de la compra 3. Mostrar todo lo que haya en la lista de la compra Requisitos: La lista de la compra cuando se muestre se mostrará ordenada alfabeticamente y al principio en una linea se mostrará la longitud de la misma Ejemplo: Tu lista de la compra tiene 3 productos los cuales son: Leche Galletas Mantequilla '''
false
a309f848cc6480e61dab0cc08c5cda2cac0b890e
JSisques/Python-Toolbox
/Seccion 04 - Funciones/01-Funciones.py
2,801
4.1875
4
''' Una funcion en programación es un tipo de sentencia que puede o no tener valores de entrada (parametros) y que puede devolver o no un valor de retorno La sintaxis de los metodos o funciones es la siguiente: nombreMetodo(parametros separados por comas) Ejemplos: 1. comprobarLetra(letra) 2. comprobarResultado(palabra) 3. pintarCoordenada(x, y) 3. pintarCubo(x, y, z) Existen dos tipos de funciones, las que devuelven un valor y las que no devuelven ningun valor Para indicar si una funcion devuelve un valor usaremos la palabra return seguido de la variable o valor que queramos devolver, si no queremos devolver nada no pondremos un return ''' miString = "Hola" miString.count("a") ''' Tomando como ejemplo la funcion o metodo count(valor) vemos que podemos diferenciar 2 partes: 1. Nombre de la funcion --> En este caso corresponde a count 2. Parametros --> Son todo lo que vaya entre () y en este caso es el valor que queremos buscar En este caso la funcion count() devuelve el numero de letras encontradas que coincidan con la letra del parametro ''' numeroLetras = miString.count("a") #print(numeroLetras) ''' Se pueden crear funciones personalizadas y programarlas para que hagan lo que uno quiera. Al definir una funcion podemos encontrar varias partes: 1. La palabra clave def --> Esta palabra indica a Python que se va a definir una funcion 2. El nombre de la función --> El nombre que le queremos dar a nuestra funcion 3. () --> Obligatorio ponerlos al definir y al llamar a una función 4. Valores dentro de los parentesis (Parametros) --> Opcionales, si tenemos valores dentro de los parentesis indicamos que la función necesita datos de entrada, pueden infinitos 5. : --> Obligatorio al final de la linea donde se define la función ''' def contarHastaDiez(): #Codigo lista = [] for i in range(1, 11): lista.append(i) return lista contarHastaDiez() #[1,2,3,4,5,6,7,8,9,10] variableLista = [1,2,3,4,5,6,7,8,9,10] variableFuncion = contarHastaDiez() variable3 = contarHastaDiez() variable4 = contarHastaDiez() print(str(variableLista)) print(str(variableFuncion)) print(str(variable3)) print(str(variable4)) def saludar(nombre): return "Hola " + str(nombre) saludo = saludar("Sara") print(saludo) def comprobacionEdad(edad): if edad >= 18: print("Puedes pasar a la discoteca") else: print("No puedes pasar") comprobacionEdad(5) def sumarDosDigitos(num1, num2): return num1 + num2 suma = sumarDosDigitos(6,10) print(suma + 10) lista = [] def addElementoLista(lista, elemento): lista.append(elemento) print(str(lista)) addElementoLista(lista, "Patata") print(str(lista)) addElementoLista(lista, 1) print(str(lista)) addElementoLista(lista, True) print(str(lista))
false
dac456345780fe6ced123598995a6e2285a89ef2
zabcdefghijklmnopqrstuvwxy/AI-Study
/1.numpy/topic59/topic59.py
1,558
4.4375
4
#argsort(a, axis=-1, kind='quicksort', order=None) # Returns the indices that would sort an array. # # Perform an indirect sort along the given axis using the algorithm specified # by the `kind` keyword. It returns an array of indices of the same shape as # `a` that index data along the given axis in sorted order. # Parameters # ---------- # a : array_like # Array to sort. # axis : int or None, optional # Axis along which to sort. The default is -1 (the last axis). If None, # the flattened array is used. # kind : {'quicksort', 'mergesort', 'heapsort'}, optional # Sorting algorithm. # order : str or list of str, optional # When `a` is an array with fields defined, this argument specifies # which fields to compare first, second, etc. A single field can # be specified as a string, and not all fields need be specified, # but unspecified fields will still be used, in the order in which # they come up in the dtype, to break ties. # Returns # ------- # index_array : ndarray, int # Array of indices that sort `a` along the specified axis. # If `a` is one-dimensional, ``a[index_array]`` yields a sorted `a`. #argsort()函数返回的是数组值从小到大的索引值。 #排序后会产生一个新的数组,不改变原有的数组。 import numpy as np arr=np.random.randint(0,100,size=(5,5)) print(f"random arr is \n{arr}") Z=arr[arr[:,1].argsort()] #Z=np.argsort(arr,axis=1) print(f"sort arr is \n{Z}")
true
0add5d9bcab734baa48b5bfc76db3e12b8be0617
pratikv06/Python-Practice
/Object Oriented/2_class.py
850
4.1875
4
class Dog(): def __init__(self, name, age): ''' Its like constructor - called when object is created (once)''' # self - represent object of that instance self.name = name self.age = age def get_name(self): ''' Display dog name''' print("Name: " + self.name) def get_age(self): print("Age: " + str(self.age)) def set_name(self, name): self.name = name def set_age(self, age): self.age = age def bark(self): '''user method''' print(self.name + " is barking...") print(">> Creating object") d = Dog('Tom', 5) print(type(d)) print(type(d.bark)) print(">> accessing attribute") print(d.name) #bad practice # create method to access variable d.get_name() d.get_age() d.set_age(10) d.get_age()
true
ed8ce5ee6f148e1f31e3cbec554f3942455486c1
beginner-lrk/test_python
/listandtuple.py
1,782
4.4375
4
#! /usr/bin/python # -*- coding: UTF-8 -*- # 变量classmates就是一个list,x=[ ] print(1) classmates = ['tom', 'Bob', '流川'] print(classmates) print(len(classmates)) # 用索引来访问list中每一个位置的元素,记得索引是从0开始的,最后一个元素的索引是len(classmates) - 1。 print(classmates[0], classmates[1], classmates[len(classmates) - 1]) # 取最后一个元素,倒数第二个,倒数第三个 print(classmates[-1], classmates[-2], classmates[-3]) # 追加元素到末尾 classmates.append('Alan') print(classmates[-1]) # 插入元素到指定位子 classmates.insert(1, '江河') print(classmates) # 删除末尾的元素 classmates.pop() print(classmates) # 删除指定的元素 classmates.pop(2) print(classmates) # 把某个元素替换成别的元素,可以直接赋值给对应的索引位置 classmates[1] = '山海' print(classmates) # 二维数组 s = ['python', 'java', ['asp', 'php'], 'scheme'] print(s[2][1]) # tuple和list非常类似,但是tuple一旦初始化就不能修改,没有append(),insert()可以正常地使用classmates[0],classmates[-1],但不能赋值成另外的元素. # 因为tuple不可变,所以代码更安全。如果可能,能用tuple代替list就尽量用tuple # tuple和list.一个是s=(),一个是s=[] t = (1, 2) print(t[1]) # 只有1个元素的tuple定义时必须加一个逗号,否则,u=(3)会优先判定数学意义上的括号 u = (3,) print(u) # 下一行中为tuple中存在一个list,a,b不可变,A,B是可变的。tuple所谓的“不变”是说,tuple的每个元素,指向永远不变 x = ('a', 'b', ['A', 'B']) x[2][1] = 'D' print(x) L = [ ['Apple', 'Google', 'Microsoft'], ['Java', 'Python', 'Ruby', 'PHP'], ['Adam', 'Bart', 'Lisa'] ] print(L[-1][-1])
false
9a707d82601e9d9624b52f04884606cfe8d81e53
noevazz/learning_python
/035_list_comprehension.py
681
4.46875
4
#A list comprehension is actually a list, but created on-the-fly during program execution, # and is not described statically. # sintax = [ value for value in expression1 if expression2] # it will generate a list with the values if the optional expression is True my_list = [number for number in range(1, 11)] # this will create a list with al the numbers generated print(my_list) even_numbers = [number for number in range(1, 11) if number%2==0] # this will create a list with al the numbers generated print(even_numbers) print("\n complicationg the things") print("creating lists in list using comprehension lists") a = [[i*2 for i in range(5, 11)] for a in range(3)] print(a)
true
e09e60bf03324e754a246d9ef71870103a86ee3a
noevazz/learning_python
/082__init__method.py
811
4.3125
4
# classes have an implicit method (that you can customize) to initialize your class with some values or etc. # the __init__ method is called constructor # __init__ cannot return a value!!!!!!!! as it is designed to return a newly created object and nothing else; class MyNiceClass(): # whenever you see "self" it is used to refer to the object. This is useful (and sometimes required) # so each object can have its own varaible def __init__(self, argument1): # self is required in the constructor. # argumentXs are optionals in the __init__ definition but required on instancing if you define a __init__ with arguments print("Hi :D") # code inside __init__() will be executed once you instance the class for each obkect obj = MyNiceClass("here you go, here is your now required argument")
true
1ac5d30ca8eb886ca9e3c293d490ca97d314024d
noevazz/learning_python
/072_ord_chr.py
708
4.59375
5
print("------ ord ------") # if you want to know a specific character's ASCII/UNICODE code point value, # you can use a function named ord() (as in ordinal). print(ord("A")) # 65 print(ord("a")) # 97 print(ord(" ")) # 32 (a-A) print(ord("ę")) # The function needs a >strong>one-character string as its argument # breaching this requirement causes a TypeError exception, # and returns a number representing the argument's code point. #print(ord("sadasdasd")) # TypeError: ord() expected a character, but string of length 9 found print("------ chr ------") # If you know the code point (number) and want to get the corresponding character, # you can use a function named chr(). print(chr(97)) print(chr(945))
true
1e78bed77a7b9c6d2c986581073098305e0fb66b
noevazz/learning_python
/010_basic_operations.py
676
4.59375
5
# +, -, *, /, //, %, ** print("BINARY operators require 2 parts, e.g. 3+2:") print("addition", 23+20) print("addition", 23+20.) # if at least one number is float the result will be a float print("subtraction", 1.-23) print("multiplication", 2*9) print("division", 5/2) print("floor division", 5//2) # floor division (IT DOES NOOOT MEAN AN INTEGER DIVISION, see below) print("floor division", 5.//2) print("floor division", 5//2.) print("mod", 10%4) #it return the remainder of the division print("exponentiation", 2**4) # it means 2*2*2*2 print("\nUnary operators require only one part:") print(-2) print(+3) # well this is not really useful, numbers are positive by default
true