blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
is_english
bool
c06217c63dd9a7d955ae6f2545773486d84158b0
Iliya-Yeriskin/Learning-Path
/Python/Exercise/Mid Exercise/4.py
266
4.40625
4
''' 4. Write a Python program to accept a filename from the user and print the extension of that. Sample filename : abc.java Output : java ''' file=input("Please enter a file full name: ") type=file.split(".") print("Your file type is: " + repr(type[-1]))
true
0d19a4381c7c94180999bc78613aecdf65cf04a0
Iliya-Yeriskin/Learning-Path
/Python/Projects/Rolling Cubes.py
2,517
4.1875
4
''' Cube project: receive an input of player money every game costs 3₪ every round we will roll 2 cubes, 1.if cubes are the same player wins 100₪ 2.if the cubes are the same and both are "6" player wins 1000₪ 3.if the cubes different but cube 2 = 2 player wins 40₪ 4.if the cubes different but cube 1 = 1 player wins 20₪ in the end we'll print how much money the player won. ''' from random import randint from time import sleep print("Welcome to the Rolling Cube Game\n--------------------------------\nEach round costs 3₪\n") money = input("How much money do you have?: \n") start_money = money turns = int(money)//3 change = int(money) % 3 print("Your Change is: "+str(change)+"₪") print("Prepare to play: "+str(turns)+" Rounds\n-----------------------") money = int(turns)*3 cube1 = 0 cube2 = 0 for i in range(turns): start_money = int(int(start_money)-3) money = int(int(money)-3) print("Round: "+str(i+1)+" Rolling...") sleep(2) cube1 = randint(1, 6) cube2 = randint(1, 6) if cube1 == cube2 & cube1 == 6: print("You Rolled ("+str(cube1)+","+str(cube2)+") And Won 1000₪!!\n-----------------------") money = money+1000 elif cube1 == cube2: if cube1 == 1: print("You Rolled ("+str(cube1)+","+str(cube2)+") And Won 120₪\n-----------------------") money = money+120 elif cube2 == 2: print("You Rolled ("+str(cube1)+","+str(cube2)+") And Won 140₪\n-----------------------") money = money+140 else: print("You Rolled ("+str(cube1)+","+str(cube2)+") And Won 100₪\n-----------------------") money = money+100 elif cube1 == 1: if cube2 == 2: print("You Rolled ("+str(cube1)+","+str(cube2)+") And Won 60₪\n-----------------------") money = money+60 else: print("You Rolled ("+str(cube1)+","+str(cube2)+") And Won 20₪\n-----------------------") money = money+20 elif cube2 == 2: print("You Rolled (" + str(cube1) + "," + str(cube2) + ") And Won 40₪\n-----------------------") money = money+40 else: print("You Rolled ("+str(cube1)+","+str(cube2)+") Sorry you didn't win\n-----------------------") print("Calculating your Prize....\n") sleep(3) print("Your Total winning are: ["+str(money)+"₪]\nNow you have: ["+str(int(start_money)+int(money))+"₪]" + "\nHope to see you again :-)")
true
5736199cbc797c8ae7d2cc6d8fc09da59023d5e2
Iliya-Yeriskin/Learning-Path
/Python/Exercise/Mid Exercise/10.py
306
4.3125
4
''' 10. Write a Python program to create a dictionary from a string. Note: Track the count of the letters from the string. Sample string : 'Net4U' Expected output: {'N': 1, 'e': 1, 't': 2, '4': 1, 'U': 1} ''' word=input("Please enter a word: ") dict={i:word.count(i) for i in word} print(dict)
true
8146be5d85020e6b965d2c4caf1991678677e410
Balgeum-Cha/vscode
/class.py
796
4.3125
4
#%% a = [1,2,3,4,] a.append(5) print(a) # %% def test(): pass class Person: pass bob = Person() cathy = Person() a = list() b = list() # %% # 생성자 class Person: def __init__(self): print(self,'is generated') self.name = 'Kate' self.age = 10 p1 = Person() p2 = Person() p1.name = 'arron' p1.age = 20 print(p1.name, p1.age) # %% # %% class Person: def __init__(self,n,a): print(self,'is generated') self.name = n self.age = a p1 = Person('Bob',30) p2 = Person('Kate',20) print(p1.name,p1.age) print(p2.name, p2.age) # %% # %% class Person: def __init__(self,name,age = 10): self.name = name self.age = age p2 = Person('Bob', 20) p3 = Person('Aaron') print(p2.name, p2.age) print(p3.name, p3.age) # %%
false
03a72365c3d05751de58a9e973736dd925ea6bb2
Stefan1502/Practice-Python
/exercise 13.py
684
4.5
4
#Write a program that asks the user how many Fibonnaci numbers to generate and then generates them. #Take this opportunity to think about how you can use functions. #Make sure to ask the user to enter the number of numbers in the sequence to generate. #(Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the sequence is the sum of the previous two numbers in the sequence. #The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …) def sum(a): return a[-2] + a[-1] def Fibonnaci(inp): li = [1, 1] for i in range(0, (inp - 2)): li.append(sum(li)) return li inpp = int(input("number pls: ")) print(Fibonnaci(inpp))
true
252901028a8feadeb4070b57ff330d2c2751757c
Stefan1502/Practice-Python
/exercise 9.py
894
4.21875
4
#Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. #(Hint: remember to use the user input lessons from the very first exercise) #Extras: Keep the game going until the user types “exit” Keep track of how many guesses the user has taken, and when the game ends, print this out. import random num = random.randint(1, 9) guess = 10 attempts = 0 while guess != num and guess != "exit": guess = int(input("guess the num: ")) if guess < num: print('too low') attempts += 1 elif guess > num: print('too high') attempts += 1 elif guess == "exit": break elif guess == num: print('you won') print(f'attempts = {attempts}') num = random.randint(1, 9) attempts = 0
true
b831314d05f1b2a996e687d3f43f046ef46eab0d
Stefan1502/Practice-Python
/exercise 28.py
421
4.375
4
# Implement a function that takes as input three variables, and returns the largest of the three. # Do this without using the Python max() function! # The goal of this exercise is to think about some internals that Python normally takes care of for us. # All you need is some variables and if statements! def return_max(x,y,z): li = sorted([x,y,z]) return li[-1] print(return_max(1,156,55))
true
d0fdd8537fc6e96de145f6c409cc166699a51ee1
ericrommel/codenation_python_web
/Week01/Chapter04/Exercises/ex_4-10.py
1,171
4.34375
4
# Extend your program above. Draw five stars, but between each, pick up the pen, move forward by 350 units, turn right # by 144, put the pen down, and draw the next star. You’ll get something like this: # # _images/five_stars.png # # What would it look like if you didn’t pick up the pen? import turtle def make_window(color="lightgreen", title="Exercise"): win = turtle.Screen() win.bgcolor(color) win.title(title) return win def make_turtle(pensize=3, color="blue"): a_turtle = turtle.Turtle() a_turtle.color(color) a_turtle.pensize(pensize) return a_turtle def draw_star(a_turtle, side=100): for i in range(5): a_turtle.right(144) a_turtle.forward(side) wn = make_window(title="Exercise 9") star = make_turtle() star.penup() star.setposition(-250, 0) star.pendown() star.speed(0) for j in range(5): draw_star(star) star.penup() star.forward(500) star.right(144) star.pendown() star2 = make_turtle(color="red") star2.penup() star2.setposition(-100, 0) star2.pendown() star2.speed(0) for j in range(5): draw_star(star2) star2.forward(150) star2.right(144) wn.mainloop()
true
7fcd55b167623ad4139ebe7d9eab75f958c78fb2
ericrommel/codenation_python_web
/Week01/Chapter04/Exercises/ex_4-09.py
694
4.53125
5
# Write a void function to draw a star, where the length of each side is 100 units. (Hint: You should turn the turtle # by 144 degrees at each point.) # # _images/star.png import turtle def make_window(color="lightgreen", title="Exercise"): win = turtle.Screen() win.bgcolor(color) win.title(title) return win def make_turtle(pensize=3, color="blue"): a_turtle = turtle.Turtle() a_turtle.color(color) a_turtle.pensize(pensize) return a_turtle def draw_star(a_turtle, side=100): for i in range(5): a_turtle.right(144) a_turtle.forward(side) wn = make_window(title="Exercise 9") star = make_turtle() draw_star(star) wn.mainloop()
true
f4aeba34d229b94abb230c2d9607b8f39570fede
ericrommel/codenation_python_web
/Week01/Chapter03/Exercises/ex_3-06.py
871
4.3125
4
# Use for loops to make a turtle draw these regular polygons (regular means all sides the same lengths, all angles the same): # An equilateral triangle # A square # A hexagon (six sides) # An octagon (eight sides) import turtle wn = turtle.Screen() wn.bgcolor("lightgreen") wn.title("Exercise 6") triangle = turtle.Turtle() triangle.color("hotpink") triangle.pensize(3) for i in range(3): triangle.forward(80) triangle.left(120) square = turtle.Turtle() square.color("hotpink") square.pensize(4) for i in range(4): square.forward(80) square.left(90) hexagon = turtle.Turtle() hexagon.color("hotpink") hexagon.pensize(6) for i in range(6): hexagon.forward(80) hexagon.left(60) octagon = turtle.Turtle() octagon.color("hotpink") octagon.pensize(8) for i in range(8): octagon.forward(80) octagon.left(45) wn.mainloop()
true
35da7c155a1d54f1e941e58340e43121a898e006
Elton86/ExerciciosPython
/EstruturaDeDecisao/Exe16.py
1,294
4.40625
4
"""Faça um programa que calcule as raízes de uma equação do segundo grau, na forma ax2 + bx + c. O programa deverá pedir os valores de a, b e c e fazer as consistências, informando ao usuário nas seguintes situações: - Se o usuário informar o valor de A igual a zero, a equação não é do segundo grau e o programa não deve fazer pedir os demais valores, sendo encerrado; - Se o delta calculado for negativo, a equação não possui raizes reais. Informe ao usuário e encerre o programa; - Se o delta calculado for igual a zero a equação possui apenas uma raiz real; informe-a ao usuário; - Se o delta for positivo, a equação possui duas raiz reais; informe-as ao usuário;""" from math import sqrt a = float(input("Digite o valor de a: ")) b = c = 0 if a == 0: print(" Valor invalido. Nao eh uma equacao de 2º grau. ") exit() else: b = float(input("Digite o valor de b: ")) c = float(input("Digite o valor de c: ")) delta = b ** 2 - 4 * a * c if delta < 0: print("A equacao no possui raizes reais.") elif delta == 0: print("Delta igual a 0. Apenas uma raiz real -> {}".format(-b / (2 * a))) else: x1 = (-b - sqrt(delta)) / (2 * a) x2 = (-b + sqrt(delta)) / (2 * a) print("A equacao possui duas raizes reais: {} e {}".format(x1, x2))
false
5760b3a9d3a22ff5c9fd0065db155cf87d873abf
Elton86/ExerciciosPython
/ExerciciosListas/Exe13.py
618
4.1875
4
"""Faça um programa que receba a temperatura média de cada mês do ano e armazene-as em uma lista. Após isto, calcule a média anual das temperaturas e mostre todas as temperaturas acima da média anual, e em que mês elas ocorreram (mostrar o mês por extenso: 1 – Janeiro, 2 – Fevereiro, . . . ).""" mes = [] media = 0 for i in range(12): mes_nome = str(input("Digite o mes: ")) temp = float(input("Digite a temperatura: ")) mes.append([mes_nome, temp]) media += temp media /= 12 for i in range(12): if mes[i][1] > media: print("Mes {} - Media {}".format(mes[i][0], mes[i][1]))
false
bc7321cb0a9bb06e00df001975f0772fcfeb13be
Elton86/ExerciciosPython
/ExerciciosListas/Exe15.py
1,511
4.125
4
"""Faça um programa que leia um número indeterminado de valores, correspondentes a notas, encerrando a entrada de dados quando for informado um valor igual a -1 (que não deve ser armazenado). Após esta entrada de dados, faça: Mostre a quantidade de valores que foram lidos; Exiba todos os valores na ordem em que foram informados, um ao lado do outro; Exiba todos os valores na ordem inversa à que foram informados, um abaixo do outro; Calcule e mostre a soma dos valores; Calcule e mostre a média dos valores; Calcule e mostre a quantidade de valores acima da média calculada; Calcule e mostre a quantidade de valores abaixo de sete; Encerre o programa com uma mensagem;""" valor = [] soma = media = quanti = x = quanti_7 = 0 while True: x = int(input("Digite um valor: ")) if x != -1: valor.append(x) soma += x else: break media = soma / len(valor) print("Total de Elementos: {}\n" "Valores em ordem: {}".format(len(valor), valor)) print("Soma: {}\n" "Media: {}".format(soma, media)) print("Ordem inversa") cont = len(valor) while cont != 0: print(valor[cont - 1]) cont -= 1 print("valores acima da media: ") for i in range(len(valor)): if valor[i] > media: print(valor[i]) quanti += 1 print("Valores acima da media: {}".format(quanti)) print("valores menores que 7: ") for i in range(len(valor)): if valor[i] < 7: print(valor[i]) quanti_7 += 1 print("Valores menores que 7: {}".format(quanti_7))
false
5de87c8f9022f227208214470e78d6cb200dff8a
Elton86/ExerciciosPython
/ExerciciosComStrings/Exe04.py
281
4.25
4
"""Nome na vertical em escada. Modifique o programa anterior de forma a mostrar o nome em formato de escada. F FU FUL FULA FULAN FULANO""" nome = input("Digite o nome: ") for i in range(1, len(nome) + 1): for j in range(0, i): print(nome[j], end=" ") print(" ")
false
5f8d04547f72564b308b9645c73f192b12a4c2b1
Elton86/ExerciciosPython
/ExerciciosFuncoes/Exe09.py
236
4.3125
4
"""Reverso do número. Faça uma função que retorne o reverso de um número inteiro informado. Por exemplo: 127 -> 721. """ def inverte_num(num): return num[::-1] numero = input("Digite o numero: ") print(inverte_num(numero))
false
bd0d86565d9a8380c8ede6fc6a36249d4b134ffb
arabindamahato/personal_python_program
/risagrud/function/actual_argument/default_argument.py
690
4.5625
5
''' In default argument the function contain already a arguments. if we give any veriable at the time of function calling then it takes explicitely . If we dont give any arguments then the function receives the default arguments''' '''Sometimes we can provide default values for our positional arguments. ''' def wish(name='Guest'): print('hello {}'.format(name)) print('hello {}'.format(name)) wish('Arabinda') ''' This below code is not right because " After default arguments we should not take non default arguments"''' # def wish(name='Guest', ph_no): # print('hello {} {}'.format(name, ph_no)) # print('hello {} {}'.format(name, ph_no)) # wish('Arabinda','ph_no')
true
90aba704a0cf75e1359c3585d1986dbb7a5b826d
arabindamahato/personal_python_program
/programming_class_akshaysir/find_last_digit.py
353
4.28125
4
print('To find the last digit of any number') n=int(input('Enter your no : ')) o=n%10 print('The last digit of {} is {}'.format(n,o)) #To find last digit of a given no without using modulas and arithmatic operator print('To find last digit of a given no') n=(input('Enter your no : ')) o=n[-1] p=int(o) print('The last digit of {} is {}'.format(n,p))
true
e4bc895b6c639fda81703d162b07034888231d50
Laurensvaldez/PythonCrashCourse
/CH8: Functions/try_it_yourself_ch8_8_8.py
986
4.375
4
# Start with your program from exercise 8-7. Write a while loop that allows users to enter an album's artist and title. # Once you have that information, call make_album() with the user's input and print the dictionary that's created. # Be sure to include a quit value in the while loop. def make_album(artist, title, tracks=0): """Return an artist name and an album title in a dictionary""" book = { 'name_artist': artist.title(), 'name_album': title.title()} if tracks: book['tracks'] = tracks return book # prepare the prompts. title_prompt = "\nWhat album are you thinking of? " artist_prompt = "Who's the artist? " # Let the user know how to quit. print("Enter 'quit' at any time to stop.") while True: title = input(title_prompt) if title == 'quit': break artist = input(artist_prompt) if artist == 'quit': break album = make_album(artist, title) print(album) print("\nThanks for responding!")
true
9cb4ce71d22344f24e1d3cc338bb9e83ed1ad3ad
Laurensvaldez/PythonCrashCourse
/CH8: Functions/making_pizzas.py
1,837
4.3125
4
# In this file we will import the function of pizza_import.py import pizza_import print("Importing all the functions in the module") pizza_import.make_pizza(16, 'pepperoni') pizza_import.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') print("-------------------------------------------") # To use the import the following syntax is necessary: # module_name.function_name() # You can also import a specific function from a module. Here's the general syntax for this approach: # from module_name import function_name # You can import as many functions as you want from a module by seperating each function's name with a comma: # from module_name import function_0, function_1, function_2 # Using 'as' to Give a Function an Alias # Here we give the function make_pizza() an alias, mp(), by importing make_pizza as mp. The 'as' keyword renames a # function using the alias you provide. from pizza_import import make_pizza as mp print("Importing specific function under an alias") mp(16, 'pepperoni') mp(12, 'mushrooms', 'green peppers', 'extra cheese') # The general syntax for providing an alias is: # from module_name import function_name as fn print("-------------------------------------------") # You can also provide an alias for a module name. # Such as: import pizza_import as p p.make_pizza(16, 'pepperoni') p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') # The general syntax for providing an alias for a module is: # import module_name as mn print("-------------------------------------------") # You can tell Python to import every function in a module by using the asterisk (*) operator # Example: from pizza_import import * make_pizza(16, 'pepperoni') make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') # The general syntax for providing this import is: # from module_name import *
true
146541bd8096d3dada3b6b651f7d74caf3d8fe68
Laurensvaldez/PythonCrashCourse
/CH9: Classes/9-6_ice_cream_stand.py
2,095
4.5625
5
# Write a class called IceCreamStand that inherits from the Restaurant class you wrote in Exercise 9-1 or Exercise 9-4 # Either version of the class will work; just pick the one you like better class Restaurant: """A simple restaurant class""" def __init__(self, restaurant_name, cuisine_type): """Initialize restaurant name and cuisine type""" self.restaurant_name = restaurant_name.title() self.cuisine_type = cuisine_type # Add an attribute called number_served with a default value of 0 self.number_served = 0 def describe_restaurant(self): print("The restaurant is called " + self.restaurant_name + ".") print("And the cuisine type is " + self.cuisine_type + ".") def open_restaurant(self): print("The restaurant " + self.restaurant_name.title() + " is open.") def customers_served(self): print("The restaurant has served " + str(self.number_served) + " people.") def set_number_served(self, served_update): """Add a method called set_number_served() that lets you set the number of customers that have been served""" self.number_served = served_update def increment_number_served(self, increment_served): """Method lets you increment the number of customers who's been served.""" self.number_served += increment_served class IceCreamStand(Restaurant): """An Ice Cream Stand, with a class of a restaurant.""" # Add an attribute called flavors that stores a list of ice cream flavors def __init__(self, name, cuisine_type='ice_cream'): super().__init__(name, cuisine_type) self.flavors = [] # Write a method that displays these flavors def display_flavors(self): """Method that displays the flavors available.""" for flavor in self.flavors: print("- " + flavor.title()) # Create an instance of IceCreamStand, and call this method big_one = IceCreamStand('The Big One') big_one.flavors = ['vanilla', 'chocolate', 'black cherry'] big_one.describe_restaurant() big_one.display_flavors()
true
f14e51cff185f2277385b1a0d580fd0a077e7195
Laurensvaldez/PythonCrashCourse
/Ch6: Dictionaries/try_it_yourself_ch6_6_1.py
514
4.3125
4
# Try it yourself challenge 6-1 # Person # Use a dictionary to store information about a person you know. # Store their first name, last name, age, and the city in which they live. You should have keys such as # first_name, last_name, age, and city. Print each piece of information stored in your dictionary. person = { 'first_name': 'Elba', 'last_name': 'Lopez', 'age': 23, 'city': 'Rotterdam', } print(person['first_name']) print(person['last_name']) print(person['age']) print(person['city'])
true
755616213684796cb48d924e5bf927e994e030d1
Laurensvaldez/PythonCrashCourse
/CH4: working with lists/try_it_yourself_ch4_4_11.py
500
4.21875
4
print ("More Loops") # all versions of foods.py in this section have avoided using for loops when printing to save space # Choose a version of foods.py, and write two for loops to print each list of foods my_foods = ['pizza', 'falafel', 'carrot cake'] print ("My favorite foods are: ") for food in my_foods: print (food.title()) print("\n") friends_foods = ['hamburger', 'kapsalon', 'pica pollo'] print("My friend's favorite foods are: ") for food in friends_foods: print(food.title())
true
2593aeaf239015183c48861a96af3d1feb21d6d3
Laurensvaldez/PythonCrashCourse
/CH9: Classes/9-5_login_attempts.py
2,622
4.46875
4
# Add an attribute called login_attempts to your User class from Exercise 9-3 class User: """A class to describe a user""" # Create two attributes called first_name and last_name # and then create several other attributes that are typically stored in a user profile def __init__(self, first_name, last_name, age, birthplace, relationship_status): """Initialize the first name and last name""" self.first_name = first_name.title() self.last_name = last_name.title() self.age = age self.birthplace = birthplace.title() self.relationship_status = relationship_status self.login_attempts = 0 def describe_user(self): """This method prints a summary of the user""" msg_1 = "The user's first name is " + self.first_name + " and his/her last name is " + \ self.last_name msg_2 = self.first_name + " " + self.last_name + " age is " + str(self.age) + \ " and lives in " + self.birthplace + "." msg_3 = self.first_name + " " + self.last_name + " is currently " + self.relationship_status + \ "." print("\n" + msg_1) print(msg_2) print(msg_3) def greet_user(self): """This method provides a personalized greeting to the user.""" # print a personalized greeting to the user greeting = "Hello " + self.first_name + ", I hope you have a wonderful day!" print(greeting) def increment_login_attempts(self): """Increment the value of login by 1.""" self.login_attempts += 1 # Write another method called reset_login_attempts() that resets the value of login_attempts to 0 def reset_login_attempts(self): self.login_attempts = 0 # Make an instance of the User class and call increment_login_attempts() several times, and call reset_login_attempts() laurens = User("Laurens", "Salcedo Valdez", 29, "Rotterdam", "in a relationship") laurens.describe_user() laurens.greet_user() laurens.increment_login_attempts() print("Login attempts are: " + str(laurens.login_attempts)) laurens.increment_login_attempts() print("Login attempts are: " + str(laurens.login_attempts)) laurens.increment_login_attempts() print("Login attempts are: " + str(laurens.login_attempts)) laurens.increment_login_attempts() print("Login attempts are: " + str(laurens.login_attempts)) laurens.reset_login_attempts() print("Login attempts are reset to: " + str(laurens.login_attempts)) # Print login_attempts again to make sure it was reset to 0 print("Login attempts are reset to: " + str(laurens.login_attempts))
true
a4ca9323e0c5bbd2cd4f81cb49151482d2a3d802
phu-mai/calculate
/calculate.py
777
4.125
4
from datetime import datetime def string_to_date(input): return datetime.strptime(input, "%d/%m/%Y") def check_date(input): if string_to_date(input) < datetime.strptime("01/01/1900", "%d/%m/%Y") or string_to_date(input) > datetime.strptime("31/12/2999", "%d/%m/%Y"): return False else: return True def date_between(first_date, second_date): if check_date(first_date) and check_date(second_date): return abs(string_to_date(first_date) - string_to_date(second_date)).days - 1 else: print("The valid date range is between 01/01/1900 and 31/12/2999") if __name__ == "__main__": print(date_between("2/6/1983", "22/6/1983")) print(date_between("4/7/1984", "25/12/1984")) print(date_between("3/1/1989", "3/8/1983"))
true
56490d658082b16ec7ec9140147f0e3e0544c630
subhendu17620/RUAS-sem-04
/PP/Java/lab03/a.py
1,391
4.1875
4
# Python3 program to print all Duplicates in array # A class to represent array of bits using # array of integers class BitArray: # Constructor def __init__(self, n): # Divide by 32. To store n bits, we need # n/32 + 1 integers (Assuming int is stored # using 32 bits) self.arr = [0] * ((n >> 5) + 1) # Get value of a bit at given position def get(self, pos): # Divide by 32 to find position of # integer. self.index = pos >> 5 # Now find bit number in arr[index] self.bitNo = pos & 0x1F # Find value of given bit number in # arr[index] return (self.arr[self.index] & (1 << self.bitNo)) != 0 # Sets a bit at given position def set(self, pos): # Find index of bit position self.index = pos >> 5 # Set bit number in arr[index] self.bitNo = pos & 0x1F self.arr[self.index] |= (1 << self.bitNo) # Main function to print all Duplicates def checkDuplicates(arr): # create a bit with 32000 bits ba = BitArray(320000) # Traverse array elements for i in range(len(arr)): # Index in bit array num = arr[i] # If num is already present in bit array if ba.get(num): print(num, end = " ") # Else insert num else: ba.set(num) # Driver Code if __name__ == "__main__": arr = [1, 5, 1, 10,10000,2,10000,1,5, 12, 10] checkDuplicates(arr) # This code is conributed by # sanjeev2552
true
f600b3970b3c556a9aa03af8d6ef7b1f1dd124f7
MirjaLagerwaard/MountRUSHmore
/main.py
1,500
4.28125
4
import sys from algorithm import * if __name__ == "__main__": # Error when the user did not give the right amount of arguments if len(sys.argv) <= 1 or len(sys.argv) > 3: print "Usage: python main.py <6_1/6_2/6_3/9_1/9_2/9_3/12> <breadth/depth/random>" exit() # update fp to the CSV file the user asked for if sys.argv[1] == "6_1": fp = "vehicles_6x6_1.csv" shape = 6 elif sys.argv[1] == "6_2": fp = "vehicles_6x6_2.csv" shape = 6 elif sys.argv[1] == "6_3": fp = "vehicles_6x6_3.csv" shape = 6 elif sys.argv[1] == "9_1": fp = "vehicles_9x9_1.csv" shape = 9 elif sys.argv[1] == "9_2": fp = "vehicles_9x9_2.csv" shape = 9 elif sys.argv[1] == "9_3": fp = "vehicles_6x6_3.csv" shape = 9 elif sys.argv[1] == "12": fp = "vehicles_12x12.csv" shape = 12 else: print "Usage: python main.py <6_1/6_2/6_3/9_1/9_2/9_3/12> <breadth/depth/random>" exit() # prepare the CSV file before running an algorithm board = PrepareFile(fp, shape) # run the algorithm the user asked for if sys.argv[2] == "breadth": BreadthFirstSearch(board) elif sys.argv[2] == "depth": Run_ReversedIterativeDeepeningDepthFirstSearch(board) elif sys.argv[2] == "random": Random(board) else: print "Usage: python main.py <6_1/6_2/6_3/9_1/9_2/9_3/12> <breadth/depth/random>" exit()
true
90bda58a280724875f5ba10d8171e81e093338ac
prince-singh98/python-codes
/ConditionalStatements/DigitAlphabateOrSpecialCharecter.py
229
4.28125
4
char = input("enter a alphabet") if((char>='a' and char<='z') or (char>='A' and char<='Z')): print(char,"is alphabet") elif(char>='0' and char<='9'): print(char, "is digit") else: print(char, "is special character")
true
4c19578d82cdd55affaef69cd74f214a1664b1ff
prince-singh98/python-codes
/Relation/RelationList.py
1,049
4.1875
4
A = {"A", "B", "C"} def is_symmetric(relation): for a, b in relation: if (a,b) in relation and (b,a) in relation and a != b: return "Symmetric" return "Asymmetric" print(is_symmetric([("A","A"), ("A","C"), ("C","A"), ("C","C")])) # True print(is_symmetric([("A","A"), ("A","C"), ("A","B"), ("C","C")])) # False def is_reflexive(relation): if all((a,a) in relation for a in A): return "reflexive" return "not reflexive" print(is_reflexive([("A","A"), ("A","C"), ("B","B"), ("A","B"), ("C","C")])) # True print(is_reflexive([("A","A"), ("A","C"), ("C","A"), ("C","C")])) # False print(is_reflexive([("A","C"), ("A","B")])) # False def is_transitive(relation): for (a, b) in relation: for (c, d) in relation: if b == c and (a, d) in relation: return "transitive" return "not transitive" print(is_transitive([("A","B"), ("A","C"), ("B","C"), ("A","B"), ("C","C")])) # True print(is_transitive([("A","B"), ("B","C"), ("A","B"), ("C","C")])) # False
false
68e536bf4e5f3b3a7f8a853223e83f6f03511a98
Chrisgo-75/intro_python
/conditionals/switch_or_case.py
696
4.15625
4
#!/usr/bin/env python3 # Index # Python does not have a "switch" or "case" control structure which # allows you to select from multiple choices of a single variable. # But there are strategies that can simulate it. # # 1. def main(): # 1. choices = dict( one = 'first', two = 'second', three = 'third', four = 'fourth', five = 'fifth' ) print('Looking for "seven" in dictionary. If it doesn\'t exist then print "other":') v = 'seven' print(choices.get(v, 'other')) print() print('Looking for a key of "five" and if found print it\'s value:') v = 'five' print(choices.get(v, 'other')) print() if __name__ == '__main__': main()
true
85145d7b919824030bb2ce9a1f2132cfadcac9df
Chrisgo-75/intro_python
/general_syntax/strings.py
1,433
4.9375
5
#!/usr/bin/env python3 # Index # 1. Strings can be created with single or double quotes. # 2. Can introduce new line into a string. # 3. Display escape characters (literally). Use "r" per example below. # - r == "raw string" which is primarily used in regular expressions. # 4. Format or replace character in string (Python 3 @ 2 way) # 5. Define a multi-line string using triple single/double quotes # 6. def main(): n = 42 # 1. Single or Double quotes s = 'This is a string using single quotes!' print(s) s1b = "This is also a string using double quotes!" print(s1b) print() # 2. New line in string s2 = "This is a string\nwhich introduces a new line!" print(s2) print() # 3. Show escape characters (literally) s3 = r"This is a string that literally displays an escape character \n." print(s3) print() # 4. Format or replace character in string (Python 3 @ 2 way) s4 = "Inserting variable value in this string ... {} ... Python3 uses curly braces and the string's format method".format(n) print(s4) s4b = "Inserting varaible value in this string ... %s ... Python2 uses percents." % n print(s4b) print() # 5. Define a multi-line string using triple single/double quotes print('This example will display a multi-line (3 lines) example:') s5 = '''\ First line Second line Third line ''' print(s5) print() if(__name__ == "__main__"): main();
true
7a16498f5039f500dbb9b916d5f6a87ba3215c4b
datarocksAmy/APL_Python
/ICE/ICE02/ICE2.py
2,515
4.125
4
''' * Python Programming for Data Scientists and Engineers * ICE #2 * Q1 : Frequencies of characters in the string. * Q2 : Max word length in the string. * Q3 : Count numbers of digits and characters in the string. * #11 Chia-Hui Amy Lin ''' # Prompt user for a sentence user_input_sentence = input("Please type a sentence you have in mind : ") # =================================================================================== # Q1 : Calculate character frequency in a string characters = list(user_input_sentence) characters = list(map(lambda x: x.strip(',.'), characters)) characters = " ".join(characters).split() frequency = {} for idx in range(len(characters)): try: frequency[characters[idx]] += 1 except KeyError: frequency[characters[idx]] = 1 # Header print("\n" + "[ Frequency Count ]") print("------------------------------------------------------") # Output frequency count for each character in the user input for key, val in frequency.items(): print("Word " + key + " : " + str(val) + " times") # =================================================================================== # Q2 : Take a list of words and return the length of the longest one wordList = user_input_sentence.split() wordLenCount = {} for word in range(len(wordList)): wordLenCount[wordList[word]] = len(wordList[word]) sort = dict(sorted(wordLenCount.items(), key=lambda x: (-x[1], x[0]))) # Header print("\n" + "[ Max Word Length ]") print("------------------------------------------------------") # Output the max lenght print("Max word length of this sentence :", list(sort.values())[0]) maxWords = [] for w_key, w_val in sort.items(): if w_val == list(sort.values())[0]: maxWords.append(w_key) # Output word(s) with the max length print("Word(s) with max length :") for selection in range(len(maxWords)): print("\t" + maxWords[selection]) # =================================================================================== # Q3 : Obtain a string and calculate the number of digits and letters # Header print("\n" + "[ # of Digits & Letters ]") print("------------------------------------------------------") # Filter out the digits in the string numberList = list(filter(str.isdigit, user_input_sentence)) letterCount = ''.join([letter for letter in user_input_sentence if not letter.isdigit()]) # Output the count for digits and letters in the string print("Total # of numbers(digits):", len(numberList)) print("Total # of letters:", len(letterCount))
true
9094b07c5ef5da96a89870a898db9b9c010dbc45
datarocksAmy/APL_Python
/Lab Assignment/Lab04/Lab04_b_MashDictionaries.py
1,293
4.125
4
# ------------------------------------------------------------ # * Python Programming for Data Scientists and Engineers # * LAB #4-b Mash Dictionaries # * #11 Chia-Hui Amy Lin # ------------------------------------------------------------ # Dictionary from statistics import mean # Function def mash(input_dict): ''' Function for mashing keys with integer values into one and update the current dictionary in the list. ''' for idx in range(len(input_dict)): intList = [] popList = [] mash = {} keyMash = "" for key, val in inputList[idx].items(): if type(val) is int: intList.append(val) popList.append(key) keyMash += (key + ",") mash[keyMash] = mean(intList) input_dict[idx].update(mash) for num in range(len(popList)): input_dict[idx].pop(popList[num]) return input_dict # Input value inputList = [{"course": "coffee", "Crows": 3, "Starbucks": 7}, {"course": "coffee", "Crows": 4, "Starbucks": 8}, {"course": "coffee", "Crows": 3, "Starbucks": 5}] print("< #4-b Mash Dictionaries >") # Call function to mash/update the original list inputList = mash(inputList) # Output the result print("Updated Input :", inputList)
true
5db43d9103f910dfeb21e7196142c38fc112af38
datarocksAmy/APL_Python
/ICE/ICE03/ICE3-2 New List.py
1,845
4.1875
4
''' * Python Programming for Data Scientists and Engineers * ICE #3-2 Make new list * Take in a list of numbers. * Make a new list for only the first and last elements. * #11 Chia-Hui Amy Lin ''' # Function for prompting user for numbers, append and return the list def user_enter_num(count_prompt, user_num_list): # Prompt user for a number(integer). # If it's an invalid input, prompt user again. flag = False while True: user_prompt = input("Please enter 5 numbers : ") try: user_prompt = int(user_prompt) except ValueError or TypeError: print("Invalid input. Please enter an INTEGER." + "\n") flag = True count_prompt -= 1 else: break user_num_list.append(user_prompt) return user_num_list # Pre-set number list numbers = [4, 5, 6, 7, 8] # Variables for customized number list user_number = [] count = 0 # Continue to call function user_enter_num until the user entered 5 numbers while count < 5: user_enter_num(count, user_number) count += 1 # Output the first and last number of new list from the original one that the user prompted print("===================================================================") print("<< User Prompt Number List >>") print("The Original User Prompt List : ", user_number) firstLastNumList = user_number[0::len(user_number)-1] print("New list containing only first and last element(user prompt) : ", firstLastNumList) # Output the first and last number of new list from the pre-set number list print("===================================================================") print("<< Pre-set Number List >>") print("Original Number List : ", numbers) presetNumList = numbers[0::len(numbers)-1] print("New list containing only first and last element(preset) : ", presetNumList)
true
dbc3dfae249a74877e71007e05cd933c92d13459
lelong03/python_algorithm
/array/median_sorted_arrays.py
2,041
4.125
4
# Find median of two sorted arrays of same size # Objective: Given two sorted arrays of size n. # Write an algorithm to find the median of combined array (merger of both the given arrays, size = 2n). # What is Median? # If n is odd then Median (M) = value of ((n + 1)/2)th item term. # If n is even then Median (M) = value of [(n/2)th item term + (n/2 + 1)th item term]/2 # Binary Approach: Compare the medians of both arrays? # - Say arrays are array1[] and array2[]. # - Calculate the median of both the arrays, say m1 and m2 for array1[] and array2[]. # - If m1 == m2 then return m1 or m2 as final result. # - If m1 > m2 then median will be present in either of the sub arrays. # - If m2 > m1 then median will be present in either of the sub arrays. # - Repeat the steps from 1 to 5 recursively until 2 elements are left in both the arrays. # - Then apply the formula to get the median # - Median = (max(array1[0],array2[0]) + min(array1[1],array2[1]))/2 def get_median_and_index(l, start, end): size = end - start + 1 if size % 2 != 0: index = start+(size+1)/2-1 return index, l[index] else: index = start+size/2 return index, (l[index] + l[index+1]) / 2 def find(a, a_start, a_end, b, b_start, b_end): if (a_end - a_start + 1) == 2 and (b_end - b_start + 1) == 2: return (max(a[a_start], b[b_start]) + min(a[a_end], b[b_end])) / 2.0 mid_index_a, median_a = get_median_and_index(a, a_start, a_end) mid_index_b, median_b = get_median_and_index(b, b_start, b_end) if median_a == median_b: return median_a * 1.0 if median_a > median_b: return find(a, a_start, mid_index_a, b, mid_index_b, b_end) else: return find(a, mid_index_a, a_end, b, b_start, mid_index_b) def get_median_of_two_sorted_arrays(array_1, array_2): return find(array_1, 0, len(array_1)-1, array_2, 0, len(array_2)-1) if __name__ == '__main__': arr_1 = [2,6,9,10,11] arr_2 = [1,5,7,12,15] print(get_median_of_two_sorted_arrays(arr_1, arr_2))
true
0847e2a138d297ceb53d34e5c15004424227907e
lelong03/python_algorithm
/array/next_permutation.py
1,358
4.125
4
# Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. # If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). # The replacement must be in-place, do not allocate extra memory. # Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. def reverse(arr, begin, end): while begin < end: arr[begin], arr[end] = arr[end], arr[begin] begin += 1 end -= 1 def next_permutation(arr, begin, end): partion_index = end-1 while partion_index > -1 and arr[partion_index] >= arr[partion_index+1]: partion_index -= 1 if partion_index == -1: return reverse(arr, begin, end) change_index = end while change_index > -1 and arr[change_index] <= arr[partion_index]: change_index -= 1 arr[change_index], arr[partion_index] = arr[partion_index], arr[change_index] return reverse(arr, partion_index+1, end) a = [1,3,4,2] next_permutation(a, 0, len(a)-1) print a a = [1,4,2,3] next_permutation(a, 0, len(a)-1) print a a = [1,2,3,4] next_permutation(a, 0, len(a)-1) print a a = [4,3,2,1] next_permutation(a, 0, len(a)-1) print a a = [5,1,1] next_permutation(a, 0, len(a)-1) print a
true
90cc3867cb7a055bfea83ee921836bbb94ff915d
lelong03/python_algorithm
/recursion/list_sub_sets.py
1,117
4.28125
4
# Question: List all sub sets of one set # Solutions: # - with base case n = 0, there is one sub set {} # - with n = 1, there are: {}, {a} # - with n = 2, there are: {}, {a}, {b}, {a,b} # - with n = 3, there are: {}, {a}, {b}, {c}, {a,b}, {a,c}, {b,c}, {a,b,c} # P(3) = P(2) + {c} # Using Recursion def list_sub_set(a_set, n): set_len = n + 1 if set_len == 0: return [[]] result = [] for subset in list_sub_set(a_set, n-1): result.append(subset) result.append(subset + list(a_set[n])) return result # Combinatorics def list_sub_set_2(a_set): set_length = len(a_set) max = 1 << set_length result = [] for i in range(max): result.append(get_sub_set(a_set, set_length, i)) return result def get_sub_set(a_set, set_length, number): sub_set = [] index = set_length-1 while number > 0: if (number & 1) == 1: sub_set.append(a_set[index]) index -= 1 number >>= 1 return sub_set aset = ['a', 'b', 'c'] print list_sub_set(aset, len(aset)-1) aset = ['a', 'b', 'c', 'd'] print list_sub_set_2(aset)
false
429a91d928bbf33f9ddf0c5daea25a8777d65084
anutha13/Python
/demo.py
1,058
4.21875
4
from time import sleep from threading import Thread class Hello(Thread): def run(self): for i in range(5): print("hello") sleep(1) class Hi(Thread): def run(self): for i in range(5): print("Hi") t1=Hello() t2=Hi() t1.start() #this is a different thread t1 sleep(0.2) t2.start() #this is another thread t2 t1.join() t2.join() #main thread will not execute until both t1 and t2 will join print("bye") #this whole program is using a main thread #but to run on different core or different threads not in Main thread #we need Thread as a parent of the Hi and Hello class # multi-threading # threading is light-weight process and that process is divided into small parts # that part is called thread # can i execute 2 function on different cores at the same time #zip() zips two list with each other list=['anu','thakur','king] num=['ab','cd','ef'] zipped=zip(list,num) for (a,b) in zipped: print(a,b)
true
5a0140339b66c37c3d1f7056f8a2b8520630d39c
JasleenUT/Encryption
/ElGamal/ElGamal_Alice.py
1,669
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 23 20:07:58 2018 @author: jasleenarora """ # Read the values from intermediate file with open('intermediate.txt','r') as f: content = f.readlines() p = int(content[0]) g = int(content[1]) a = int(content[2]) c1 = int(content[3]) c2 = int(content[4]) ###fast powered def fastPower(g, A, N): a=g b=1 while A>0: if A%2==1: b=(b*a)%N a=(a*a)%N A=A//2 return b # This script converts an integer to binary def int2bin(integer): if integer == 0: return('00000000') binString = '' while integer: if integer % 2 == 1: binString = '1' + binString else: binString = '0' + binString integer //=2 while len(binString)%8 != 0: binString = '0' + binString return binString # Converts binary to integer def bin2int(binary): return int(binary,2) # this tells the function that the input 'binary' is in base 2 and it converts it to base 10 # This will convert integer to character def int2msg(integer): return bin2msg2(int2bin(integer)) # Write the conversion from binary to character in one line def bin2msg2(binary): return ''.join(chr(int(binary[i*8:i*8+8],2)) for i in range(len(binary)//8)) def ElGamal(p,g,a,c1,c2): # Step1: calculate ((c1)^a)^p-2 temp = fastPower(c1,a,p) s1 = fastPower(temp,p-2,p) # Step2: Multiply this by c2 s2 = (s1*c2)%p # Step3: Convert this to character msg = int2msg(s2) print("The decoded message is: ",msg) ElGamal(p,g,a,c1,c2)
true
2a0c0bb0c9f718791d2742a1e43bfd097c8c5196
maiconarantes/Atividade2
/questao2.py
805
4.28125
4
#_*_coding:latin1_*_ #Elaborar um programa que lê 3 valores a,b,c e verifica se eles formam #ou não um triângulo. Supor que os valores lidos são inteiros e positivos. Caso #os valores formem um triângulo, calcular e escrever a área deste triângulo. Se #não formam triângulo escrever os valores lidos. (Se a &gt; b + c não formam #triângulo algum, se a é o maior). print("Informe um valor para a!") a = float(input()) print("Informe um valor para b!") b = float(input()) print("Informe um valor para c!") c = float(input()) if a < b + c and b < a + c and c < a + b: print("Os Valores acima podem formar um triangulo") area = b * a / 2 print("A area do Triangulo e", area) else: print("Os valores acima não pode formar um triangulo") print(a,b,c)
false
d96e0003f97a041987cb123654bbd02b12c62220
ChristianChang97/Computational-Thinking
/ex1.py
283
4.15625
4
print("1TDS - FIAP - Primeiro Programa Python") numero = int (input("Digite um número: ")) #campo para digitação do número quadrado = numero*numero #cálculo do quadrado do número print("O quadrado do número {} é {}".format(numero, quadrado)) #impressão do resultado
false
31437cfb86cb0bdd9ce378ba6aacd44a48c1a3dd
opember44/Engineering_4_Notebook
/Python/calculator.py
1,426
4.34375
4
# Python Program 1 - Calculator # Written by Olivia Pemberton def doMath (num1, num2, operation): # defines do math function # program will need yo to enter 2 numbers to do operation if operation == 1: x = round((num1 + num2), 2) return str(x) if operation == 2: x = round((num1 - num2), 2) return str(x) if operation == 3: x = round((num1 * num2), 2) return str(x) if operation == 4: x = round((num1 / num2), 2) return str(x) if operation == 5: x = round((num1 % num2), 2) return str(x) # this makes the operation add, subtract, multiply, divide, and find # the remainder of the two numbers entered go = "y" # this sets the variable for the whileloop print("After calculations is complete, press Enter to go again") print("Press x then Enter to quit program") # prints the instructions the user needs to work the calculator while go == "y": # starts the calculator a = float(input("Enter 1st Number: ")) b = float(input("Enter 2nd Number: ")) # the user is told to put in the two numbers print("Sum:\t\t" + doMath(a,b,1)) print("Difference:\t" + doMath(a,b,2)) print("Product:\t" + doMath(a,b,3)) print("Quotient:\t" + doMath(a,b,4)) print("Modulo:\t\t" + doMath(a,b,5)) # the program run and finds all the answers to the math functions key = input(" ") # the program can be run again if the user puts in more numbers if key == "x": # the user can end the program by pressing x then enter break
true
1916dfb9e0fe6e071f41364a68eade456d4310aa
walterkwon/CWK-Memento-Python
/ep018.py
2,397
4.40625
4
#!/usr/bin/env python3 # Wankyu Choi - Creative Works of Knowledge 2019 # https://www.youtube.com/wankyuchoi # # # Episode 018 - Data Types: Tuple & Set Types def main(): """Entry Point""" print("=" * 10, "Tuple", "=" * 10) a_list = ['wankyu', 'james', 'fred', 'tom', 'harry'] a_tuple = ('wankyu', 'james', 'fred', 'tom', 'harry') print(f'a_list is a {type(a_list)}: {a_list}') print(f'a_tuple a {type(a_tuple)}: {a_tuple}') a_list[0] = 'ben' print(f'a_list is a {type(a_list)}: {a_list}') # tuples are immutable # a_tuple[0] = 'ben' # a_tuple.append('ben') # print(f'a_tuple a {type(a_tuple)}: {a_tuple}') a = ('wankyu') b = ('choi') print(f'{a} {b}') b, a = a, b print(f'{a} {b}') args = (3,'key',True) a, b, c = args print(f'args: 1. {a}, 2. {b}, 3. {c}') print("=" * 10, "Pseudo Tuple Comprehension", "=" * 10) odd_numbers = (x for x in range(10) if x % 2) print(tuple(odd_numbers)) print("=" * 10, "Set", "=" * 10) a_set = {'wankyu', 'james', 'fred', 'tom', 'harry'} another_set = set('wankyu james fred tom harry') print(f'a_set a {type(a_set)}: {a_set}') print(f'another_set a {type(another_set)}: {another_set}') print(f'another_set sorted: {sorted(another_set)}') list_set = set(dir(list)) tuple_set = set(dir(tuple)) print(sorted(list_set)) print(sorted(tuple_set)) # Union: 합집합 A | B print(f'Union: {sorted(list_set | tuple_set)}') print('Union:', sorted(list_set.union(tuple_set))) # Intersection: 교집합 A & B print(f'Intersection: {sorted(list_set & tuple_set)}') print('Intersection:', sorted(list_set.intersection(tuple_set))) # Difference: 차집합 A - B print(f'Difference: {sorted(list_set - tuple_set)}') print('Difference:', sorted(list_set.difference(tuple_set))) # Complement: 여집합(보집합) (A | B) - A print(f'Complement: {sorted((list_set | tuple_set) - list_set)}') # Symmetric Difference: 대칭 차집합 (A | B) - (A & B) print(f'Symmetric Difference:{sorted(list_set ^ tuple_set)}') print(f'Symmetric Difference: {sorted((list_set | tuple_set) - (list_set & tuple_set))}') print("=" * 10, "Set Comprehension", "=" * 10) odd_numbers = {x for x in range(10) if x % 2} print(odd_numbers) if __name__ == '__main__': main()
false
d95b1bfa19fa52013079f7d63f7794d1c6736d84
hectorzaragoza/python
/functions.py
1,985
4.1875
4
#functions allow us to put something into it, does something to it, and gives a different output. #We start with def to define the function, then we name it, VarName() #def function(input1, input2, input3,...): # code # more code # return value #result = functionName(In1, In2, In3,...) #result = value def addOne(x): #this line of code simply gives your function a name and inside the parenthesis, the inputs y = x + 1 #this line of code determines the actual function/manipulation/calculation that you are trying to do. #Line 12 cont. i.e. what you want to do to your inputs and assign that to a new variable which will then be returned return y #this line of code returns the output of your function def addTogether(in1, testin2): inter = in1 + testin2 return inter testValue = 2 #this is going to be the variable we put into our addOne function, whose result is assigned in result result = addOne(testValue) #y = testValue + 1 -> 2+1 -> 3 print(result) secondTwo = addTogether(testValue, result) #secondTwo is a variable that will store the result of inputting testValue #and result into the addTogether function defined in line 16. print(secondTwo) print(addTogether("Hello"," World!")) print(addTogether("Hello",str(1))) #exercise #Write a function that takes two inputs and returns their sum def SumFunction(VarOne, Vartwo): varthree = VarOne + Vartwo return varthree open = 1 close = 2 EndProduct = SumFunction(open, close) print(EndProduct) #Write a function that takes an input and checks how many times the input is divisible by 3 and by 5. It then returns #those two values def aFunction(InputA): DivByThree = int(InputA/3) #You can have multiple things done to an input within a single function and return #multiple results for tall those things as in this example. DivByFive = int(InputA/5) return DivByThree, DivByFive Divisible = aFunction(489) print(Divisible) print(163*3, 97*5) #testing result
true
ef58048b8b05de8a3239b61c320f601d02da1daa
manjushachava1/PythonEndeavors
/ListLessThanTen.py
498
4.21875
4
# Program 3 # Take a list and print out the numbers less than 5 # Extras: # 1. Write program in one line of code # 2. Ask the user for a number and return a list that contains elements that are smaller than that user number. a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [] c = [] # Extra 1 for element in a: if element < 5: b.append(element) print(b) # Extra 2 num = int(input("Enter a random number: ")) for element in a: if element < num: c.append(element) print(c)
true
7f66d0d287df330aaad8d58a3d74308a85171942
JavaScriptBach/Project-Euler
/004.py
518
4.125
4
#coding=utf-8 """ A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. """ def is_palindrome(num): string = str(num) for i in range(0, len(string) / 2): if string[i] != string[len(string) - 1 - i]: return False return True num = 0 for i in range(100, 1000): for j in range(100, 1000): if is_palindrome(i * j) and i * j > num: num = i * j print num
true
592e65372e0cbbbbaaaa50e61b16a4546e6301a5
pgiardiniere/notes-WhirlwindTourOfPython
/06-scalarTypes.py
2,782
4.53125
5
### Simple Types in Python :: # --- Python Scalar Types --- # ---------------------------------------------- # Type Example Description # `````````````````````````````````````````````` # int x = 1 integers # float x = 1.0 floating point nums # complex x = 1 + 2j complex nums # bool x = True True/False # str x = 'abc' String: chars//text # NoneType x = None Null values # # ---------------------------------------------- ### Integers (ints) x = 1; print ( type(x) ) # unlike most languages, ints do NOT overflow # they are variable-precision. print ( 2 ** 200 ) # Python ints up-cast to floats when divided print ( 5 / 2 ) # PYTHON 2 ONLY -- difference between 'int' and 'long' ### Floating-Point numbers # can be defined in decimal notation OR exponential x = 0.000005 y = 5e-6 print ( x == y ) x = 1400000.00 y = 1.4e6 print ( x == y ) # as expected, cast to float as follows: float(1) # as usual, floating point comparison is wonky print ( 0.1 + 0.2 == 0.3 ) # yields False # caused by binary > decimal (base-2 > base-10) approximation print( "0.1 = {0:.17f}".format(0.1) ) print( "0.2 = {0:.17f}".format(0.2) ) print( "0.3 = {0:.17f}".format(0.3) ) # specifically, representing a 1/10 digit num requires infinite digits in base-2 # much like 1/3 requires infinite digits in base-10 ### Complex Numbers print ( complex(1, 2) ) # j used instead of i c = 3 + 4j # j is 'keyword' - denotes imag print ( c.real ) print ( c.imag ) print ( c.conjugate() ) # 3 - 4j print ( abs(c) ) # 3^2 + (4j)^2 absolute magnitude ### String Type # String created with EITHER 'single' "double" quotes message = "foobar" response = "doi" # example (useful) string funcs/methods. print ( len(message) ) # 3 print ( message.upper() ) # make all-caps print ( message.lower() ) # all-lowercase print ( message.capitalize() ) # first-cap print ( message + response ) # string concat (NO auto-spacing) print ( message[0] ) # char indexing print ( 5 * response ) # * to mult. concat. ### None Type print ( type(None) ) # None keyword denotes NoneType # commonly used like "void" returns in other langs return_value = print('abc') print ( return_value ) ### Boolean Type result = (4 < 5) print ( result ) print ( type(result) ) print(True, False) # Boolean vals CASE SENSITIVE # construct using bool() print ( bool(42) ) # numeric nonzero is True print ( bool(0) ) # numeric zero is False print ( bool(None) ) # NoneType is False print ( bool("text") ) # norm. string is True print ( bool("") ) # empty string is False print ( bool([1,2]) ) # norm. list is True print ( bool([]) ) # empty list is False
true
6b43604d2d995874639262c7995a22dde3bd5b41
eshulok/2.-Variables
/main.py
604
4.53125
5
#Variables are like nicknames for values #You can assign a value to a variable temperature = 75 #And then use the variable name in your code print(temperature) #You can change the value of the variable temperature = 100 print(temperature) #You can use variables for operations temp_today = 85 temp_yesterday = 79 #How much warmer is it today than yesterday? print(temp_today - temp_yesterday) #Tomorrow will be 10 degrees warmer than today print(temp_today + 10) #Or if you want to save the value for tomorrow's temperature, create a new variable temp_tomorrow = temp_today + 10 print(temp_tomorrow)
true
37499520285d5a5b5b8746d02a4fc06854627f13
riyaasenthilkumar/riya19
/factorial.py
270
4.125
4
num=7 num=int(input("Enter a number:")) factorial=1 if num<0: print("factorial does not exist for negative number") elif num==0: print("the factorial of0 is 1") else: for i in range (1,num+1): factorial=factorial*i print("the factorial of",num,"is",factorial)
true
ccf67c2b2625e3ae6d1acc1e7cca475f8b3e5f67
Xtreme-89/Python-projects
/main.py
1,424
4.1875
4
<<<<<<< HEAD is_male = True is_tall = False if is_male and is_tall: print("You are a tall male") elif is_male and not is_tall: print("You are a short male") elif not is_male and is_tall: print("You are a tall female") else: print("You are a short female") #comparisons def max_num(num1, num2, num3): if num1 >= num2 and num2 >= num3: return num1 if num2 >= num1 and num2 >= num3: return num2 if num3 >= num1 and num3 >= num2: return num3 else: print("WTF u siked my programme") num1 = int(input("Type your first number ")) num2 = int(input("Type your second number ")) num3 = int(input("Type your third number ")) print(str(max_num(num1, num2, num3)) + " is the highest number") #Guessing Game secret_word = "Giraffe" guess = "" guess_count = 0 guess_limit = 3 out_of_guesses = False while guess != secret_word and not(out_of_guesses): if guess_count < guess_limit: guess = input("Guess the secret word: ") guess_count += 1 else: out_of_guesses = True if out_of_guesses: print("Out of guesses - you have no access") else: print("Well done, you now have full access to the high order of variables.") #For loops friends = ["Jim", "Karen", "Emma", "Alexandria", "Liz", "Ellie"] for friend in friends: print (friend) ======= print(3 +4.5) >>>>>>> ab1d0e7820f4a8f97b5b83024948417c6bbadd0b
true
3b6c35f55899dbc8819e048fdbdebb065cd01db1
brunomatt/ProjectEulerNum4
/ProjectEulerNum4.py
734
4.28125
4
#A palindromic number reads the same both ways. #The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. #Find the largest palindrome made from the product of two 3-digit numbers. products = [] palindromes = [] three_digit_nums = range(100,1000) for k in three_digit_nums: for j in three_digit_nums: products.append(k*j) def check_palindrome(stringcheck): #only works for 6 digit numbers which is all we need for this exercise if str(stringcheck)[0] == str(stringcheck)[-1] and str(stringcheck)[1] == str(stringcheck)[-2] and str(stringcheck)[2] == str(stringcheck)[-3]: palindromes.append(stringcheck) for num in products: check_palindrome(num) print(max(palindromes))
true
18187aef39ed5cdb6edad56d8599bc80586d93f8
TokarAndrii/PythonStuff
/pythonTasks/data_structures/moreOnList.py
1,760
4.71875
5
# https: // docs.python.org/3.0/tutorial/datastructures.html # list.append(x) # Add an item to the end of the list # equivalent to a[len(a):] = [x]. # list.extend(L) # Extend the list by appending all the items in the given list # equivalent to a[len(a):] = L. # list.insert(i, x) # Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x). # list.remove(x) # Remove the first item from the list whose value is x. It is an error if there is no such item. # list.pop([i]) # Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.) # list.index(x) # Return the index in the list of the first item whose value is x. It is an error if there is no such item. # list.count(x) # Return the number of times x appears in the list. # list.sort() # Sort the items of the list, in place. # list.reverse() # Reverse the elements of the list, in place. a = [66.25, 333, 333, 1, 1234.5] a.append(237) print(a) # [66.25, 333, 333, 1, 1234.5, 237] a.insert(1, 999) print(a) # [66.25, 999, 333, 333, 1, 1234.5, 237] a.remove(333) print(a) # [66.25, 999, 333, 1, 1234.5, 237] a.pop(1) print(a) # [66.25, 333, 1, 1234.5, 237] find = a.index(237) print(find) # 4 print(a.count(333)) # 1 a.sort() print(a) # [1, 66.25, 237, 333, 1234.5] a.reverse() print(a) # [1234.5, 333, 237, 66.25, 1]
true
1f3aaa0e48d787f2b1ec361d800cbc8d4606c7af
wicarte/492
/a3.py
845
4.125
4
#Assignment 3 (W3D4) - William Carter #What I think will happen before running the code: #I think the code prompts the user to enter a number, casts #the number as an int, counts up by 1 on the interval (2, user #provided number), and prints whenever the outer loop iterator (i) #is not cleanly divisible by the inner loop iterator (k). n = input("Please enter a number as an upper limit: ") n = int(n) for i in range(2, n): check_var = True for k in xrange(2, i): if (i%k) == 0: check_var = False if check_var: print(i) #After running the code: #A number is printed out and another number is printed out as many times #as the first number's value. For example, if 5 is printed out and 7 #is the next number to be printed, 7 will print 5 different times. #This pattern continues until the upper bound provided by the user #is reached.
true
06e3854ec42cb507701909da375a8e2f6dc62ab7
Pissuu/6thsempython
/simplecalc.py
480
4.15625
4
print("simple calculator") print(" enter 1 for *") print(" enter 2 for /") print(" enter 3 for +") print(" enter 4 for -") choice=int(input()) ans=int a1=int(input("enter first argument")) a2=int(input("enter second argument")) if choice==1: ans=a1*a2 print("answer is:",ans) if choice==2: ans=a1/a2 print("answer is:",ans) if choice==3: ans=a1+a2 print("answer is:",ans) if choice==4: ans=a1-a2 print("answer is",ans)
false
1a948637866f58b51f76d1b69c070d67a6a615c8
nbenkler/CS110_Intro_CS
/HW #5/untitled folder/convertFunctions.py
955
4.15625
4
# Program to read file HW5_Input.txt and convert characters in the file to their unicode, hexadecimal, and binary representations. #Noam Benkler #2/12/18 def fileIngest(fileName): inFile = open(fileName, "r") return inFile inFile.close() def conversionOutput(file): for line in file: full = (line) character = (full[0]) unicode = uniConversion(character) hexadecimal = hexConversion(unicode) binary = binConversion(unicode) output = str("The Character "+str(character)+" is encoded as "+str(unicode)+" in Unicode, which is "+str(hexadecimal)+" in hexadecimal and "+str(binary)+" in binary.") print (output) def uniConversion(alphanum): uni = ord(alphanum) return uni def hexConversion(alphanum): hexa = hex(alphanum) [2:] return hexa def binConversion(alphanum): bina = bin(alphanum) [2:] return bina def main(): fileName = "HW5_input.txt" conversionFile = fileIngest(fileName) conversionOutput(conversionFile) main()
true
590d5ad63a0fcf7f0f27a6352051093acfc9923c
nbenkler/CS110_Intro_CS
/Lab 3/functions.py
1,026
4.4375
4
'''function.py Blake Howald 9/19/17, modified for Python 3 from original by Jeff Ondich, 25 September 2009 A very brief example of how functions interact with their callers via parameters and return values. Before you run this program, try to predict exactly what output will appear, and in what order. You are trying to trace the movement of data throughout the program, and make sure you understand what happens when. This simple program is very important for you to understand. If you have figured it out, the rest of the term will be a lot easier than if you haven't. ''' def f(n): print(n) result = 3 * n + 4 return result def g(n): print(n) result = 2 * n - 3 return result number = 5 print('number = ', number) print() print('Experiment #1') answer = f(number) print('f(number) =', answer) print() print('Experiment #2') answer = g(number) print('g(number) =', answer) print() print('Experiment #3') answer = f(g(number)) print('f(g(number)) =', answer) print()
true
78ef5fc28e3f4ae7efc5ed523eeffe246496c403
alexmkubiak/MIT_IntroCS
/week1/pset1_2.py
413
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 24 18:00:03 2018 This code determines how many times the string 'bob' occurs in a string s. @author: Alex """ s = 'azcbobobegghakl' count = 0 index = 0 for index in s: if s[index] == 'b': if s[index + 1] == 'o': if s[index+2] == 'b': count += 1 print("Number of times bob occurs is: " + str(count))
true
9ecd69b1dc1bd808055cea00eabc82428dc12056
TheChuey/DevCamp
/range_slices_in_pythonList.py
982
4.3125
4
tags = [ 'python', 'development', 'tutorials', 'code', 'programing', 'computer science' ] #tags_range = tags[:-1:2] tags_range = tags[::-1] # reverses the oder of the list # slicing function print(tags_range) """ # Advanced Techniques for Implementing Ranges and Slices in Python Lists tag_range = tags[1:-1:2] # we want every other tag here (place in an interval) -inside the bracket you can pass in the third elemnt(interval(every other tag) the 2 takes every other element) tag_range = tags[::-1] #slicing -flip the entire order of the list- in bracket-reverse index values-remove second perameter #above-you would use this print(tag_range) #------------------------------------------------------------------------------ tags.sort(reverse=True) #sorting function looks at the alphabetical value-instead of the above example that pulls the index print(tags) //////////////////////////////////////////////////////////// """
true
fddd74d8a7cbb7641c3d0bfbfb2ee7901639d7f3
DyadushkaArchi/python_hw
/Python_hw_20.py
987
4.125
4
import random #========================================================================== #task 19 #========================================================================== #Написать функцию для поиска разницы сумм всех четных и всех нечетных чисел среди #100 случайно сгенерированных чисел в произвольном числовом диапазоне. #Т.е. от суммы четных чисел вычесть сумму нечетных чисел. def diff_even_odd(num_limit, lower_bound, upper_bound): # returns int even_number = 0 odd_number = 0 for i in range(num_limit): rand_number = random.randint(lower_bound, upper_bound) print("Rand.number:", rand_number) if rand_number % 2 == 0: even_number += rand_number else: odd_number += rand_number result = even_number - odd_number return result example = diff_even_odd(4, -20, 0) print(example)
false
09a4ae07c0b9e3c8d1604bfaea0ce58078d52936
asim09/Algorithm
/data-types/List/sort-list-of-string.py
256
4.1875
4
# Python Program to sort a list according to the length of the elements a = ['Apple', 'Ball', 'Cat', 'Ox'] for i in range(len(a)): for j in range(len(a) - i - 1): if len(a[j]) > len(a[j+1]): a[j], a[j+1] = a[j+1], a[j] print(a[-1])
true
234a8bc6f168afac7ab18c566b0a783e5e9080fd
prabalbhandari04/python_
/labexercise2.py
312
4.28125
4
#Write a program that reads the length of the base and the height of a right-angled triangle and prints the area. Every number is given on a separate line.# length_of_base = int(input("Enter the lenght of base:")) height = int(input("Enter the height:")) area = (1/2)*(length_of_base*height) print(area)
true
06fe1661b93a940e28adb9c5fab488df85e19eb8
ankush-phulia/Lift-MDP-Model
/simulator/Elevator.py
2,956
4.25
4
class Elevator(object): """ - state representation of the elevator """ def __init__(self, N, K): self.N = N # number of floors self.K = K # number of elevators # initial positions of all elevators self.pos = [0]*K # button up on each floor (always 0 for top floor) self.BU = [0]*N # button down on each floor (always 0 for first floor) self.BD = [0]*N # floor buttons pressed inside elevator, for each elevator self.BF = [[0]*N for i in range(K)] # light up indicator for each lift for its current floor (always 0 for top floor) self.LU = [0]*K # light down indicator for each lift for its current floor (always 0 for first floor) self.LD = [0]*K def __str__(self): """ - returns a string expression of the current state of the elevator """ state = '' state += ' '.join([str(x) for x in self.pos]) + ' ' state += ''.join([str(x) + ' ' + str(y) + ' ' for x, y in zip(self.BU, self.BD)]) for e in self.BF: state += ' '.join([str(x) for x in e]) state += ' ' state += ' '.join([str(x) for x in self.LU]) + ' ' state += ' '.join([str(x) for x in self.LD]) + ' ' return state # state modifiers def modify_pos(self, k, delta): """ - change position of kth lift by delta (+/- 1) - validity checks in Simulator """ self.pos[k] += delta def modify_floor_button(self, n, direction, status): """ - n : floor number - direction : 'U' for up button and 'D' for down button - status : 0 to clear and 1 to press - returns if status was toggled """ toggled = True if direction == 'U': if self.BU[n] == status: toggled = False self.BU[n] = status if direction == 'D': if self.BD[n] == status: toggled = False self.BD[n] = status return toggled def modify_elevator_button(self, k, n, status): """ - k : elevator number - n : floor number - status : 0 to clear and 1 to press - returns if status was toggled """ toggled = True if self.BF[k][n] == status: toggled = False self.BF[k][n] = status return toggled def reset_lights(self): self.LU = [0] * self.K self.LD = [0] * self.K def modify_lights(self, k, direction, status): """ - k : lift number - direction : 'U' for up button and 'D' for down button - status : 0 to clear and 1 to press """ if direction == 'U': self.LU[k] = status if direction == 'D': self.LD[k] = status
true
608c925a7bb0d43f25cbb24431020093dd0617c4
FefAzvdo/Python-Training
/Aulas/013.py
431
4.21875
4
# Estruturas de Repetição # Output: 1, 2, 3, 4, 5 for count in range(1, 6): print(count) # Executa 3x # Output: * * * for count in range(0, 3): print("*") for count in range(0, 11): if(count % 2 == 0): print(f"{count} é PAR") else: print(f"{count} é ÍMPAR") for count in range(6, 0, -1): print(count) n = int(input("Digite um número: ")) for count in range(0, n+1): print(count)
false
1218eb2a6ac77aecfdef4846500dc1623c58c418
FefAzvdo/Python-Training
/Exercicios/Aula 10/033.py
738
4.25
4
# Condição de existência de um triângulo # Para construir um triângulo não podemos utilizar qualquer medida, tem que seguir a condição de existência: # Para construir um triângulo é necessário que a medida de qualquer um dos lados seja menor que a soma das medidas dos outros dois e maior que o valor absoluto da diferença entre essas medidas. # | b - c | < a < b + c # | a - c | < b < a + c # | a - b | < c < a + b a = float(input("Digite o tamanho da primeira medida: ")) b = float(input("Digite o tamanho da segunda medida: ")) c = float(input("Digite o tamanho da terceira medida: ")) isTriangle = abs(b - c) < a < (b + c) if isTriangle: print("Forma um triângulo") else: print("Não forma um triângulo")
false
1d8df8f0fd6996602088725eaef8fb63429cdf99
mileshill/HackerRank
/AI/Bot_Building/Bot_Saves_Princess/princess.py
2,127
4.125
4
#!/usr/bin/env python2 """ Bot Saves Princess: Mario is located at the center of the grid. Princess Peach is located at one of the four corners. Peach is denoted by 'p' and Mario by 'm'. The goal is to make the proper moves to reach the princess Input: First line contains an ODD integer (3<=N<=99) denoting the size of the grid. The is followed by an NxN grid. Output: Print out the steps required to reach the princess. Each move will have the format "MOVE\n" Valid Moves: LEFT, RIGHT, UP, DOWN """ from sys import stdin, stdout r = stdin.readline def find_princess_position( grid_size ): """ Read the array to find princess """ assert type( grid_size ) is int for i in range( grid_size ): line = list(r().strip()) if 'p' in line: j = line.index('p') location = (j,i) return location def get_directions( x_peach, y_peach, x_mario, y_mario): """ Determine L/R U/D directions mario will travel """ horizontal_dir ='' vertical_dir = '' # horizontal direction if x_peach > x_mario: horizontal_dir = "RIGHT" else: horizontal_dir = "LEFT" # vertical direction if y_peach > y_mario: vertical_dir = "DOWN" else: vertical_dir = "UP" return (horizontal_dir, vertical_dir) def generate_marios_path( grid_size, location_of_princess ): """ Generate the steps to move to the princess """ grid_center = (grid_size -1)/2 + 1 distance_to_wall = grid_center -1 xp, yp = location_of_princess x_dir, y_dir = get_directions( xp, yp, xm, ym ) horizontal = [ x_dir for x in range(distance_to_wall)] vertical = [ y_dir for y in range(distance_to_wall) ] return horizontal + vertical def main(): grid_size = int( r().strip() ) location_of_princess = find_princess_position( grid_size ) marios_path = generate_marios_path( grid_size, location_of_princess ) assert type( marios_path ) is list for move in marios_path: stdout.write( move + '\n' ) if __name__ == '__main__': main()
true
f1d0eed5c88aff33508a9b32e9aaec1a3f962de3
rahulkumar1m/exercism-python-track
/isogram/isogram.py
528
4.3125
4
def is_isogram(string) -> bool: # Tokenizing the characters in the string string = [char for char in string.lower()] # initializing an empty list of characters present in the string characters = [] # if a character from string is already present in our list of characters, we return False for char in string: if (char == " ") or (char == "-"): continue elif char in characters: return False else: characters.append(char) return True
true
7912b115e12d200e6981cdbe55ca8c3175eba085
fangbz1986/python_study
/函数式编程/03filter.py
1,222
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Python内建的filter()函数用于过滤序列。 和map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。 filter()的作用是从一个序列中筛出符合条件的元素。由于filter()使用了惰性计算,所以只有在取filter()结果的时候,才会真正筛选并每次返回下一个筛出的元素。 ''' # 例如,在一个list中,删掉偶数,只保留奇数,可以这么写: def is_odd(n): return n % 2 == 1 a = filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]) print(type(a)) # filter print(list(a)) # filter # 把一个序列中的空字符串删掉,可以这么写: def not_empty(s): return s and s.strip() a = list(filter(not_empty, ['A', '', 'B', None, 'C', ' '])) print(a) ''' 可见用filter()这个高阶函数,关键在于正确实现一个“筛选”函数。 注意到filter()函数返回的是一个Iterator,也就是一个惰性序列,所以要强迫filter()完成计算结果,需要用list()函数获得所有结果并返回list '''
false
122a3f71dd406d2cea9d838e3fe1260cd0e3adcf
hardlyHacking/cs1
/static/solutions/labs/gravity/solution/system.py
2,283
4.21875
4
# system.py # Solution for CS 1 Lab Assignment 3. # Definition of the System class for gravity simulation. # A System represents several Body objects. # Based on code written by Aaron Watanabe and Devin Balkcom. UNIVERSAL_GRAVITATIONAL_CONSTANT = 6.67384e-11 from math import sqrt from body import Body class System: # To initialize a System, just save the body list. def __init__(self, body_list): self.body_list = body_list # Draw a System by drawing each body in the body list. def draw(self, cx, cy, pixels_per_meter): for body in self.body_list: body.draw(cx, cy, pixels_per_meter) # Compute the distance between bodies n1 and n2. def dist(self, n1, n2): dx = self.body_list[n2].get_x() - self.body_list[n1].get_x() dy = self.body_list[n2].get_y() - self.body_list[n1].get_y() return sqrt(dx * dx + dy * dy) # Compute the acceleration of all other bodies on body n. def compute_acceleration(self, n): total_ax = 0 total_ay = 0 n_x = self.body_list[n].get_x() n_y = self.body_list[n].get_y() for i in range(len(self.body_list)): if i != n: # don't compute the acceleration of body n on itself! r = self.dist(i, n) a = UNIVERSAL_GRAVITATIONAL_CONSTANT * self.body_list[i].get_mass() / (r * r) # a is the magnitude of the acceleration. # Break it into its x and y components ax and ay, # and add them into the running sums total_ax and total_ay. dx = self.body_list[i].get_x() - n_x ax = a * dx / r total_ax += ax dy = self.body_list[i].get_y() - n_y ay = a * dy / r total_ay += ay # To return two values, use a tuple. return (total_ax, total_ay) # Compute the acceleration on each body, and use the acceleration # to update the velocity and then the position of each body. def update(self, timestep): for n in range(len(self.body_list)): (ax, ay) = self.compute_acceleration(n) self.body_list[n].update_velocity(ax, ay, timestep) self.body_list[n].update_position(timestep)
true
490389021ee556bb98c72ae687389445ebb6dcb7
Andras00P/Python_Exercise_solutions
/31 - Guess_Game.py
855
4.46875
4
''' Build a simple guessing game where it will continuously ask the user to enter a number between 1 and 10. If the user's guesses matched, the user will score 10 points, and display the score. If the user's guess doesn't match, display the generated number. Also, if the user enters "q" stop the game. ''' import random print("Welcome to the Guessing Game! \n\n") print("Enter the letter q, to quit.\n") score = 0 while True: npc = random.randint(0, 10) print("Guess a number between 0 and 10.") n = input("What's your guess? \n") if n == "q": print("\nGame Over!") break num = int(n) if num is npc: score += 10 print("Your guess was correct!\n") print(f"You currently have {score} points\n") else: print(f"The number was {npc}\n")
true
1312a36aee5ceebbb32beedfef010210a5bb19bb
Andras00P/Python_Exercise_solutions
/18 - Calculate_Grades.py
871
4.21875
4
''' Calculate final grade from five subjects ''' def grades(a, b, c, d, e): avg_grade = int((a + b + c + d + e) / 5) f_grade = "" if avg_grade >= 90: f_grade = "Grade A" elif avg_grade >= 80: f_grade = "Grade B" elif avg_grade >= 70: f_grade = "Grade C" elif avg_grade >= 60: f_grade = "Grade D" else: f_grade = "Grade F" return f_grade, avg_grade grade_a = int(input("Enter the subject a grade: \n\n")) grade_b = int(input("Enter the subject b grade: \n\n")) grade_c = int(input("Enter the subject c grade: \n\n")) grade_d = int(input("Enter the subject d grade: \n\n")) grade_e = int(input("Enter the subject e grade: \n\n")) final_grade, final_score = grades(grade_a, grade_b, grade_c, grade_d, grade_e) print(f"Your Final grade is: {final_grade}, {final_score}")
false
3607e93c5431e03789f3f980fd2220c4a8dc9b10
Andras00P/Python_Exercise_solutions
/24 - Reverse_String.py
443
4.375
4
""" Reverse a string. If the input is: Hello World. The output should be: .dlroW olleH """ def reverse_string(text): result = "" for char in text: result = char + result return result # Shortcut def reverse_string2(text): return text[::-1] usr_text = input("Write the text, you want to reverse: \n") print("Reversed: \n", reverse_string(usr_text) + "\n", reverse_string2(usr_text))
true
a5fd62036f3dd8a6ec226ffae14b48c6c5ab06ca
Andras00P/Python_Exercise_solutions
/21 - Check_Prime.py
357
4.21875
4
''' For a given number, check whether the number is a prime number or not ''' def is_prime(num): for i in range(2, num): if (num % i) == 0: return False return True usr_num = int(input("Enter number: \n")) if is_prime(usr_num): print("The number is a Prime") else: print("The number is not a Prime")
true
06afe217a85fc98b1689ac6e6119a118fe91f9b5
garciacastano09/pycourse
/intermediate/exercises/mod_05_iterators_generators_coroutines/exercise.py
2,627
4.125
4
#-*- coding: utf-8 -*- u''' MOD 05: Iterators, generators and coroutines ''' def repeat_items(sequence, num_times=2): '''Iterate the sequence returning each element repeated several times >>> list(repeat_items([1, 2, 3])) [1, 1, 2, 2, 3, 3] >>> list(repeat_items([1, 2, 3], 3)) [1, 1, 1, 2, 2, 2, 3, 3, 3] >>> list(repeat_items([1, 2, 3], 0)) [] >>> list(repeat_items([1, 2, 3], 1)) [1, 2, 3] :param sequence: sequence or iterable to iterate over :param num_times: number of times to repeat each item :returns: generator with each element of the sequence repeated ''' for i in sequence: rep=num_times while rep>0: yield i rep-=1 continue def izip(*sequences): '''Return tuples with one element of each sequence It returns as many pairs as the shortest sequence The same than std lib zip function >>> list(izip([1, 2, 3], ['a', 'b', 'c'])) [[1, 'a'], [2, 'b'], [3, 'c']] >>> list(izip([1, 2, 3], ['a', 'b', 'c', 'd'])) [[1, 'a'], [2, 'b'], [3, 'c']] :param sequences: two or more sequences to loop over :returns: generator returning tuples with the n-th item of input sequences ''' if len(sequences) > 0: tuples_len = min(int(i) for i in map(lambda x: len(x), sequences)) else: yield [] return for index in range(0, tuples_len): result_element = [] for sequence in sequences: result_element.append(sequence[index]) yield result_element def merge(*sequences): '''Iterate over all sequences returning each time one item of one of them Always loop sequences in the same order >>> list(merge([None, True, False], ['a', 'e', 'i', 'o', 'u'])) [None, 'a', True, 'e', False, 'i', 'o', 'u'] >>> list(merge(['a', 'e', 'i', 'o', 'u'], [None, True, False])) ['a', None, 'e', True, 'i', False, 'o', 'u'] >>> list(merge(['a', 'e', 'i', 'o', 'u'], [None, True, False], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])) ['a', None, 0, 'e', True, 1, 'i', False, 2, 'o', 3, 'u', 4, 5, 6, 7, 8, 9] :param sequences: two or more sequences to loop over :returns: generator returning one item of each ''' iterators = map(iter, sequences) while sequences: yield map(iter) def flatten(L): '''flatten the input list of lists to a flattened list >>>list(flatten([1, 2, [3]]) [1, 2, 3] >>>list(flatten([1, 2, [3, 4], [[5]]) [1, 2, ,3 ,4 ,5] :param L: list of lists :returns: generator with flattened list ''' yield None
true
014e36604daf04ec73c663fe223cd445fcd01ca5
garciacastano09/pycourse
/advanced/exercises/mod_05_functools/exercise_mod_05.py
585
4.25
4
#!/usr/bin/env python #-*- coding: utf-8 -*- u""" Created on Oct 5, 2013 @author: pablito56 @license: MIT @contact: pablito56@gmail.com Module 05 functools exercise >>> it = power_of(2) >>> it.next() 1 >>> it.next() 2 >>> it.next() 4 >>> it.next() 8 >>> it.next() 16 >>> it = power_of(3) >>> it.next() 1 >>> it.next() 3 >>> it.next() 9 """ from itertools import imap, count def power_of(x): """Generator returning powers of the provided number """ # Try to use imap and count (from itertools module) # You MUST use pow function in this exercise return count(1)
true
c3d462c1e5cd9bb28a67ee54f8f80c03ec14f06a
ACEinfinity7/Determinant2x2
/deter_lib.py
792
4.125
4
def deter2x2(matrix): """ function to calculate the determinant of the 2x2 matrix. The determinant of a matrix is defined as the upper-left element times the lower right element minus the upper-right element times the lower left element """ result = (matrix[0][0]*matrix[1][1])-(matrix[0][1]*matrix[1][0]) # TODO: calculate the determinant of the 2x2 matrix return result def deter3x3(matrix): a = matrix[0][0] b = matrix[0][1] c = matrix[0][2] d = matrix[1][0] e = matrix[1][1] f = matrix[1][2] g = matrix[2][0] h = matrix[2][1] i = matrix[2][2] result = (a*e*i) - (a*f*h) - (b*d*i) + (b*f*g) + (c*d*h) - (c*e*g) return result matrix_test = [[4,1,3],[5,3,1],[8,4,2]] print(deter3x3(matrix_test))
true
e354f576673621e8dc851bda02d495a5196f9f7d
mitchellflax/lpsr-samples
/3-6ATkinterExample/remoteControl.py
464
4.28125
4
import turtle from Tkinter import * # create the root Tkinter window and a Frame to go in it root = Tk() frame = Frame(root, height=100, width=100) # create our turtle shawn = turtle.Turtle() # make some simple buttons fwd = Button(frame, text='fwd', fg='red', command=lambda: shawn.forward(50)) left = Button(frame, text='left', command=lambda: shawn.left(90)) # put it all together fwd.pack(side=LEFT) left.pack(side=LEFT) frame.pack() turtle.exitonclick()
true
ed15cbf4fd067d8b9c8194d22b795cb55005797f
mitchellflax/lpsr-samples
/ProblemSets/PS5/teamManager.py
1,525
4.3125
4
# a Player on a team has a name, an age, and a number of goals so far this season class Player(object): def __init__(self, name, age, goals): self.name = name self.age = age self.goals = goals def printStats(self): print("Name: " + self.name) print("Age: " + str(self.age)) print("Goals: " + str(self.goals)) # default doesn't matter, we'll set it again user_choice = 1 my_players = [] while user_choice != 0: print("What do you want to do? Enter the # of your choice and press Enter.") print("(1) Add a player") print("(2) Print all players") print("(3) Print average number of goals for all players") print("(0) Leave the program and delete all players") user_choice = int(raw_input()) # if the user wants to add a player, collect their data and make a Player object if user_choice == 1: print("Enter name:") player_name = raw_input() print("Enter age:") player_age = int(raw_input()) print("Enter number of goals scored this season:") player_goals = int(raw_input()) my_players.append(Player(player_name, player_age, player_goals)) print("Ok, player entered.") # if the user wants to print the players, call printStats for each Player if user_choice == 2: print("Here are all the players...") for player in my_players: player.printStats() if user_choice == 3: # average = sum of all goals divided by count of players sum = 0 count = 0 for player in my_players: sum += player.goals count += 1 avg = sum / count print("Average goals: " + str(avg))
true
505b7944e773905bd8b1c5c8be4ce6d9a3b58730
mitchellflax/lpsr-samples
/4-2WritingFiles/haikuGenerator2.py
1,548
4.3125
4
# haikuGenerator.py import random # Ask the user for the lines of the haiku print('Welcome to the Haiku generator!') print('Would you like to write your haiku from scratch or get a randomized first line?') print('(1) I\'ll write it from scratch') print('(2) Start me with a random line') user_choice = int(raw_input()) # if the user wants to write from scratch, keep it simple if user_choice == 1: print('Provide the first line of your haiku:') haiku_ln1 = raw_input() # if the user is into getting a random starter, we have some work to do else: # open the rando file and bring in the random lines starters_file = open('haikuStarters.txt', 'r') starters_list = [] # get the starter lines and add them to a list line = starters_file.readline() while line: starters_list.append(line) line = starters_file.readline() # spit the line back to the user print('All right, here\'s your first line:') haiku_ln1 = starters_list[random.randint(0,len(starters_list))] print(haiku_ln1) print('Provide the second line of your haiku:') haiku_ln2 = raw_input() print('Provide the third line of your haiku:') haiku_ln3 = raw_input() # Ask the user for the filename print('What file would you like to write your haiku to?') filename = raw_input() # Write the haiku to a file my_file = open(filename, 'w') my_file.write(haiku_ln1 + '\n') my_file.write(haiku_ln2 + '\n') my_file.write(haiku_ln3 + '\n') # Success! Close the file. my_file.close() print("Done! To view your haiku, type 'cat' and the name of your file at the command line.")
true
7e13745a73f6d77bbebcc267c0d4481ba6a86d3a
mitchellflax/lpsr-samples
/3-4FunctionsInTurtle/samplePatternTemplate.py
495
4.25
4
# samplePattern.py import turtle # myTurtle is a Turtle object # side is the length of a side in points def makeTriangle(myTurtle, side): pass # make our turtle kipp = turtle.Turtle() kipp.forward(150) kipp.right(180) # kipp makes triangles centered at a point that shifts # and decreases in size with each loop length = 100 while length > 0: makeTriangle(kipp, length) kipp.forward(3) # make the sides shorter length = length - 1 # wait to exit until I've clicked turtle.exitonclick()
true
f9f2cbd0408139865c1cb412a80c1d60b5cc038c
Brian-Musembi/ICS3U-Unit6-04-Python
/array_average.py
1,839
4.1875
4
#!/usr/bin/env python3 # Created by Brian Musembi # Created on June 2021 # This program prints a 2D array and finds the average of all the numbers import random def average_2D(list_2D): # This function finds the average total = 0 rows = len(list_2D) columns = len(list_2D[0]) for row_value in list_2D: for value in row_value: total += value average = total / (rows * columns) return average def main(): # This function handles input and prints a 2D array print("This program prints a 2D array and finds the average " "of all numbers.") print("") list_2D = [] # input while True: try: rows_input = input("Input the number of rows you want: ") rows = int(rows_input) columns_input = input("Input the number of columns you want: ") columns = int(columns_input) print("") # check for negative numbers if rows > 0 and columns > 0: for loop_counter_rows in range(0, rows): temp_column = [] for loop_counter_columns in range(0, columns): random_num = random.randint(0, 50) temp_column.append(random_num) print("{0} ".format(random_num), end="") list_2D.append(temp_column) print("") average_of_array = average_2D(list_2D) average_rounded = '{0:.5g}'.format(average_of_array) print("") print("The average of all the numbers is: {0}" .format(average_rounded)) break except Exception: # output print("Enter a number for both values, try again.") if __name__ == "__main__": main()
true
c054b2383fd5b7d7a042d69673d2708aef9be0b1
coreman14/Python-From-java
/CPRG251/Assignment 6/Movie.py
2,090
4.40625
4
class Movie(): def __init__(self, mins:int, name:str, year:int): """Creates an object and assign the respective args Args: mins (int): Length of the movie name (str): Name of the movie year (int): Year the movie was released """ self.mins = mins self.year = year self.name = name def getYear(self): """Returns the year of the movie Returns: int: The year of the movie """ return self.year; def setYear(self, year): """Sets the year of the movie Args: year (int): The year of the movie """ self.year = year; def getMins(self): """Returns the length of the movie in minutes Returns: int: The length of the movie """ return self.mins; def setMins(self,mins): """Sets the length of the movie in minutes Args: mins (int): The length of the movie """ self.mins = mins; def getName(self): """Returns the name of the movie Returns: str: The name of the movie """ return self.name; def setName(self, name): """Sets the name of the movie Args: name (str): The name of the movie """ self.name = name; def __str__(self): """Returns a formatted string for output Returns in order of (Mins,Year,Name) Returns: str: A string for output in a list (Mins,Year,Name) """ return f"{self.getMins():<15}{self.getYear():<6}{self.getName()}" def formatForFile(self): """Returns the movie in a csv format Returns in order of (Mins,Name,Year) Returns: str: The movie in a CSV format (Mins,Name,Year) """ return f"{self.getMins()},{self.getName()},{self.getYear()}\n"
true
34d705727c44475ce5c1411558760a01969ef75b
Syvacus/python_programming_project
/Session number 2.py
2,246
4.1875
4
# Question 1 # Problem: '15151515' is printed because the chairs variable is text instead of a number # Solution: Convert the chairs variable from text to number chairs = '15' # <- this is a string (text) rather than an int (number) nails = 4 total_nails = int(chairs) * nails # <- convert string to int by wrapping it in the int() function message = 'I need to buy {} nails'.format(total_nails) print(message) #my solution nails = 4 chairs = 15 total_nails = nails * chairs message = "I _need _to _buy" + str (total_nails) +"nails" print(message) # Question 2 # Problem: When the code is run, we get a error: 'NameError: name 'Penelope' is not defined' # this is because Python is interpreting Penelope as a variable, rather than a string # Solution: To store text, it needs to be enclosed in either '{text}' or "{text}" my_name = 'Penelope' # <- store the name as text by enclosing in single or double quotes my_age = 29 message = 'My name is {} and I am {} years old'.format(my_name, my_age) print(message) #my solution my_name = "Penelope" my_age = 29 message = (my_name, my_age) print(message) # Question 3 # Task: I have a lot of boxes of eggs in my fridge and I want to calculate how many omelettes I can make. # Write a program to calculate this. # Assume that a box of eggs contains six eggs and I need four eggs for each omelette, but I should be # able to easily change these values if I want. The output should say something like "You can make 9 # omelettes with 6 boxes of eggs". boxes = 7 eggs_per_box = 6 eggs_per_omelette = 4 total_number_of_eggs = boxes * eggs_per_box # Calculate whole number of omelettes number_of_whole_omelettes = total_number_of_eggs // eggs_per_omelette left_over_eggs = total_number_of_eggs % eggs_per_omelette message = 'Using {} boxes of eggs, you can make {} whole omelettes, with {} eggs left over.' print(message.format(boxes, number_of_whole_omelettes, left_over_eggs)) # Calculate number of omelettes (as a decimal) number_of_decimal_omelettes = total_number_of_eggs / eggs_per_omelette message = 'Using {} boxes of eggs, you can make {} omelettes.' print(message.format(boxes, number_of_decimal_omelettes))
true
acab7dba850041e5b5283d1a661a00a76b17a8c1
NapsterZ4/python_basic_course
/tuplas.py
492
4.1875
4
# listas que no pueden modificarse a = (1, 4, 5.6, "Juan", 6, "Maria") b = ["Jorge", 5, "Peru", 90] tup2 = 34, "Javier", 9.6, "Murillo" c = tuple(b) # Convirtiendo la lista en tupla d = list(a) # Conviertiendo la tupla en una lista print(tup2) print(a) print(c) # Resultado de la lista convertida en tupla print(d) # Resultado de la tupla convertida en lista print("Elementos de la tupla: ", len(a)) # Contar elementos de la tupla print("Posicion de un elemento en la tupla: ", d[4])
false
95d7dd2afe45d705d1bbb3884245e1258651f0c0
DHANI4/NUMBER-GUESSING-GAME
/NumberGuessing.py
443
4.28125
4
import random print("Number Guessing Game") rand=random.randint(1,20) print("Guess a Number between 1-20") chances=0 while(chances<5): chances=chances+1 guess=int(input("Enter Your Guess")) if(guess==rand): print("Congratulations You Won!!") break elif(guess<rand): print("Guess a number higher") else: print("Guess a number lesser") if not chances<5: print("You Loose")
true
949b939ef934fb793119900d36b377d7069c1916
vivianlorenaortiz/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/4-print_square.py
345
4.3125
4
#!/usr/bin/python3 """ Funtion that prints a square with the character #. """ def print_square(size): """ Function print square. """ if type(size) is not int: raise TypeError("size must be an integer") elif size < 0: raise ValueError("size must be >= 0") for i in range(size): print(size * "#")
true
809e7e3a4be9be995241c67909ae61fc5796d98d
drummerevans/Vector_Multiply
/cross_input.py
564
4.125
4
import numpy as np items = [] max = 3 while len(items) < max: item = input("Add an element to the list: ") items.append(int(item)) print("The length of the list is now increased to {:d}." .format(len(items))) print(items) things = [] values = 3 for i in range(0, values): thing = input("Add an element to the second list: ") things.append(int(thing)) print("The length of the second list is now increased to {:d}. " .format(len(things))) print(things) z = np.cross(items, things) print("The cross product of the two lists are: ", z)
true
44a4dda12809ebd8ba6e3c6c52c96e130a0fa7e1
PrateekMinhas/Python
/assignment14.py
1,555
4.4375
4
Q.1- Write a python program to print the cube of each value of a list using list comprehension. lst=[1,2,3,4,5] lstc=[i**3 for i in lst] print(lstc) #Q.2- Write a python program to get all the prime numbers in a specific range using list comprehension. lst_pr= [ i for i in range(2,int(input("Enter the end input of the range for the prime numbers"))) if all(i%j!=0 for j in range(2,i)) ] #all returns true if all items in a seq are true print(lst_pr) #Q.3- Write the main differences between List Comprehension and Generator Expression. """generator expression uses () while list comprehension uses [] list comprehension returns a list that we can iterate and access via index but same is not the case in generator expression""" #LAMBDA & MAP #Q.1- Celsius = [39.2, 36.5, 37.3, 37.8] Convert this python list to Fahrenheit using map and lambda expression. Celsius = [39.2, 36.5, 37.3, 37.8] far=list(map(lambda i:(i * (9/5)) + 32,Celsius)) print(far) #Q.2- Apply an anonymous function to square all the elements of a list using map and lambda. lst1=[10,20,30,40,50] lstsq=list(map(lambda i:i**2,lst1)) print(lstsq) #FILTER & REDUCE #Q.1- Filter out all the primes from a list. lis3 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] for m in range(2, 18): lis3 = list(filter(lambda x: x == m or x % m and x > 1, lis3)) print(lis3) #Q.2- Write a python program to multiply all the elements of a list using reduce. from functools import reduce lis4 = [1,2,3,4,5,6,7,8,9,10] mul = reduce(lambda x, y: x*y,lis4) print(mul)
true
cc1aa3c2ec38ffc869b942af0491d3c44baf9ba1
PrateekMinhas/Python
/assignment3.py
2,048
4.25
4
#Q.1- Create a list with user defined inputs. ls=[] x=int(input("enter the number of elements")) for i in range (x): m=input() ls.append(m) print (ls) #Q.2- Add the following list to above created list: #[‘google’,’apple’,’facebook’,’microsoft’,’tesla’] ls1=['google','apple','facebook','microsoft','tesla'] ls.extend(ls1) print(ls) #Q.3 - Count the number of time an object occurs in a list. ls2=[1,2,3,3,'rabbit',',','$','$',4,7] x = input("enter an element from the string to know its occurence in it") print (ls2.count(x)) #Q.4 - create a list with numbers and sort it in ascending order. ls3=[1,2,45,6,8,4,3,6,8,9,0,8,67,-4] ls3.sort() print (ls3) #Q.5 - Given are two one-dimensional arrays A and B which are sorted in ascending order. #Write a program to merge them into a single sorted array C that contains every item from #arrays A and B, in ascending order. [List] A=[1,3,4,6,7,-8,-98] B=[1,4,5,3,6,56,33,23] C=[12,34,5] A.sort() #sorts A B.sort() #sorts B C.sort() #sorts C A.extend(B) #adds b to A C.extend(A) #adds new A to C C.sort() #sorts the new C print(C)#prints C #Q.6 - Count even and odd numbers in that list. odd=[] even=[] for y in C: if y%2==0: even.append(y) else: odd.append(y) print ("even numbers are ",len(even)) print ("odd numbers are ",len(odd)) #TUPLE #Q.1-Print a tuple in reverse order. tup=('apple','mango','banana') rev=reversed(tup) print(tuple(rev)) #Q.2-Find largest and smallest elements of a tuples. tup1=(1,2,4,5,6,78,-90) print(max(tup1)) print(min(tup1)) #STRINGS #Q.1- Convert a string to uppercase. string='im so sister shook ryt now !!' print (string.upper()) #Q.2- Print true if the string contains all numeric characters. string2=str(input("enter a string")) print (string2.isdigit()) #Q.3- Replace the word "World" with your name in the string "Hello World". string3='Hello World' print(string3.replace('World','Prateek Minhas'))
true
cef5dd3e9ca6fe8f9ce33b6e4f8aca9e35f368f4
0xch25/Data-Structures
/2.Arrays/Problems/Running sum of 1D Array.py
497
4.21875
4
'''Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). Return the running sum of nums. Example 1: Input: nums = [1,2,3,4] Output: [1,3,6,10] Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]''' def runningSum(nums): sum =0 for i in range(len(nums)): temp=nums[i] nums[i] =nums[i] +sum sum+=temp return nums nums=[1,1,1,1,1] nums2=[1,2,3,4] print(runningSum(nums)) print(runningSum(nums2))
true
7816262c0cda16be8c7d255780fba2c1203905a8
0xch25/Data-Structures
/3.Stacks/Palindrome using Stacks.py
544
4.15625
4
'''Program to check weather the given string is palindrome or not''' class Stack: def __init__(self): self.items = [] def push(self, data): self.items.append(data) def pop(self): return self.items.pop() def is_empty(self): return self.items == [] s = Stack() str= input("enter the string:") for char in str: s.push(char) str2="" while not s.is_empty(): str2 = str2 + s.pop() if str == str2: print('The string is a palindrome') else: print('The string is not a palindrome')
true
e70a83469f49d7f0dcb0ce94f8621e1b8b032836
0xch25/Data-Structures
/10.Strings/Problems/Shuffle String.py
776
4.1875
4
''' Given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string. Return the shuffled string. Example 1: Input: s = "codeleet", indices = [4,5,6,7,0,2,1,3] Output: "leetcode" Explanation: As shown, "codeleet" becomes "leetcode" after shuffling. Example 2: Input: s = "abc", indices = [0,1,2] Output: "abc" Explanation: After shuffling, each character remains in its position. Example 3: Input: s = "aiohn", indices = [3,1,4,2,0] Output: "nihao" ''' def restoreString(s,indices): res = [" "] * len(s) for i in range(len(s)): res[indices[i]] = s[i] return "".join(res) s = "aiohn" indices = [3,1,4,2,0] print(restoreString(s,indices))
true
4f45c92ee32651269b186c7ac51ce7897ed1ab1c
memuller/bunnyscript
/Python/14-lists-index.py
473
4.125
4
# -*- coding: utf-8 -*- ''' Faça um programa exatamente como o anterior, mas que possua um for no qual a variável de controle represente o índice de cada elemento, ao invés de o elemento em si. for i blabla: #aqui i deve ser o índice de cada elemento ''' # len(lista) # retorna a quantidade de elementos de uma lista, string, etc i=0 lista="eu gosto de você", "eu gosto de barcos grandes" for i in range(0,len(lista)): print "{}: {}".format(i+1, lista[i])
false
e30453364c48bdf2673d717cbd4ec9e06eca6581
memuller/bunnyscript
/Python/17-list-duplicates.py
892
4.125
4
# -*- coding: utf-8 -*- ''' Escreva um programa que leia palavras fornecidas pelo usuário. Caso a palavra não tenha sido fornecida anteriormente, a adicionamos em uma lista. Paramos de ler palavras quando o usuário não inserir nenhuma. Ao final do programa, imprimimos a lista das palavras não-repetidas inseridas. ''' i=0 words=list() word=raw_input("Digite uma palavra: ") words.append(word) while "uma coisa" != "outra coisa": insira=True word=raw_input("Digite uma palavra: ") if(word == ""): break for i in range(0,len(words)): if word == words[i]: insira=False if insira: words.append(word) # works well enough. mas novamente, posso só #...assumir que sempre quero inserir a palavra que estou lendo agora. # o loop me faz mudar de idéia ou não, mas a cada nova palavra # estou disposto a inserir. print words
false
355a3568f845a02c8c3af90bf627ea2a207d7b84
ndri/challenges
/old/33.py
1,139
4.125
4
#!/usr/bin/env python # 33 - Area Calculator import sys try: shape, args = sys.argv[1], ' '.join(sys.argv[2:]) except: sys.exit('Error. Use -h for help.') if shape == '-h': print 'Challenge 33 - Area Calculator' print '-h\t\t\tDisplay this help' print '-r width height\t\tArea for a rectangle' print '-c radius\t\tArea for a circle' print '-t base height\t\tArea for a triangle' elif shape == '-r': try: width, height = args.split()[:2] area = float(width) * float(height) print 'The area of this rectangle is {0:.4}'.format(area) except: print 'Usage: -r width height' elif shape == '-c': try: radius = float(args.split()[0]) area = 3.14159265358 * radius**2 print 'The area of this circle is {0:.4}'.format(area) except: print 'Usage: -c radius' elif shape == '-t': try: base, height = args.split()[:2] area = 0.5 * float(base) * float(height) print 'The area of this triangle is {0:.4}'.format(area) except: print 'Usage: -t base height' else: print 'Error. Use -h for help.'
true
e416d465ae64dad5353d431d099ff1fab5e801cf
CodingPirates/taarnby-python
/uge1/5_lister.py
2,203
4.125
4
#coding=utf8 # Når vores programmer bliver lidt mere komplicerede får vi rigtig mange variable # Det gør at de bliver mere og mere besværlige at læse # Nogle gange så hænger flere af de variable sammen # Så kan vi prøve at lave dem om til en enkelt variabel som gemmer på mere end én ting ad gangen # Den mest simple hedder en liste minshoppingliste = ["1 kg mel","2 liter mælk","3 skumfiduser"] print("Min shoppingliste lyder: "+str(minshoppingliste)) # Det ser ikke særlig pænt ud, men det er også ok # Når vi bruger lister, så plukker vi enkelte ting ud ad gangen # Det gør vi med at bruge firkantede parenteser # minshoppingliste[<nummer>] giver os et element fra listen print("Det første på listen er "+minshoppingliste[0]) print("Det tredie på listen er "+minshoppingliste[2]) print("Det andet på listen er "+minshoppingliste[1]) # Hov! Der står 2 hvor vi skal tage det tredie element # Jep, den er god nok. Computere tæller altid fra 0, så det kan vi lige så godt vænne os til # Vi kan også bruge variable når vi vælger fra listerne: nummer = 0 print("Element nummer "+str(nummer) + " på listen er: " + minshoppingliste[nummer]) print("") # Prøv at lave om på "nummer" og se hvad der sker # Vi kan også lave andre slags lister. For eksempel "dict", som er en slags ordbog # En dict er god til at gemme ting hvor rækkefølgen er ligegyldig # I stedet for en firkantet parentes bruger vi en krøllet (Tuborg) parentes # Hvert element i listen gemmes som en nøgle og en værdi med kolon imellem mitfodboldhold = {"målmand" : "P. Schmeichel", "højre back" : "P. Ninkov", "angriber" : "C. Ronaldo"} print("Holdets målmand er: "+mitfodboldhold["målmand"]) print("Holdets højre back er: "+mitfodboldhold["højre back"]) print("Holdets angriber er: "+mitfodboldhold["angriber"]) print("") # Vi kan godt lave om på dele af holdet uden at starte forfra mitfodboldhold["målmand"] = "J. Hart" print("Holdets nye målmand er: "+mitfodboldhold["målmand"]) print("Holdets højre back er: "+mitfodboldhold["højre back"]) print("Holdets angriber er: "+mitfodboldhold["angriber"]) print("") # Øvelse: Lav en liste over jeres yndlingsbøger og print ud til skærmen
false
42096d931802f6a0edcfa5702f2a91d0bbba2cd5
LaloGarcia91/CrackingTheCodingInterview
/Chapter_1/CheckPermutation.py
775
4.125
4
class CheckPermutation: def __init__(self, str1, str2): self.checkIfIsPermutation(str1, str2) def checkIfIsPermutation(self, str1, str2): str1_len = len(str1) str2_len = len(str2) if str1_len == str2_len: counterIfEqualLetters = 0 for str1_letter in str1: if str1_letter in str2: counterIfEqualLetters += 1 else: print("It is NOT a permutation") return False if counterIfEqualLetters == str1_len: print("It IS a permutation") return True else: print("Words are not even the same length") # run exercise CheckPermutation("HELLO", "HLLEO")
true
cfaef8bea20c252652c22f58e5c0b569b46312e4
miawich/repository_mia
/Notes/NotesB/05_sorting_miawich.py
2,149
4.21875
4
# sorting import random import time # swapping values a = 1 b = 2 temp = a a = b b = temp print(a, b) # pythonic way a, b = b, a # works only in python # selection sort my_list = [random.randrange(1, 100) for x in range(100)] my_list_2 = my_list[:] my_list_3 = my_list[:] print(my_list) print() for cur_pos in range(len(my_list)): min_pos = cur_pos for scan_pos in range(cur_pos + 1, len(my_list)): if my_list[scan_pos] < my_list[min_pos]: min_pos = scan_pos my_list[cur_pos], my_list[min_pos] = my_list[min_pos], my_list[cur_pos] print(my_list) # insertion sort for key_pos in range(1, len(my_list_2)): key_val = my_list_2[key_pos] # key dancer scan_pos = key_pos - 1 # looking to the dancer to the left while scan_pos >= 0 and key_val < my_list_2[scan_pos]: my_list_2[scan_pos + 1] = my_list_2[scan_pos] # move the scan position left scan_pos -= 1 my_list_2[scan_pos + 1] = key_val # commit the move print(my_list_2) my_list_3.sort() # much quicker!!! print(my_list_3) # optional function parameters print("Hello", end=" ") print("World", end=" ") print("Hello", "World", sep="Big", end="!!!\n") def hello(name, time_of_day="morning"): print("hello", name, "good", time_of_day) hello("mia") # lambda function # when you need a function, but dont want to make a function # also called anonymous function # lambda= parameter: return double_me = lambda x: x * 2 print(double_me(5)) product = lambda a, b: a * b my_list = [random.randrange(1, 100) for x in range(100)] print(my_list) print() my_2dlist = [[random.randrange(1, 100) , random.randrange(1, 100)] for x in range(100)] print(my_2dlist) print() # sort method(change the list in place) my_list.sort() print(my_list) my_list.sort(reverse=True) print(my_list) print() my_2dlist.sort(key=lambda a: a[0]) print(my_2dlist) print() my_2dlist.sort(key=lambda a: a[1]) print(my_2dlist) print() my_2dlist.sort(reverse=True, key=lambda a: sum(a)) print(my_2dlist) print() # sorted function (returns a new list) new_list = sorted(my_2dlist, reverse=True, key=lambda x: abs(x[0] - x[1])) print(new_list)
false
13550a3bd2b683327b96a2676f5d006b69353b73
AndreiBratkovski/CodeFights-Solutions
/Arcade/Intro/Smooth Sailing/isLucky.py
614
4.21875
4
""" Ticket numbers usually consist of an even number of digits. A ticket number is considered lucky if the sum of the first half of the digits is equal to the sum of the second half. Given a ticket number n, determine if it's lucky or not. Example For n = 1230, the output should be isLucky(n) = true; For n = 239017, the output should be isLucky(n) = false. """ def isLucky(n): n_list = [int(i) for i in str(n)] half = int((len(n_list)/2)) list1 = n_list[:half] list2 = n_list[half:] if sum(list1) == sum(list2): return True else: return False
true
27f090cb703d12372205b7308efe17f5e0a73980
AndreiBratkovski/CodeFights-Solutions
/Arcade/Intro/Smooth Sailing/commonCharacterCount.py
718
4.34375
4
""" Given two strings, find the number of common characters between them. Example For s1 = "aabcc" and s2 = "adcaa", the output should be commonCharacterCount(s1, s2) = 3. Strings have 3 common characters - 2 "a"s and 1 "c". """ def commonCharacterCount(s1, s2): global_count = 0 char_count1 = 0 char_count2 = 0 s1_set = set(s1) for i in s1_set: if i in s2: char_count1 = s1.count(i) char_count2 = s2.count(i) if char_count1 <= char_count2: global_count += char_count1 elif char_count2 <= char_count1: global_count += char_count2 return global_count
true
b7315bf9114c641c1b3493ffef65109da2dc9046
Surenu1248/Python3
/eighth.py
434
4.15625
4
# Repeat program 7 with Tuples (Take example from Tutorial) tpl1 = (10,20,30,40,50,60,70,80,90,100,110) tpl2 = (11,22,33,44,55,66,77,88,99) # Printing all Elements..... print("List Elements are: ", tpl1) # Slicing Operations..... print("Slicing Operation: ", tpl1[3:6]) # Repetition..... print("Repetition of list for 5 times: ", (tpl1,) * 5) # Concatenation of lst and lst2 print("Combination of lst and lst2: ", tpl1 + tpl2)
true
54d2387d255062fe1e739f7defeb0cff1f9cf634
Surenu1248/Python3
/third.py
233
4.375
4
# Write a program to find given number is odd or Even def even_or_odd(a): if a % 2 == 0: print(a, " is Even Number.....") else: print(a, " is Odd Number.....") print(even_or_odd(10)) print(even_or_odd(5))
false