blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
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')
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))
1005780057842370fb6348a74f77054eb42a71f7
Laurensvaldez/PythonCrashCourse
/CH5: If Statements/try_it_yourself_ch5_5_10.py
545
4.03125
4
# do the following to create a program that simulates how websites ensure that everyone has a unique username current_users = ['laurens', 'rensley', 'jeremy', 'ian', 'ergin'] new_users = ['jonathan', 'khristian', 'domingo', 'ian', 'ergin'] current_users_lower = [user.lower() for user in current_users] for new_user in new_users: if new_user.lower() in current_users_lower: print ("The username "+ new_user + " is already in use, please choose another one.") else: print ("The username " + new_user + " is available.")
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!")
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 *
fce2b46e2edfe1a84b98b69cdebf3fc7ac90d97b
Laurensvaldez/PythonCrashCourse
/CH5: If Statements/try_it_yourself_ch5_5_6.py
410
3.9375
4
# write an if-elif-else chain that determines a person's stage of life. Set a value for the variable age, and then: person = int(1.99) if person <2: print ("You are a baby.") elif person <4: print ("You are a toddler.") elif person <13: print("You are a kid.") elif person <20: print("You are a teenager.") elif person <65: print("You are an adult.") else: print("You are an elder.")
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()
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'])
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())
42f2ffcbb27880696f75427c05e0977c1432c0ed
Laurensvaldez/PythonCrashCourse
/CH8: Functions/try_it_yourself_ch8_8_14.py
415
3.671875
4
def make_car(manufacturar, model, **extra_info): """Write function that stores information about a car in a dictionary.""" car_dict = {} car_dict['manufacturar_name'] = manufacturar.title() car_dict['model_name'] = model.title() for key, value in extra_info.items(): car_dict[key] = value return car_dict car = make_car('subaru', 'wrc', color='blue', tow_package=True) print(car)
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))
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"))
0503c26bc5c814aba63beb1ac0781db0ce194f5f
dzwduan/CS61A
/Lec/Lec09/gcd.py
300
3.90625
4
#python3 -m doctest -v ex.py def gcd(m,n): """Returns the lagest k that divides both by m and n. k,m,n are all positive integers. >>> gcd(12,8) 4 >>> gcd(20,40) 20 """ if m==n: return m elif m<n: return gcd(n,m) else: return gcd(m-n,n)
3f64bed0bc77f15de807b3694b294240e6b3a93b
bmcclannahan/sort-testing
/sorts.py
611
3.90625
4
def is_sorted(arr): for i in range(len(arr)-1): if arr[i] > arr[i+1]: return False return True def swap(a, b, arr): temp = arr[a] arr[a] = arr[b] arr[b] = temp def insertion_sort(start, end, arr): for i in range(start, end): curr = i while curr >= 1 and arr[curr] < arr[curr-1]: swap(curr, curr-1, arr) curr -= 1 def selection_sort(start, end, arr): for i in range(start, end-1): curr = i for j in range(i+1, end): if arr[curr] > arr[j]: curr = j swap(i, curr, arr)
bf6296c1d7583330c86b7670cdb4dca12e286e24
thinkofmia/Team-MIA-Shopee-Code-League-2021
/03 Programming Contest/shoffee.py
1,423
3.6875
4
#!/bin/python3 import math import os import random import re import sys from itertools import combinations # # Complete the 'maxSubstring' function below. # # The function is expected to return a STRING. # The function accepts STRING s as parameter. # def findShoffee(coffeeBeanAndExpectation, preferenceValue): # Write your code here coffeeBeanAndExpectation = coffeeBeanAndExpectation.split(' ') N = int(coffeeBeanAndExpectation[0]) K = int(coffeeBeanAndExpectation[1]) preferenceValue = preferenceValue.split(' ') preferences = [] for i in preferenceValue: preferences.append(int(i)) result = [] for a in range(len(preferences)+1): result.append(list(combinations(preferences, a))) resultClean = [item for sublist in result for item in sublist] resultClean.pop(0) resultClean = list(dict.fromkeys(resultClean)) another = [] for i in resultClean: myList = list(i) sums = 0 for j in myList: sums += j another.append(sums / len(myList)) count = 0 for i in another: if i >= K: count += 1 return count if __name__ == '__main__': coffeeBeanAndExpectation = input() preferenceValue = input() result = findShoffee(coffeeBeanAndExpectation, preferenceValue) print(result)
92b8f79687ebc4dafcc3014653d95f13330b5852
saulmont/programacion_python
/Bases/Practica/repaso_8.py
660
3.578125
4
def suma(abc, defg, hijk): return abc + defg + hijk def resta(abc, defg, hijk): return abc - defg - hijk def multiplicacion(abc, defg, hijk): return abc * defg * hijk def division(abc, defg): return abc / defg for i in range(0, 101, 2): print("Cargando", i , "% completo") resultado = resta(4568, 98489, 152) print("El resultado de la resta es: ", resultado) resultado = suma(6489, 25654, 9845) print("El resultado de la suma es: ", resultado) resultado = multiplicacion(256, 159, 68) print("El resultado de la Multiplicacion es: ", resultado) resultado = division(4568, 48) print("El resultado de la division es: ", resultado)
e82a2b73a4cdccef5721a26f75dd1a90d43137b6
saulmont/programacion_python
/Bases/Practica/repaso_9.py
614
3.796875
4
var_numeral = 12 # esta variable es global y puede ser accedida desde cualquier lugar del codigo. def crear_variable(): var_numeral = 98 # esta variable es local y solo puede ser accedida desde esta funcion. print(var_numeral) def modificar_variable(): global var_numeral # esta accediendo a la variable global. var_numeral = 1569 # esta modificando el valor de la variable global. print(var_numeral) # imprime la variable global antes de que se modifique. modificar_variable() # esta llamando a funcion. print(var_numeral) # esta imprimiendo la variable global despues de su modificacion.
8a948203bc68f0fefd919a34ecd810cfd60c11f9
saulmont/programacion_python
/Algoritmos/Numeros.py
166
4.09375
4
numero = int(input("Ingrese un numero: ")) if numero %2 ==0: print("El Numero que has ingresado es par") else: print("El Numero que has ingresado es Impar")
3cc14a8cad1ca03776f4b406dd5b4d203ff1d47d
saulmont/programacion_python
/Algoritmos/elevar_exponente.py
337
3.953125
4
base = int(input("Ingrese la base: ")) exponente = int(input("Ingrese el exponente: ")) acumulador = 1 contador = 0 if exponente == 0: print("El resultado es: ", exponente) else: while contador < exponente: acumulador = acumulador * base contador = contador + 1 print("El resultado es: ", acumulador)
0554177b38e7da60432866c00f5535e41f41bf29
shah-farheen/data_wrangling
/xls_parser.py
3,458
3.546875
4
import csv import xlrd datafile = "2013_ERCOT_Hourly_Load_Data.xls" example_file = "example.csv" def parse(datafile): workbook = xlrd.open_workbook(datafile) sheet = workbook.sheet_by_index(0) data = [[sheet.cell_value(r, col) for col in range(sheet.ncols)] for r in range(sheet.nrows)] print "\nList Comprehension" print "data[3][2]:" print data[3][2] print "\nCells in a nested loop:" for row in range(sheet.nrows): for col in range(sheet.ncols): if row == 50: print sheet.cell_value(row, col), print "\n\nROWS, COLUMNS, and CELLS:" print "Number of rows in the sheet:", print sheet.nrows print "Type of data in cell (row 3, col 2):", print sheet.cell_type(3, 2) print "Value in cell (row 3, col 2)", print sheet.cell_value(3, 2) print "Get a slice of values in column 3, from rows 1-3:" print sheet.col_values(3, start_rowx=1, end_rowx=4) print "\nDATES" print "Type of data in cell (row 1, col 0):", print sheet.cell_type(1, 0) exceltime = sheet.cell_value(1, 0) print "Time in Excel format:", print exceltime print "Convert time to a python datetime tuple, from the excel float:", print xlrd.xldate_as_tuple(exceltime, 0) def parse_file(datafile): workbook = xlrd.open_workbook(datafile) sheet = workbook.sheet_by_index(0) data = { 'maxtime': (0, 0, 0, 0, 0, 0), 'maxvalue': 0, 'mintime': (0, 0, 0, 0, 0, 0), 'minvalue': 0, 'avgcoast': 0 } maxvalue = float(sheet.cell_value(1, 1)) minvalue = float(sheet.cell_value(1, 1)) maxtime = float(sheet.cell_value(1, 0)) mintime = float(sheet.cell_value(1, 0)) total = 0.0 for i in range(1, sheet.nrows): value = float(sheet.cell_value(i, 1)) total += value if value > maxvalue: maxvalue = value maxtime = sheet.cell_value(i, 0) if value < minvalue: minvalue = value mintime = sheet.cell_value(i, 0) data['maxtime'] = xlrd.xldate_as_tuple(maxtime, 0) data['mintime'] = xlrd.xldate_as_tuple(mintime, 0) data['maxvalue'] = maxvalue data['minvalue'] = minvalue data['avgcoast'] = total / (sheet.nrows - 1) return data # Lesson 2 Ques2 def xls_parse(datafile): workbook = xlrd.open_workbook(datafile) sheet = workbook.sheet_by_index(0) data = [["Station", "Year", "Month", "Day", "Hour", "Max Load"]] for col in range(1, 9): data.append([sheet.cell_value(0, col).strip()]) maxvalue = float(sheet.cell_value(1, col)) maxtime = sheet.cell_value(1, 0) for row in range(1, sheet.nrows): value = float(sheet.cell_value(row, col)) if value > maxvalue: maxvalue = float(sheet.cell_value(row, col)) maxtime = sheet.cell_value(row, 0) time = xlrd.xldate_as_tuple(maxtime, 0) data[col].append(time[0]) data[col].append(time[1]) data[col].append(time[2]) data[col].append(time[3]) data[col].append(maxvalue) return data def save_file(data, filename): with open(filename, "wb") as csv_file: writer = csv.writer(csv_file, delimiter='|') for line in data: writer.writerow(line) csv_file.close() def main(): data = xls_parse(datafile) print data save_file(data, example_file) main()
b2735390b25903d298a497dfb616d306cc0540e9
JoaquinFarfan/TSI_repo1
/Factorial.py
182
3.90625
4
import math def factorial(x): factorial = math.factorial(x) return factorial x = int(input('Ingrese un numero entero: ')) print('El factorial de ',x,' es',factorial(x))
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
bda7c73b238715ee9b7fb75b3e6de0fed8f1aca5
jrperlic/data-structure-tutorial
/code/1-problem-solution.py
312
3.953125
4
shelf = input() stack = [] for item in shelf: if item == "[": stack.append(item) elif item == "]": if len(stack) == 0 or stack.pop() != "[": print("False") exit() elif item == "|": continue else: print("False") exit() print("True")
e0b2b7001dede40fc01f2f06d8bbb6d62c1d6f2b
Guthixx23/IBS_Assignment_Wanderer_app
/wanderer/character.py
5,422
3.5
4
import random # Parent class for Skeleton, Boss, and Hero class Character(): def __init__(self): self.hp = 0 self.dp = 0 self.sp = 0 self.current_hp = 0 self.level = 0 self.position_row = 0 self.position_col = 0 # 6 side dice roll def roll_d6(self): return random.randint(1, 6) # finding and empty cell for a monster to spawn initially def find_empty_cell(self, maze): done = False i = 0 j = 0 while not done: i = random.randint(1, 10) j = random.randint(1, 10) if i == 1 and j == 1: continue if maze.layout[i][j] == 0: done = True maze.layout[i][j] = 2 return [j, i] # drawing object on canvas def draw(self, canvas, maze): i, j = self.find_empty_cell(maze) canvas.create_image((i - 1) * 72 + 36, (j - 1) * 72 + 36, image=self.image) self.position_col = i self.position_row = j # formatting and displaying stats for the label below the maze def display_stats(self): stats = self.name + " (Level " + str(self.level) + ") HP: " + str(self.current_hp) + "/" + str( self.hp) + " | DP: " + str(self.dp) + " | SP: " + str(self.dp) if self.name == "Boss": return stats else: return stats + " | Key: " + str(self.has_key) # calculating monster levels def calculate_level(self): i = random.randint(0, 9) chance1 = [0, 1, 2, 3, 4] chance2 = [5, 6, 7, 8] if i in chance1: return self.controller.maze.level elif i in chance2: return self.controller.maze.level + 1 else: return self.controller.maze.level + 2 # strike function to represent the interaction between attacker and defender def strike(self, defender): strike_value = 2 * self.roll_d6() + self.sp if strike_value > defender.dp: defender.current_hp -= (strike_value - defender.dp) # function to move characters in the maze def move_character_to(self, row, col): # down if row == self.position_row + 1: if self.controller.maze.layout[self.position_row + 1][self.position_col] != 1: self.canvas.create_image((self.position_col - 1) * 72 + 36, (self.position_row) * 72 + 36, image=self.image) self.position_row = row else: self.canvas.create_image((self.position_col - 1) * 72 + 36, (self.position_row - 1) * 72 + 36, image=self.image) # up if row == self.position_row - 1: if self.controller.maze.layout[self.position_row - 1][self.position_col] != 1: self.canvas.create_image((self.position_col - 1) * 72 + 36, (self.position_row - 2) * 72 + 36, image=self.image) self.position_row = row else: self.canvas.create_image((self.position_col - 1) * 72 + 36, (self.position_row - 1) * 72 + 36, image=self.image) # left if col == self.position_col - 1: if self.controller.maze.layout[self.position_row][self.position_col - 1] != 1: self.canvas.create_image((self.position_col - 2) * 72 + 36, (self.position_row - 1) * 72 + 36, image=self.image) self.position_col = col else: self.canvas.create_image((self.position_col - 1) * 72 + 36, (self.position_row - 1) * 72 + 36, image=self.image) # right if col == self.position_col + 1: if self.controller.maze.layout[self.position_row][self.position_col + 1] != 1: self.canvas.create_image((self.position_col) * 72 + 36, (self.position_row - 1) * 72 + 36, image=self.image) self.position_col = col else: self.canvas.create_image((self.position_col - 1) * 72 + 36, (self.position_row - 1) * 72 + 36, image=self.image) # funtion to find valid moves for monsters in the maze def find_valid_moves(self): correct_moves = [] if self.controller.maze.layout[self.position_row + 1][self.position_col] != 1: correct_moves.append([self.position_row + 1, self.position_col]) if self.controller.maze.layout[self.position_row - 1][self.position_col] != 1: correct_moves.append([self.position_row - 1, self.position_col]) if self.controller.maze.layout[self.position_row][self.position_col + 1] != 1: correct_moves.append([self.position_row, self.position_col + 1]) if self.controller.maze.layout[self.position_row][self.position_col - 1] != 1: correct_moves.append([self.position_row, self.position_col - 1]) return correct_moves[random.randint(0, len(correct_moves) - 1)] # function to hide monsters "reflection" after a move in the maze def hide_from_maze(self): self.controller.maze.draw_cell(self.position_row, self.position_col)
167c5c40a3cca81e5bcff9a86f8c75373703a30f
mohit242/SPOJ-Solutions
/FCTRL2.py
202
3.53125
4
# coding: utf-8 # In[6]: def fact(i): if i==0 or i==1: return 1 return fact(i-1)*i num_cases=int(raw_input()) for i in range(num_cases): inp=int(raw_input()) print fact(inp)
e775843d534f446bb0b4b2539be15b3c0f0d4f21
TheUnknownCurry/psesudocode-and-python-code-
/assignment.py
3,630
4.03125
4
import random attempts_list=[] def start_game(): random_number=int(random.randint(1,50)) print("Hello, Gamer ") print("Welcome To The Number Guessing Game ") print("Let's Play An Interesting Game Were You Have To Guess A Number ") print("A Number Which I Am Thinking Right Now ") print("Can You Guess The Number Right? ") player_name=input("But First May I Know Your Name- ") play=input("Hi, {} and would you like to play this game? Enter(yes/no) ".format(player_name)) print("Let's start the game and have fun") print("Note: 1. You only have 5 attempts to guess the correct answer") print(" 2. The total score of the game is 60") print(" 10 points will decreased for your extra chance taken") attempts=0 score=60 while play.lower()=="yes": if attempts<5: try: guess=input("Now Pick Any Number Between 1 to 50: ") if int(guess)< 1 or int(guess) > 50: print("Guess Within The Range ") print("Your number was not in the range of 1 to 50 ") if int(guess)==random_number: print("Wow, Congrats!! You Got The Answer Right") print("You are a real gamer") attempts+=1 score-=10 attempts_list.append(attempts) print("It Took {} Attempts To Get The Correct Answer".format(attempts)) print("Your total score is {}".format(score)) print("Let's again start the game and have fun") play=input("Would You Like To Play Again Enter (yes/no): ") attempts=0 score=60 random_number=int(random.randint(1,50)) if play.lower() == "no": print("😞") print("Ok no problem, I guess you will miss out on the fun...") break elif int(guess) > random_number: print("Oh no!! The Number Which I Guessed Is Too Low") print("Don't worry, give it one more try") print("Hint- The number which i am thinking is in the range of {},{} :".format(random_number-5, random_number+5)) attempts+=1 score-=10 elif int(guess) < random_number: print("The Number Which I Guessed Is Too High") print("Don't worry, give it one more try") print("Hint- The number is in the range of {},{} :".format(random_number-5, random_number+5)) attempts+=1 score-=10 except ValueError as err: print("Not A Valid Number, Try Again") print("Your number should be between 1 to 50 ") print("({})".format(err)) else: print("Oh no!! Your attempts are over") play_again=input("Would You Like To Play Again Enter (yes/no): ") attempts=0 random_number=int(random.randint(1,50)) if play_again.lower() == "no": print("😞") print("Ok no problem, I guess you will miss out on the fun...") break else: print("😞") print("Ok no problem, I guess you will miss out on the fun...") if __name__ == '__main__': start_game()
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()
cefed8ceb330309a398607fbd2feffe9c87fcd49
fabienf/SDP2015
/planning/utilities.py
2,642
3.5
4
from math import tan, pi def is_shot_blocked(world, angle_to_turn=0): """ Checks if our robot could shoot past their robot """ predicted_y = predict_y_intersection( world, world.their_attacker.x, world.our_defender, full_width=False, bounce=True, angle_to_turn=angle_to_turn) if predicted_y is None: return True return abs(predicted_y - world.their_attacker.y) < world.their_attacker.length def predict_y_intersection(world, predict_for_x, robot, full_width=False, bounce=False, angle_to_turn=0): """ Predicts the (x, y) coordinates of the ball shot by the robot Corrects them if it's out of the bottom_y - top_y range. If bounce is set to True, predicts for a bounced shot Returns None if the robot is facing the wrong direction. """ x = robot.x y = robot.y top_y = world.pitch.height - 60 if full_width else world.our_goal.y + (world.our_goal.width / 2) - 15 bottom_y = 60 if full_width else world.our_goal.y - (world.our_goal.width / 2) + 15 angle = robot.angle + angle_to_turn if (robot.x < predict_for_x and not (pi / 2 < angle < 3 * pi / 2)) or \ (robot.x > predict_for_x and (3 * pi / 2 > angle > pi / 2)): if bounce: if not (0 <= (y + tan(angle) * (predict_for_x - x)) <= world.pitch.height): bounce_pos = 'top' if (y + tan(angle) * (predict_for_x - x)) > world.pitch.height else 'bottom' x += (world.pitch.height - y) / tan(angle) if bounce_pos == 'top' else (0 - y) / tan(angle) y = world.pitch.height if bounce_pos == 'top' else 0 angle = (-angle) % (2 * pi) predicted_y = (y + tan(angle) * (predict_for_x - x)) # Correcting the y coordinate to the closest y coordinate on the goal line: if predicted_y > top_y: return top_y elif predicted_y < bottom_y: return bottom_y return predicted_y else: return None def is_wall_in_front(world): """ Checks if there is a wall within the catcher area """ robot = world.our_defender zone = world.pitch.zones[world.our_defender.zone] | world.pitch.zones[world.their_attacker.zone] return not zone.covers(robot.front_area) def centre_of_zone(world, robot): """ Given a robot calculate the centre of it's zone """ zone_index = robot.zone zone_poly = world.pitch.zones[zone_index][0] min_x = int(min(zone_poly, key=lambda z: z[0])[0]) max_x = int(max(zone_poly, key=lambda z: z[0])[0]) x = min_x + (max_x - min_x) / 2 y = world.pitch.height / 2 return x, y
6e637521ca94000db1c04e3f798984d183244d0d
Test01DezWebSite/KattisDemos
/helpaphd/helpaphd.py
601
3.609375
4
#! /usr/bin/env python3 import sys def answer(equation): result = 'skipped' try: result = eval(equation) except: pass return result def solve(): data = sys.stdin.readlines() ans = [] for line in data[1:]: ans.append(str(answer(line))) print('\n'.join(ans)) def test(): assert answer('P=NP') == 'skipped' assert answer('99+1') == 100 assert answer('0+1000') == 1000 print('all test casses passed...') if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] == 'test': test() else: solve()
351e04dbcd8cd47a887a4b8bf388c14b88672b5d
danieloved1/anigma
/main.py
7,807
3.65625
4
import json day = input("Enter day:\n") while int(day) < 1 or int(day) > 7: day = input("Enter day:\n") # ----------------- Enigma Settings ----------------- reflector = "UKW-B" file = open("code-book.json") data = file.read() data = json.loads(data) dailyConfig = data[day] rotors = dailyConfig["rotors"] ringSettings = dailyConfig["settings"] ringPositions = dailyConfig["positions"] file = open("reflector.json") data = file.read() data = json.loads(data) dataReflector = data file = open("rings.json") data = file.read() data = json.loads(data) plugboard = "AT BS DE FM IR KN LZ OW PV XY" # --------------------------------------------------- def caesarShift(str, amount): output = "" for i in range(0, len(str)): c = str[i] code = ord(c) if ((code >= 65) and (code <= 90)): c = chr(((code - 65 + amount) % 26) + 65) output = output + c return output def encode(plaintext): global rotors, reflector, ringSettings, ringPositions, plugboard # Enigma Rotors and reflectors rotor = data["I"]; rotor1 = rotor["cipher"]; rotor1Notch = "notch" rotor = data["II"]; rotor2 = rotor["cipher"]; rotor2Notch = "notch" rotor = data["III"]; rotor3 = rotor["cipher"]; rotor3Notch = "notch" rotor = data["IV"]; rotor4 = rotor["cipher"]; rotor4Notch = "notch" rotor = data["V"]; rotor5 = rotor["cipher"]; rotor5Notch = "notch" rotorDict = {"I": rotor1, "II": rotor2, "III": rotor3, "IV": rotor4, "V": rotor5} rotorNotchDict = {"I": rotor1Notch, "II": rotor2Notch, "III": rotor3Notch, "IV": rotor4Notch, "V": rotor5Notch} reflectorB = dataReflector["1"]; reflectorC = dataReflector["2"]; alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" rotorANotch = False rotorBNotch = False rotorCNotch = False if reflector == "UKW-B": reflectorDict = reflectorB else: reflectorDict = reflectorC # A = Left, B = Mid, C=Right rotorA = rotorDict[rotors[0]] rotorB = rotorDict[rotors[1]] rotorC = rotorDict[rotors[2]] rotorANotch = rotorNotchDict[rotors[0]] rotorBNotch = rotorNotchDict[rotors[1]] rotorCNotch = rotorNotchDict[rotors[2]] rotorALetter = ringPositions[0] rotorBLetter = ringPositions[1] rotorCLetter = ringPositions[2] rotorASetting = ringSettings[0] offsetASetting = alphabet.index(rotorASetting) rotorBSetting = ringSettings[1] offsetBSetting = alphabet.index(rotorBSetting) rotorCSetting = ringSettings[2] offsetCSetting = alphabet.index(rotorCSetting) rotorA = caesarShift(rotorA, offsetASetting) rotorB = caesarShift(rotorB, offsetBSetting) rotorC = caesarShift(rotorC, offsetCSetting) if offsetASetting > 0: rotorA = rotorA[26 - offsetASetting:] + rotorA[0:26 - offsetASetting] if offsetBSetting > 0: rotorB = rotorB[26 - offsetBSetting:] + rotorB[0:26 - offsetBSetting] if offsetCSetting > 0: rotorC = rotorC[26 - offsetCSetting:] + rotorC[0:26 - offsetCSetting] ciphertext = "" # Converplugboard settings into a dictionary plugboardConnections = plugboard.upper().split(" ") plugboardDict = {} for pair in plugboardConnections: if len(pair) == 2: plugboardDict[pair[0]] = pair[1] plugboardDict[pair[1]] = pair[0] plaintext = plaintext.upper() for letter in plaintext: encryptedLetter = letter if letter in alphabet: # Rotate Rotors - This happens as soon as a key is pressed, before encrypting the letter! rotorTrigger = False # Third rotor rotates by 1 for every key being pressed if rotorCLetter == rotorCNotch: rotorTrigger = True rotorCLetter = alphabet[(alphabet.index(rotorCLetter) + 1) % 26] # Check if rotorB needs to rotate if rotorTrigger: rotorTrigger = False if rotorBLetter == rotorBNotch: rotorTrigger = True rotorBLetter = alphabet[(alphabet.index(rotorBLetter) + 1) % 26] # Check if rotorA needs to rotate if (rotorTrigger): rotorTrigger = False rotorALetter = alphabet[(alphabet.index(rotorALetter) + 1) % 26] else: # Check for double step sequence! if rotorBLetter == rotorBNotch: rotorBLetter = alphabet[(alphabet.index(rotorBLetter) + 1) % 26] rotorALetter = alphabet[(alphabet.index(rotorALetter) + 1) % 26] # Implement plugboard encryption! if letter in plugboardDict.keys(): if plugboardDict[letter] != "": encryptedLetter = plugboardDict[letter] # Rotors & Reflector Encryption offsetA = alphabet.index(rotorALetter) offsetB = alphabet.index(rotorBLetter) offsetC = alphabet.index(rotorCLetter) # Wheel 3 Encryption pos = alphabet.index(encryptedLetter) let = rotorC[(pos + offsetC) % 26] pos = alphabet.index(let) encryptedLetter = alphabet[(pos - offsetC + 26) % 26] # Wheel 2 Encryption pos = alphabet.index(encryptedLetter) let = rotorB[(pos + offsetB) % 26] pos = alphabet.index(let) encryptedLetter = alphabet[(pos - offsetB + 26) % 26] # Wheel 1 Encryption pos = alphabet.index(encryptedLetter) let = rotorA[(pos + offsetA) % 26] pos = alphabet.index(let) encryptedLetter = alphabet[(pos - offsetA + 26) % 26] # Reflector encryption! if encryptedLetter in reflectorDict.keys(): if reflectorDict[encryptedLetter] != "": encryptedLetter = reflectorDict[encryptedLetter] # Back through the rotors # Wheel 1 Encryption pos = alphabet.index(encryptedLetter) let = alphabet[(pos + offsetA) % 26] pos = rotorA.index(let) encryptedLetter = alphabet[(pos - offsetA + 26) % 26] # Wheel 2 Encryption pos = alphabet.index(encryptedLetter) let = alphabet[(pos + offsetB) % 26] pos = rotorB.index(let) encryptedLetter = alphabet[(pos - offsetB + 26) % 26] # Wheel 3 Encryption pos = alphabet.index(encryptedLetter) let = alphabet[(pos + offsetC) % 26] pos = rotorC.index(let) encryptedLetter = alphabet[(pos - offsetC + 26) % 26] # Implement plugboard encryption! if encryptedLetter in plugboardDict.keys(): if plugboardDict[encryptedLetter] != "": encryptedLetter = plugboardDict[encryptedLetter] ciphertext = ciphertext + encryptedLetter return ciphertext # Main Program Starts Here print(" ##### Enigma Encoder #####") print("") filename = input("write the name of the file ") file = open(filename, "r") d = file.read() textFile = d printext = textFile ciphertext = encode(textFile) f = open("textencript", "w") plaintext = textFile ciphertext = encode(plaintext) f.write(ciphertext) print("\nfile Encoded text: \n " + ciphertext) ################################################ print("#########################################") plaintext=input("write some text") cliptext = encode(plaintext) print(cliptext)
5ba04f2a2ab1f498f565e9aa2c9f2d14a7e46771
maxjackson705/Python-Practice
/collections.py
285
3.71875
4
my_list = ['p', 'r', 'o', 'b', 'e'] my_list2 = [10, 20, 30, 40] print(my_list2) print(my_list[0]) print(my_list[2]) print(my_list[4]) n_list = ["Happy", [2, 0, 1, 5]] print(n_list[0][1]) print(n_list[1][3]) print(my_list[2:5]) for item in my_list2: print(item)
0a1ba8bcf84ab53fa0d2d5fc8b1702142d945ed5
AscendentFive/Python
/FuncionMAP.py
150
3.609375
4
def operador(n,m): if n==None or m==None: return 0 return n+m l1 = [1,2,3,4] t1 = (9,8,7,6) lr = map(operador,l1,t1) print l1 print t1 print lr
02cfb2e06082639aeed0be7813753611b2101560
AscendentFive/Python
/diccionarios.py
155
3.796875
4
d = {'Clave1':[1,2,3], 'Clave2':True, 4:True } print d['Clave1'] print d['Clave2'] print d[4] #Cambiar una clave d[4] = "Hola He cambiado" print d[4]
a6bf630f2b172e307da8e72f982a58b750f15fa7
AscendentFive/Python
/FuncionOrdenSuperior.py
243
3.546875
4
def seleccion(operacion): def suma(n,m): return n+m def multiplicacion(n,m): return n*m if operacion == "suma": return suma elif operacion == "multi": return multiplicacion fGuardada = seleccion("multi") print fGuardada(12,12)
f19270953319dd13b4647d50ab6d48efec6c2abd
mannurulz/Machine_Learning
/slop_intercept_n_predict.py
759
3.78125
4
from statistics import mean import numpy as np import matplotlib.pyplot as plt from matplotlib import style style.use('ggplot') xs = np.array([1,2,3,4,5], dtype=np.float64) ys = np.array([5,4,6,5,6], dtype=np.float64) def best_fit_slope_and_intercept(xs,ys): m = (((mean(xs)*mean(ys)) - mean(xs*ys)) / ((mean(xs)*mean(xs)) - mean(xs*xs))) b = mean(ys) - m*mean(xs) return m, b m, b = best_fit_slope_and_intercept(xs,ys) print(m,b) regression_line = [(m*x)+b for x in xs] predict_x = 8 predict_y = (m*predict_x)+b plt.scatter(xs,ys,color='#003F72',label='data') plt.scatter(predict_x,predict_y,color='green',label='predict data') plt.plot(xs, regression_line, label='predict regression line') plt.legend(loc=4) plt.show()
5a40f176f18234f361b4b362ed05148e79d964c8
aomline1/python_algorithm
/sort.py
1,941
3.890625
4
#插入排序 lista=[1,40,12,25,78,8,9,18] def insert_sort(list): for i in range(1,len(list)): key=list[i] j=i-1 while( j>0 and list[j]>key): list[j+1]=list[j] j-=1 list[j+1]=key return list #归并排序 def merge_sort(list): if len(list)<=1: return list mid=len(list)//2 left=merge_sort(list[:mid]) right=merge_sort(list[mid:]) return merge(left,right) def merge( left,right): i,j=0,0 result=[] while(i<len(left) and j<len(right)): if left[i]<right[j]: result.append(left[i]) i+=1 else: result.append(right[j]) j+=1 result+=left[i:] result += right[j:] return result #选择排序 def select_sort(list): for i in range(len(list)): a=list[i] for j in range(i,len(list)): if list[j]<list[i]: temp=list[i] list[i]=list[j] list[j]=temp return list #冒泡排序 def bubble_sort(list): for i in range(1,len(list)): for j in range(len(list)-i): if list[j]>list[j+1] : temp = list[j+1] list[j+1] = list[j] list[j] = temp return list #希尔排序 def shell_sort(list): grap=len(list)//2 while grap>=1: for i in range(grap,len(list)): j=i-grap while j>=0 and list[j]>list[i]: list[j+grap]=list[j] j-=grap #快速排序 '''def swap(list,i,j): temp=list[i] list[i]=list[j] list[j]=temp''' def quicksort(list): if len(list)<2: return list else: pivot=list[0] less=[i for i in list[1:] if i <pivot] greater=[i for i in list[1:] if i >pivot] return quicksort(less)+[pivot]+quicksort(greater) #堆排序
9165d23f16e7ba35acf8b8f08ed5f28ea74f12da
nadiabey/rosalind
/dnastructures.py
323
3.703125
4
nucleotides = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'} def reverse(st): temp = st[::-1] ret = "" for x in temp: if x in nucleotides.keys(): ret += nucleotides[x] print(ret) return ret if __name__ == '__main__': f = open('rosalind_revc.txt', 'r').readlines()[0] reverse(f)
17c26d98f7b010a6dd18fba21d6f7dc6a113df50
hyunkyeng/TIL
/algorithm/day12/피자굽기.py
802
3.609375
4
def pizza(): global cheeze pan = [] for i in range(N): pan.append(cheeze.pop(0)) return bake(pan) def bake(pan): while True: if len(pan) == 1: return pan[0][0] pan[0][1] = pan[0][1] // 2 if pan[0][1] != 0: pan.append(pan.pop(0)) elif pan[0][1] == 0: if len(cheeze) != 0: pan.append(cheeze.pop(0)) pan.pop(0) else: pan.pop(0) import sys sys.stdin = open("피자굽기.txt") T = int(input()) for tc in range(T): N, M = map(int, input().split()) cheeze = [] for i, name in enumerate(list(map(int, input().split()))): cheeze.append([i + 1, name]) # for i, name in enumerate(temp): print(f'#{tc+1} {pizza()}')
3198cbddd9a4ed9ab9aa5c19b54b3d8824415b6f
ouzarf/tuto-py
/classY.py
442
3.5
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 4 08:59:44 2018 @author: ouzarf """ class Y: def __init__(self, v0): self.v0 = v0 self.g = 9.81 def value(self, t): return self.v0*t - 0.5*self.g*t**2 def formula(self): return ("v0*t - 0.5*g*t**2; v0=%g" % self.v0) y = Y(5) t = 0.2 v = y.value(t) print( "y(t=%g; v0=%g) = %g" % (t, y.v0, v)) print (y.formula())
4569c713cbb38259afd412666bbe92c6af35547a
anteater333/Anteater_lab
/Algo/5086/__init__.py
323
3.546875
4
outputs = [] done = False while not done: a, b = map(int, input().split()) if a == 0 and b == 0: done = True elif a % b == 0: outputs.append("multiple") elif b % a == 0: outputs.append("factor") else: outputs.append("neither") for output in outputs: print(output)
e38b6169034ffa41f946851485367923aba2a652
yuyan1991/Python-ProjectEuler
/PE0001.py
116
3.984375
4
# -*- coding:utf-8 -*- ans = 0; for x in range(1000): if x%3==0 or x%5==0: ans += x print("ans=", ans)
3723ca900a2c07388f8e1ea7ea961c74c83be178
prince-singh98/python-codes
/Loops/GuessingGame2.py
550
3.90625
4
num = 7 list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for trial in range(3): ans = int(input("enter a num : ")) if ans in list: if trial == 0 or trial == 1: if ans == num: print("success") break else: print("try again") elif trial == 2: if ans == num: print("success") break else: print("You lost the game! ") else: print("Please select any one from 0 to 9") break
589c19c0041b1a176e8b3a896b6eb17d9dee9ccb
prince-singh98/python-codes
/Relation/WarshallAlgorithm.py
406
3.6875
4
import numpy as np M = np.array([[1, 0, 1], [0, 1, 0], [1, 1, 0]]) x = len(M) def warshall(M): assert(len(row) == len(M) for row in M) n = len(M) for k in range(n): for i in range(n): for j in range(n): M[i][j] = M[i][j] or (M[i][k] and M[k][j]) return M print("The given relation is: ") print(M) print("Transitive Closure is: ") print(warshall(M))
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")
eb97ccd4bed66773ffa8de7a12b6ec48dc7feeb3
prince-singh98/python-codes
/Loops/Fibonacci.py
219
4.09375
4
# fibonacci series wrt term term = int(input("enter up to which term you want: ")) t1 = 0 t2 = 1 print(t1) print(t2) for x in range(2,term,1): nextTerm = t1 + t2 print(nextTerm) t1 = t2 t2 = nextTerm
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
10ed809445886786b67ae5806fcb58afcf3382f8
prince-singh98/python-codes
/Relation/RelationAssignment.py
2,056
3.734375
4
A = {1, 2, 3} R = {(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)} def is_reflex_notReflex_Irreflex(R): count = 0 for a, b in R: if (a, b) and a == b: count += 1 if count == 0: # Ir-reflexive relation return count if count == len(A): # Reflexive relation return count # Not reflexive relation return count def is_symmetric(R): for a, b in R: if (b, a) not in R: return False return True def is_not_symmetric(R): for a, b in R: if (a, b) in R and (b, a) not in R: return True return False def is_anti_symmetric(R): # checks Anti-Symmetric status = False for a, b in R: if (a, b) in R and (b, a) in R: if a == b: status = True return status def is_transitive(R): for a, b in R: for c, d in R: if b == c and (a, d) not in R: return False return True def check_equivalence(R): return is_symmetric(R) and is_transitive(R) and is_reflex_notReflex_Irreflex(R) == len(A) def partial_order(R): return is_anti_symmetric(R) and is_transitive(R) and is_reflex_notReflex_Irreflex(R) == len(A) result = is_reflex_notReflex_Irreflex(R) if result == len(A): print("R is reflexive") elif result == 0: print("R is not Ir reflexive") else: print("R is not reflexive") result = is_symmetric(R) if result is True: print("R is symmetric") result = is_not_symmetric(R) if result is True: print("R is not symmetric") result = is_anti_symmetric(R) if result is True: print("R is anti symmetric") result = is_transitive(R) if result is True: print("R is transitive") else: print("R is not transitive") result = check_equivalence(R) if result is True: print("R is a Equivalence Relation") else: print("R is not a Equivalence Relation") result = partial_order(R) if result is True: print("R is partial order") else: print("R is not partial order")
94cdc04e927c6085167dbd774cc0660e641fb1bf
prince-singh98/python-codes
/ClassAndObjects/Calculator.py
491
3.71875
4
class Calculator: def userInput(self,no1,no2): self.no1 = no1 self.no2 = no2 def add(self): return self.no1+self.no2 def sub(self): return self.no1-self.no2 def mul(self): return self.no1*self.no2 def div(self): return self.no1//self.no2 cal = Calculator() cal.userInput(21,4) print("sum is: ",cal.add()) print("subtraction is: ",cal.sub()) print("multiplication is: ",cal.mul()) print("division is: ",cal.div())
b9cfdb68bb172692e0ac36a882bd10be58e9dc72
prince-singh98/python-codes
/ConditionalStatements/Average.py
281
3.96875
4
# average of 5 nos a = int(input("enter first number")) b = int(input("enter second number")) c = int(input("enter third number")) d = int(input("enter fourth number")) e = int(input("enter fifth number")) sum = a + b + c + d + e result = sum / 5 print("average is : ", result)
cfd82a0d2e541e6e0058a6fe3206a21bbc2a457a
MustansirMR/Python-Projects
/number_guessing/main.py
2,334
3.984375
4
import random class NumberGuessingGame: def __init__(self): self.score = 10 def guess_number(self): self.num_to_guess = random.randint(2, 99) print(self.num_to_guess) print(f'I have a number in mind between 2 and 100. Can you guess it in {self.score} turns?') while True: try: guessed_num = int(input('Guess the number: ')) except ValueError: self.reduce_score() self.check_end_game() print(f'Naughty Naughty! What you entered is not a number. You score is now {self.score}') continue if guessed_num == self.num_to_guess: print(f'You have guessed the number! Good job! Your score is {self.score}\n' f'Thanks for playing the game!') break else: self.reduce_score() self.check_end_game() print(f'Not the number. Guess again. Your score is now {self.score}') self.print_hint() def print_hint(self): a = [self.get_multiple_hint, self.get_divisible_hint, self.get_lower_num, self.get_higher_num] print(f'Hint: {random.choice(a)()}') def get_multiple_hint(self): return f'{self.num_to_guess * random.randint(2, 20)} is a multiple of the number.' def get_divisible_hint(self): divisor_top_range = self.num_to_guess // 2 + 1 divisors = [i for i in range(2, divisor_top_range) if self.num_to_guess % i == 0] if divisors: return f'{random.choice(divisors)} is a divisor of the number.' else: return 'The number is a prime number' def get_lower_num(self): return f'The number is higher than {random.randint(2, self.num_to_guess-1)}.' def get_higher_num(self): return f'The number is lower than {random.randint(self.num_to_guess+1, 99)}' def check_end_game(self): if self.score == 0: print("Oh no! You couldn't guess the number :( " "But thanks for playing the game!") exit(0) def reduce_score(self): self.score -= 1 if __name__ == '__main__': random.seed() game = NumberGuessingGame() game.guess_number() # print(game.get_divisible_hint())
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()
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();
70a6549f5d354ecf63fc1cd8899c9c9a67cb7799
thiagoeh/exercism
/python/largest-series-product/largest_series_product.py
540
3.890625
4
def serie_product(serie): product = 1 for char in serie: product *= int(char) return product def largest_product(series, size): if size < 0: raise ValueError('size must be a non-negative integer') # Generate all combinations based on the size combinations = (series[i:size+i] for i in range(0, len(series)-size+1)) # Generate a product for each combination products = (serie_product(combination) for combination in combinations) # Return the largest product return max(products)
55d5bb10659365468580c9f842ee5a06ee6b5c27
thiagoeh/exercism
/python/run-length-encoding/run_length_encoding.py
1,020
3.8125
4
def decode_char(c, multiplier): if multiplier == '': multiplier = 1 return c * int(multiplier) def decode(string): multiplier = '' decoded_str = '' for c in string: if c.isdigit(): multiplier = multiplier + c else: decoded_str = decoded_str + decode_char(c, multiplier) multiplier = '' return decoded_str def encode_char(c, multiplier): if int(multiplier) == 0: return '' elif int(multiplier) == 1: return c else: return str(multiplier) + c def encode(string): encoded_str = '' previous_char = '' char_counter = 0 for c in string: if c == previous_char: char_counter = char_counter + 1 else: encoded_str = encoded_str + \ encode_char(previous_char, char_counter) previous_char = c char_counter = 1 encoded_str = encoded_str + encode_char(previous_char, char_counter) return encoded_str
d18d24ce0234c050bf14090cd8f04078c1a788ac
thiagoeh/exercism
/python/isbn-verifier/isbn_verifier.py
1,119
3.734375
4
def verify(isbn): # Initialize sum isbn_sum = 0 # Removing dashes isbn_stripped = isbn.replace('-','') # Test if we have the right length if len(isbn_stripped) != 10: return False # X at the end is equivalent to 10 at the position if(isbn_stripped[-1] == 'X'): # Replace X with a 0 at the end and increment isbn_sum isbn_stripped = isbn_stripped[:-1] + '0' isbn_sum = 10 # Test if the input have any letter (which makes it invalid) if not isbn_stripped.isnumeric(): return False # Calculates the sum according to validation algorithm isbn_sum += ( int(isbn_stripped[0]) * 10 \ + int(isbn_stripped[1]) * 9 \ + int(isbn_stripped[2]) * 8 \ + int(isbn_stripped[3]) * 7 \ + int(isbn_stripped[4]) * 6 \ + int(isbn_stripped[5]) * 5 \ + int(isbn_stripped[6]) * 4 \ + int(isbn_stripped[7]) * 3 \ + int(isbn_stripped[8]) * 2 \ + int(isbn_stripped[9]) * 1 ) isbn_modulus = isbn_sum % 11 return (isbn_modulus == 0)
ea0ba9d5b27e60510c4c8787b999b33048b15c57
joaovitordmoraes/curso_CeV_python3
/mundo 01/exercicio27.py
192
3.921875
4
nomecompleto = str(input('Digite seu nome completo: ')).strip() nome = nomecompleto.split() print('Seu primeiro nome é: {}'.format(nome[0])) print('Seu último nome é: {}'.format(nome[-1]))
408e448d3c3d62263f1ac47ec626a5cfefd24b25
joaovitordmoraes/curso_CeV_python3
/mundo 01/exercicio28.py
340
3.8125
4
from random import randint from time import sleep computador = randint(0, 5) # SORTEIA UM NÚMERO ENTRE 0 E 5 print('Escolhendo um número.......') voce = int(input('Tente adivinhar em que número o computador pensou: ')) print('Processando...') sleep(2) if voce == computador: print('Você acertou!') else: print('Você errou!')
b223daabfdef0d456262ed54430a85c199eb2bdc
joaovitordmoraes/curso_CeV_python3
/mundo 02/exercicio44.py
1,277
3.703125
4
preco = float(input('Qual o preço do produto? R$')) forma = str(input('Qual a forma de pagamento (à vista ou parcelado)? ')).strip() red = '\033[31m' fecha = '\033[m' if forma == 'à vista' or forma == 'a vista': print('À vista selecionado.') avista = str(input('Será pago em dinheiro, cheque ou cartão? ')).strip() if avista == 'dinheiro' or avista == 'cheque': desconto = preco - (preco * (10/100)) print('O valor total a ser pago é de R${:.2f}'.format(desconto)) elif avista == 'cartão' or avista == 'cartao': desconto = preco - (preco * (5/100)) print('O valor total a ser pago é de R${:.2f}'.format(desconto)) else: print('{}Forma de pagamento inválida.{}'.format(red, fecha)) elif forma == 'parcelado': print('Parcelado selecionado.') parcelas = int(input('Em quantas parcelas deseja dividir no cartão? ')) if parcelas == 2: print('O valor total a ser pago é de R${:.2f}'.format(preco)) elif parcelas >= 3: juros = preco + (preco * (20/100)) print('O valor total a ser pago é de R${:.2f}'.format(juros)) else: print('{}Forma de pagamento inválida.{}'.format(red, fecha)) else: print('{}Forma de pagamento inválida.{}'.format(red, fecha))
1abeac658c51abed58627a94bcfa750fbdafeb83
joaovitordmoraes/curso_CeV_python3
/mundo 01/exercicio09.py
124
3.796875
4
tabuada = int(input('Digite a tabuada: ')) for x in range(1, 11): print('{} x {} = {}'.format(tabuada, x, tabuada * x))
695540ac11869112344c218342df05c686e0cf83
joaovitordmoraes/curso_CeV_python3
/mundo 01/exercicio10.py
122
3.796875
4
valor = float(input('Digite o valor: ')) converter = valor / 3.27 print('Você possui {:.2f} dólares'.format(converter))
5f97f81c6f4a6b6f601859606f88709d09d404d7
joaovitordmoraes/curso_CeV_python3
/mundo 02/exercicio36.py
579
3.90625
4
''' EMPRESTIMO BANCÁRIO PARA A COMPRA DE UMA CASA ''' valor = float(input('Qual o valor da casa? R$')) salario = float(input('Qual o valor do seu salário? R$')) anos = float(input('Em quantos anos pretende pagar? ')) prestacao = (valor / anos) / 12 parcelas = anos * 12 abre = '\033[31m' fecha = '\033[m' if prestacao <= (salario * 30/100): print('Empréstimo aprovado! Você deverá pagar {:.0f} parcelas de R${:.2f}'.format(parcelas, prestacao)) else: print('{}Empréstimo negado. O valor da parcela não pode exceder 30% do salário.{}'.format(abre, fecha))
bca8a5ec4316bb544908cdf93411b1dfc1c10a1f
xpenalosa/Text-To-Image-Encryption
/src/algorithms/streams/stream_seed.py
1,929
3.5625
4
from src.algorithms.streams.base_stream import BaseStreamAlgorithm from typing import Generator, Optional import random class StreamSeedAlgorithm(BaseStreamAlgorithm): """Implementation of BaseStreamAlgorithm that streams the algorithm list. The class provides the option to apply an XOR operation to the input bytes with the algorithm list as the key. Since the algorithm list is already required in order to decode the message, it is preferred over prompting the user for another password. This class requires the following parameters: Algorithm list, provided by the user >>> ssa = StreamSeedAlgorithm() >>> # seed = 0, generates int(97) >>> ssa.encode( ... bytes("a", "ascii"), ... algorithms=bytes(chr(0), "ascii")) b'\\x03' >>> # seed = 97, generates int(49) >>> ssa.encode( ... bytes("a", "ascii"), ... algorithms=bytes("a", "ascii")) b'P' >>> ssa.decode( ... bytes("a", "ascii"), ... algorithms=bytes(chr(0), "ascii")) b'\\x03' >>> ssa.decode( ... bytes("a", "ascii"), ... algorithms=bytes("a", "ascii")) b'P' """ def stream_values(self, **kwargs) -> Generator[int, Optional[int], None]: """Create an integer generator that yields encoded byte values. The integer generator yields randomly generated integers in the range 1-127, XOR'd with the input text in order. The random seed is the sum of each byte value of the algorithm key. :param kwargs: Optional parameters for the generator. :return: An integer generator. """ next_val = yield -1 key = kwargs["algorithms"] seed = sum([b for b in key]) random.seed(seed) while True: next_val = yield next_val ^ random.randint(0, 2 ** 7 - 1) if __name__ == "__main__": import doctest doctest.testmod()
1959626da5a5f9d5f4cb9853b54ac2d9d30f16f0
xpenalosa/Text-To-Image-Encryption
/src/algorithms/bit_cycle.py
4,668
3.90625
4
from src.algorithms.base import BaseAlgorithm from src.utilities import bytes_conversions, algorithm_list_parser class BitCycleAlgorithm(BaseAlgorithm): """Implementation of BaseAlgorithm that encodes through left-cycling bits. The class provides the option to cycle the bits forming the text string an arbitrary amount of positions. The decoding process uses right-cycling as the inverse operation of left-cycling. This class requires the following parameters: Algorithm list, provided by the user Algorithm index, calculated automatically """ def __get_cycle_positions(self, **kwargs) -> int: """Determine the positions to shift based on the algorithm list. Looks for the current position in the algorithm list and tries to find a single-digit value (1-9) on the next position. The digit represents the amount of bits to cycle. If no digit is found, defaults to 4 bits. If digit found is 0, defaults to 1. :param kwargs: See BitCycleAlgorithm. :return: The amount of positions to cycle. >>> bca = BitCycleAlgorithm() >>> bca._BitCycleAlgorithm__get_cycle_positions( ... algorithms=bytes("b1", "ascii"), ... index=0) 1 >>> bca = BitCycleAlgorithm() >>> bca._BitCycleAlgorithm__get_cycle_positions( ... algorithms=bytes("b0", "ascii"), ... index=0) 1 >>> bca = BitCycleAlgorithm() >>> bca._BitCycleAlgorithm__get_cycle_positions( ... algorithms=bytes("acdb5ef", "ascii"), ... index=3) 5 >>> bca = BitCycleAlgorithm() >>> bca._BitCycleAlgorithm__get_cycle_positions( ... algorithms=bytes("a", "ascii"), ... index=10) 4 >>> bca = BitCycleAlgorithm() >>> bca._BitCycleAlgorithm__get_cycle_positions( ... algorithms=bytes("abc", "ascii"), ... index=1) 4 """ try: # Access next digit in algorithm list positions = int(algorithm_list_parser.get_algorithm_key( algorithms=kwargs["algorithms"], index=kwargs["index"] + 1)) except (ValueError, IndexError): # Fall back to default value positions = 4 return max(positions, 1) def encode(self, text: bytes, **kwargs) -> bytes: """Encode the text using the bit-wise left-cycle algorithm. :param text: The text to encode. :param kwargs: See BitCycleAlgorithm. :return: The encoded text, as a bytes object. >>> bca = BitCycleAlgorithm() >>> bca.encode( ... bytes("a", "ascii"), ... algorithms=bytes(chr(0)+"1", "ascii"), ... index=0) b'C' >>> bca.encode( ... bytes("a", "ascii"), ... algorithms=bytes(chr(0)+"7", "ascii"), ... index=0) b'a' >>> bca.encode( ... bytes("a", "ascii"), ... algorithms=bytes(chr(0), "ascii"), ... index=0) b'\\x1c' """ # Format each byte as a concatenation of 7-bit padded values bit_list = bytes_conversions.bytes_to_bit_rep(text) positions = self.__get_cycle_positions(**kwargs) # Cycle first N bits bit_list = bit_list[positions:] + bit_list[:positions] # Reconstruct string and return return bytes_conversions.bit_rep_to_bytes(bit_list) def decode(self, text: bytes, **kwargs) -> bytes: """Decode the text using the bit-wise right-cycle algorithm. :param text: The text to decode. :param kwargs: See BitCycleAlgorithm. :return: The decoded text, as a bytes object. >>> bca = BitCycleAlgorithm() >>> bca.decode( ... bytes("a", "ascii"), ... algorithms=bytes(chr(0)+"1", "ascii"), ... index=0) b'p' >>> bca.decode( ... bytes("a", "ascii"), ... algorithms=bytes(chr(0)+"7", "ascii"), ... index=0) b'a' >>> bca.decode( ... bytes("a", "ascii"), ... algorithms=bytes(chr(0), "ascii"), ... index=0) b'\\x0e' """ bit_list = bytes_conversions.bytes_to_bit_rep(text) positions = self.__get_cycle_positions(**kwargs) bit_list = bit_list[-positions:] + bit_list[:-positions] # Reconstruct string and return return bytes_conversions.bit_rep_to_bytes(bit_list) if __name__ == "__main__": import doctest doctest.testmod()
3e7afa5abee0267909f56bae2ade9759b4dde67a
Salmon420/01_Temperature
/08_valid_filename.py
1,031
4.0625
4
#checks in something is valid import re # Data to be outputted data = ['first','second','third','fourth','fifth','sixth','seventh'] has_error = "yes" while has_error == "yes": print() filename = input("Enter a filename: ") has_error = "no" problem = "" valid_char = "[A-Za-z0-9_]" for letter in filename: if re.match(valid_char, letter): continue elif letter == " ": problem = "(no spaces allowed)" else: problem = ("(no {}'s allowed) ".format(letter)) if filename == "": problem = "can't be bank" if problem != "": print("Invalid filename - {}".format(problem)) else: print("You entered a vaild filename") has_error = "no" # add .txt suffix! filename += ".txt" # create file to hold data f = open(filename, "w+") # add new line at end of each item for item in data: f.write(item + "\n") # close file f.close()
b36448a0e41f3ac2f94fb807d9beb21f6825674e
Ren-Jingsen/day04
/sshop.py
2,664
3.59375
4
''' 任务: 优化购物小条 10机械革命优惠券,0.5 20张卫龙辣条优惠券 0.3 15张HUA WEI WATCH 0.8 随机抽取一张优惠券。 商城: 1.准备一些商品 2.有空的购物车 3.钱包 4.结算 流程: 看你输入的产品存不存在, 若存在 若钱够了: 将商品添加到购物车 钱包余额减去商品的钱 若钱不够 温馨: 若不存在 温馨提示: 非法输入: 退出: 打印购物小条 ''' import copy import random import time b = 1 # 机械革命 c = 1 # HUA WEI WATCH d = 1 # 卫龙辣条 shop = [ ["lenovo PC", 5600], ["HUA WEI WATCH", 1200], ["Mac pro", 12000], ["洗衣机", 3000], ["机械革命", 5000], ["卫龙辣条", 4.5], ["老干妈辣酱", 20], ] a = random.randint(0, 44) # 1.准备好钱包 money = input("亲输入您的初始余额:") money = int(money) ticket = input("您是否要抽取优惠券?\n y/n?\n") if ticket == "y": # time.sleep(2) if a >= 0 and a <= 9: b = 0.5 shop[4][1] = round(shop[4][1] * b, 2) print("恭喜您抽中一张机械革命五折优惠券") elif a > 9 and a <= 29: d = 0.3 shop[5][1] = round(shop[5][1] * d, 2) print("恭喜你抽中一张卫龙辣条三折优惠券") elif a > 29 and a <= 44: c = 0.8 shop[1][1] = round(shop[1][1] * c, 2) print("恭喜您抽中一张HUA WEI WATCH八折优惠券") else: pass # 2. 准备一个空的购物车 mycart = [] sum = 0 # 3.开始购物 sum = 0 i = 0 while i < 20: for key, value in enumerate(shop): print(key, value) # 请输入您要卖的商品 chose = input("请输入您要买的商品:") if chose.isdigit(): chose = int(chose) # "1" --> 1 if chose > len(shop) or chose < 0: # 9 > 7 print("该商品不存在!别瞎弄!") else: if money >= shop[chose][1]: money = money - shop[chose][1] mycart.append(copy.deepcopy(shop[chose])) sum = sum + shop[chose][1] print("恭喜,商品添加成功!您的余额为:¥", money) if b != 1 and chose == 4: shop[4][1] = 5000 elif c != 1 and chose == 1: shop[1][1] = 1200 elif d != 1 and chose == 5: shop[5][1] = 4.5
b71e808a3cad44634d68acc663c543289b3feb74
arvinjason/py4e
/Dict_Exercise1_Aquino.py
232
3.546875
4
file = input('Enter file name: ') fh = open(file) date = dict() for line in fh: if line.startswith("From "): lst = line.split() if lst[2] not in date: date[lst[2]] = 1 else: date[lst[2]] = date[lst[2]] + 1 print(date)
cde54473101afb081a05589e10754aafd4be65d6
arvinjason/py4e
/Exercise3-Aquino.py
282
3.921875
4
score = input('Enter score: ') try: s = float(score) except: s = -1 if s>0 and s<0.6: print('F') elif s >= 0.6 and s < 0.7: print('D') elif s >= 0.7 and s < 0.8: print('C') elif s >= 0.8 and s < 0.9: print('B') elif s >= 0.9 and s < 1.0: print('A') else: print('Bad score')
e1fa1ee994a79d85ce82e5578c9e03623ceeb4a2
DaishanHuang/python
/youtube/Tutorial-21_Function-and-return/main.py
407
4
4
# 1 def allowed_dating_age(my_age) : girls_age = my_age / 2 + 7 return girls_age # 1.1 example mincongs_limit = allowed_dating_age() print("i can date firls", mincongs_limit, "or older") # 2 def get_gender(sex='unknown') : if sex is 'm' : sex = "Male" elif sex is 'f' : sex = "Female" print(sex) # 2.1 example get_gender('m') # 'Male' get_gender('f') # 'Female' get_gender() # 'unknown'
b9fb8ee35b3cf5d73c30ca9874ca0daf20d5e3fc
DaishanHuang/python
/youtube/Tutorial-09_Sequences-and-Lists/main.py
194
3.6875
4
coloc = ['mincong','pape','charline'] print(coloc[0]) # mincong print(coloc[1]) # pape print(coloc[2]) # charline # Pay attention ! print(coloc[-1]) # charline coloc[0][2] # 'mincong'[2] # 'n'
a70b235ca5ecb8b7392d680f008b004d8da6cbcf
yui330/-
/tiktoktest3.py
1,160
3.546875
4
import re class money(): def inputdata(self): N = input() N = int(N) if N < 1 or N > 1000: print("N is error") return line = input() line = re.split(r'\s', line) line = [int(e) for e in line] if len(line) != N: print("error") return c = self.cost(N, line) print(c) def cost(self, N, line): self.c = 100 cost = [self.c] for i in range(N-1): cost.append(self.c) if line[i] > line[i+1]: if cost[i] < cost[i+1]: cost[i] = cost[i] + self.c self.costleft(line, cost, i) else: cost[i+1] = cost[i] + self.c print(cost) return self.costcount(cost) def costleft(self, line, cost, n): if line[n-1] > line[n]: cost[n-1] = cost[n-1] + self.c self.costleft(line, cost, n-1) def costcount(self, cost): c = sum(cost) return c if __name__ == '__main__': m = money() m.inputdata()
096ad52ee4f95913932548d78ce15d314e9a0268
thenerdygeek/Python-Help
/help.py
2,484
3.75
4
string='string' integer=10 floating=10.2 list1=[] while True: x=int(input("Help For:-\n\t1)Integer\n\t2)Float\n\t3)String\nEnter your choice: ")) count=1 z=(input("Would you like to 'print' or save on a 'notepad'.:")) if z=='print': if(x==1): list1=dir(integer) for i in list1: print(count,') ',i) count+=1 print(count,') All') y=int(input("Enter Your Choice: ")) if y<count: result= getattr(integer,list1[y-1]) print(list1[y-1],end=':-- ') print(help(result),end='\n'*5) print('_'*80,end='\n'*2) elif(y==count): for i in list1: result= getattr(integer,i) print(i,end=':-- ') print(help(result),end='\n'*5) print('_'*80,end='\n'*2) else: break elif(x==2): list1=dir(floating) for i in list1: print(count,') ',i) count+=1 print(count,') All') y=int(input("Enter Your Choice: ")) if y<count: result= getattr(floating,list1[y-1]) print(list1[y-1],end=':-- ') print(help(result),end='\n'*5) print('_'*80,end='\n'*2) elif(y==count): for i in list1: result= getattr(floating,i) print(i,end=':-- ') print(help(result),end='\n'*5) print('_'*80,end='\n'*2) else: break elif(x==3): list1=dir(string) for i in list1: print(count,') ',i) count+=1 print(count,') All') y=int(input("Enter Your Choice: ")) if y<count: result= getattr(string,list1[y-1]) print(list1[y-1],end=':-- ') print(help(result),end='\n'*5) print('_'*80,end='\n'*2) elif(y==count): for i in list1: result= getattr(string,i) print(i,end=':-- ') print(help(result),end='\n'*5) print('_'*80,end='\n'*2) else: break else: break elif z=='notepad': print('Code Under Progress')
04a944d6c356c78d0ff31c8f3406ac40f6921bd5
datarocksAmy/APL_Python
/ICE/ICE04/ICE04 Wikipage.py
1,929
3.59375
4
# ------------------------------------------------------------------------------------------------------------ # * Python Programming for Data Scientists and Engineers # * ICE #4 Parse wikipage and extract the headers of the page. # * BeautifulSoup + Requests Library # * #11 Chia-Hui Amy Lin # ------------------------------------------------------------------------------------------------------------ # Import Libraries import requests from bs4 import BeautifulSoup # Function def header_finder(soup, header_name, header_num_list, header_dic): ''' Extract any possible headers in div from the page ''' for div in soup: for idx in range(len(header_num_list)): heading = div.find("h" + header_num_list[idx]) if heading is not None: header_dic[header_name].append(heading.text) return header_dic # Variables header_num = ["1", "2", "3", "4", "5", "6", "7"] # possible header numbers headerdic = {"div Header": [], "body Header": []} # Dictionary to store headers for div and body URL_Taiwan_wiki = "https://en.wikipedia.org/wiki/Taiwan" # Obtain the html code using requests page_info_response = requests.get(URL_Taiwan_wiki) # Parse Html info using BeautifulSoup html_soup = BeautifulSoup(page_info_response.text, "html.parser") # Find all lines that start with 'div' and 'body' div_result = html_soup.find_all('div') body_content = html_soup.find_all('body') # Call function header_finder to get all header info and store in the dictionary div_header = header_finder(div_result, "div Header", header_num, headerdic) body_header = header_finder(body_content, "body Header", header_num, headerdic) # Output the results for 'div' and 'body' print("< 'div' Headers >") print(headerdic["div Header"]) print("----------------------------------------------------------------------------------------------") print("< 'body' Headers >") print(headerdic["body Header"])
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))
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)
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)
008311dfd41940a63087d41c7579f3b72eb6743b
datarocksAmy/APL_Python
/ICE/ICE06/ICE06 - Linear Regression.py
1,424
3.890625
4
# ------------------------------------------------------------------------------------------------------------ # * Python Programming for Data Scientists and Engineers # * ICE #6 Linear Regression with numpy + matplotlib # * #11 Chia-Hui Amy Lin # ------------------------------------------------------------------------------------------------------------ # Libraries import numpy as np import matplotlib.pyplot as plt from pylab import figtext from sklearn import linear_model # x, y data points x_axis = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] y_axis = [1, 3, 2, 5, 7, 8, 8, 9, 10, 12] # Reshape the x and y numpy array x_axis = np.reshape(x_axis, (len(x_axis), 1)) y_axis = np.reshape(y_axis, (len(y_axis), 1)) # Build a LR model LR_Model = linear_model.LinearRegression() # Throw the data points into the model LR_Model.fit(x_axis, y_axis) # Calculate the coefficient of the LR model coefficient = LR_Model.coef_ # Plot the data points on the graph plt.scatter(x_axis, y_axis, color='red') # Plot the Linear Regression Line plt.plot(x_axis, LR_Model.predict(x_axis), color='blue', linewidth=3) # Title for the graph plt.suptitle("Linear Regression", fontsize=30) # X legend plt.xlabel("x-axis", fontsize=20) # Y legend plt.ylabel("y-axis", fontsize=20) # Sub texts at the bottom of the graph plt.subplots_adjust(bottom=0.25) figtext(.1, .09, "* Coefficient :" + str(coefficient), fontsize=16) # Output the graph plt.show()
1e0a31556ab37f2c1c6ac3799c06899a0531aa87
mmax5/project-euler
/Problem 32.py
1,437
3.984375
4
# -*- coding: iso-8859-15 -*- """ We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. The product 7254 is unusual, as the identity, 39 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital. Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital. HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum. """ digits = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] import itertools def is_pandigital(n): #3x3 #if int(''.join(n[0:2])) * int(''.join(n[3:5])) == int(''.join(n[6:8])): # return int(''.join(n[6:8])) #1 x 4 if int(''.join(n[0])) * int(''.join(n[1:4])) == int(''.join(n[5:8])): return int(''.join(n[5:8])) #2 x 4 #if int(''.join(n[0:1])) * int(''.join(n[2:5])) == int(''.join(n[6:8])): # return int(''.join(n[6:8])) #2 x 3 if int(''.join(n[0:1])) * int(''.join(n[2:4])) == int(''.join(n[5:8])): return int(''.join(n[5:8])) return 0 ### 1 x 4 = 4 ### 2 x 3 = 4 total = [] for x in itertools.permutations(digits): if is_pandigital(x) != 0: print x print is_pandigital(x) if is_pandigital(x) not in total: total.append(is_pandigital(x)) print sum(total)
b58b88e52af5404e379189e3744b42ee535838fd
mmax5/project-euler
/Problem52.py
586
3.734375
4
__author__ = 'mikemax' """It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits.""" def test_number(x): for i in [2, 3, 4, 5, 6]: for dig in str(x): if dig not in str(x*i): return False for dig in str(x*i): if dig not in str(x): return False return True for x in xrange(1, 1000000): if test_number(x): print x break
1fa6d1b0e7de65b9f52999887cfb1a4827d615a1
mmax5/project-euler
/Problem 28.py
466
4
4
''' Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 It can be verified that the sum of the numbers on the diagonals is 101. What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way? ''' def spiral(x): x = (x-1)/2 return 16/3*x**3 + 10*x**2 + 26/3*x + 1 print (spiral(1001))
0016c5ca8a1ef3d15ac7e3351e9434464aeec6f7
mmax5/project-euler
/Problem 24.py
540
3.859375
4
""" A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are: 012 021 102 120 201 210 What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? """ import itertools a = list(itertools.permutations([0,1,2,3,4,5,6,7,8,9])) print "".join([str(x) for x in a[1000000-1]])
2474eb0b564ed43645ec3e5914bcad6ff2496453
dunaevai135/algos_ITMO_2019
/oe/5w/priorityqueue.py
2,330
3.953125
4
from edx_io import edx_io def heappush(heap, item): heap.append(item) siftdown(heap, 0, len(heap)-1) def heappop(heap): """Pop the smallest item off the heap, maintaining the heap invariant.""" lastelt = heap.pop() # raises appropriate IndexError if heap is empty if heap: returnitem = heap[0] heap[0] = lastelt siftup(heap, 0) return returnitem return lastelt def siftup(heap, pos): endpos = len(heap) startpos = pos newitem = heap[pos] # Bubble up the smaller child until hitting a leaf. childpos = 2*pos + 1 # leftmost child position while childpos < endpos: # Set childpos to index of smaller child. rightpos = childpos + 1 if rightpos < endpos and not heap[childpos] < heap[rightpos]: childpos = rightpos print("A") # Move the smaller child up. heap[pos] = heap[childpos] pos = childpos childpos = 2*pos + 1 # The leaf at pos is empty now. Put newitem there, and bubble it up # to its final resting place (by sifting its parents down). heap[pos] = newitem siftdown(heap, startpos, pos) def siftdown(heap, startpos, pos): newitem = heap[pos] # Follow the path to the root, moving parents down until finding a place # newitem fits. while pos > startpos: parentpos = (pos - 1) >> 1 parent = heap[parentpos] if newitem < parent: heap[pos] = parent pos = parentpos continue break heap[pos] = newitem def main(io): heap = [] # fo= open("output.txt","w") # fi = open('input.txt', 'r') n = io.next_int() arr = [0]*(10**6) for i in range(0, n): inp = io.next_token() if inp == b'A': p = io.next_int() heappush(heap, p) arr[i] = p elif inp == b'X': if len(heap)==0: io.writeln("*") continue pop = heappop(heap) io.writeln(str(pop)) # fo.write(str(pop)) # fo.write("\n") # TODO elif inp == b'D': p = io.next_int() oldNum = arr[p-1] newNum = io.next_int() arr[p-1] = newNum ind = heap.index(oldNum) heap[ind] = newNum # heapq._siftdown(heap, 0, ind) # heapq._siftup(heap, ind) siftdown(heap, 0, ind) else: print(inp) if __name__ == "__main__": with edx_io() as io: main(io)
b35fdead2749686c0f517ec5891726b95dd2dd5d
xuezhaoit/learn_python
/python_5_AdvancedFun.py
1,310
3.640625
4
# # -*- coding: utf-8 -*- # import sys # import io # sys.stdout=io.TextIOWrapper(sys.stdout.buffer,encoding='utf8') ''' 高阶函数:map/reduce、filter、sorted 返回函数 匿名函数 装饰器 偏函数 ''' # ---------高阶函数------------- # -----------map-------------- # def fun1(args): # return args * args # r = map(fun1, range(3)) # print (list(r)) # # ---------reduce----------------- # def fun2(x,y): # return x + y # from functools import reduce # print (reduce(fun2,[1,2,3,4,5])) # ---------filter---------------- def fun3(x): return x % 2 ==1 print(list(filter(fun3,[1,2,3,4,5,6]))) # ----------sorted-------------------- print(sorted([36, 5, -12, 9, -21])) print(sorted([36, 5, -12, 9, -21], key=abs)) # ---------返回函数------------- # ---------匿名函数------------- # lambda表示匿名函数 # lambda x: x * x 等效 # def f(x): # return x * x # ---------装饰器------------- # 在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。 # ---------偏函数------------- # functools.partial的作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数 import functools int2 = functools.partial(int, base=2) print(int2('1010101'))
d266471c8be63888f5e60dad137784395dafb9b4
ghyhoiu/learn-python
/6.Functional programming/05.py
215
3.75
4
# 对于一个列表,偶数组成新的列表 # 定义过滤函数 # 过滤函数要求有输入,有布尔值 def isEven(a): return a % 2 == 0 l = [1,23,2,45,3,4,5] l1=filter(isEven,l) for i in l1: print(i)
d53c4e77b2b0d89e654e491674045eade6a694cf
ghyhoiu/learn-python
/6.Functional programming/01.py
322
3.828125
4
# lambda表达式 # 以lambda开头 # 紧跟参数(如果有的话) # 参数后面用逗号和表达式分开 # 只是一个表达式,没有return # 计算一个数的123倍(单个参数) stm = lambda x:x * 123 print(stm(12)) # 计算三个数字的加法(多个参数) stm2 = lambda a,b,c: a + b + c print (stm2(12,3,5))
a6a266b9b8e8b8663221534179f7caa18c62c3e9
ghyhoiu/learn-python
/3.Exception handling/02.py
1,011
3.953125
4
# 简单异常案例 # 给出提示 try: num = int(input("请输入你要输入的数字(整数):")) rst = 100/num print("计算结果是{0}".format(rst)) # 捕获一个异常,把异常实例化,出错信息会在实例里 # 注意以下写法: # 以下语句是捕获 ZeroDivisionError异常并并实例化 # 如果出现了多种错误,要把越具体的情况,越往前放 except ZeroDivisionError as e: print("你为什么要输入{0},你还能干点啥???????".format(num)) print(e) exit() except ValueError as e: print("省点心吧,看不见要输入整数吗?") print(e) except NameError as e: print("连名字都能打错,自己考虑吧") print(e) exit() except AttributeError as e: print("对象没有这个属性,要不再试试") print(e) exit() # 如果写上下面这句话,所有的错误都会被拦截 # 下面这句话一定是最后一个exception except Exception as e: print("我也不知道哪里错了") print(e) exit()
f28c8b94e19ffab49c2b76712243df6d2697c759
ghyhoiu/learn-python
/3.Exception handling/01.py
266
3.6875
4
# 简单异常案例 try: num = int(input("请输入你要输入的数字(整数):")) rst = 100/num print("计算结果是{0}".format(rst)) except: print("你为什么要输入{0},你还能干点啥".format(num)) # exit是退出程序 exit()
5fdbe6879dbd660e9e729eee18913d5f0d3e00b6
ghyhoiu/learn-python
/2.oop/07.py
468
3.78125
4
# __call__举例 class A(): def __init__(self, name=0): print("已经被调用") def __call__(self): print("再一次被调用") def __str__(self): return"小明是个好学生" # 这时将对象变为字符串使用 a = A() a() print(a) class B(): name = "Noname" age = 18 def __getattr__(self,item): print("没有找到哦") b = B() print(b.name) print(b.attr) # 这时不会报错,只会用魔法函数
edc6d34d72440134779c7a6cd3ceaecd42c903b9
RevathiJambunathan/amrex
/Tools/Postprocessing/python/column_depth.py
2,843
3.703125
4
#!/usr/bin/env python import sys import numpy def countValidLines(iterableObject): """ Here we count the number of lines in the iteratableObject that don't start with a comment (#) character. The iterableObject can be a file, in which case we rewind the file to the beginning.""" import types numGoodLines = 0 for line in iterableObject: if not line.lstrip().startswith("#"): numGoodLines +=1 # if this is a file, rewind it if type(iterableObject) is types.FileType: iterableObject.seek(0) return numGoodLines def columnDepth(inputFile,columnDepthStart): """ This method takes in a file specifying the density as a function of radius and calculates the column depth as a function of radius, starting with some specified initial column depth. That is, we integrate some profile, and output the integrated profile to some output file. The input format is given as : # some headers stuff # more headers # any number of header lines <radius_values> <density_values> The output profile will be given at the same coordinates as the input file.""" if inputFile: try: fh = open(inputFile,'r') nLines = countValidLines(fh) data = fh.read() fh.close() except IOError: print 'Could not open file %s for reading.' % inputFile sys.exit(1) else: data = sys.stdin.readlines() nLines = countValidLines(data) print nLines print data[0] r = numpy.zeros(nLines,numpy.float64) density = numpy.zeros(nLines,numpy.float64) columnDepth = numpy.zeros(nLines,numpy.float64) columnDepth[-1] = columnDepthStart pt = 0 for line in data: if line.lstrip().startswith("#"): continue line = line.split() r[pt] = line[0] density[pt] = line[1] pt += 1 # trapezoidal integration for pt in range(nLines-2,-1,-1): dr = r[pt]-r[pt+1] columnDepth[pt] = -0.5e0*dr*(density[pt]+density[pt+1]) + \ columnDepth[pt+1] for pt in range(nLines): print "%s %s" % (r[pt],columnDepth[pt]) if __name__ == "__main__": from optparse import OptionParser # this should be updated to something more recent, like argparse parser = OptionParser() parser.add_option("-f","--file", dest="file", help="input FILE containing density profile; if not specified, use stdin", default=None, metavar="FILE") parser.add_option("-s","--start", dest="start", default=0.0e0, help="starting value of column depth; defaults to %default") (options, args) = parser.parse_args() columnDepth(options.file,options.start)
41936305a845745c6d57198b17a967ffb7e85e2b
motakuw/x-o-game
/FINALEEEE - Copy.py
2,716
3.9375
4
def showboard(): print(board[0],'|',board[1],'|',board[2]) print(board[3],'|',board[4],'|',board[5]) print(board[6],'|',board[7],'|',board[8]) board=[0,1,2,3,4,5,6,7,8] print("LET'S START!!") a=input(str("Player 1, what's your name?? ")) b=input(str("Player 2, what's your name?? ")) print(a, 'is X and' ,b, 'is O, Ok?? :D ') showboard() def checkboard(): if (board[0]=='x'and board[1]=='x'and board[2]=='x') or(board[3]=='x'and board[4]=='x'and board[5]=='x')or(board[6]=='x'and board[7]=='x'and board[8]=='x')or(board[0]=='x'and board[3]=='x'and board[6]=='x')or(board[1]=='x'and board[4]=='x'and board[7]=='x')or(board[2]=='x'and board[5]=='x'and board[8]=='x')or(board[0]=='x'and board[4]=='x'and board[8]=='x')or(board[2]=='x'and board[4]=='x'and board[6]=='x'): print('WINNER IS ',a, ' \(^O^)/') break elif(board[0]=='o'and board[1]=='o'and board[2]=='o')or(board[3]=='o'and board[4]=='o'and board[5]=='o')or(board[6]=='o'and board[7]=='o'and board[8]=='o')or(board[0]=='o'and board[3]=='o'and board[6]=='o')or(board[1]=='o'and board[4]=='o'and board[7]=='o')or(board[2]=='o'and board[5]=='o'and board[8]=='o')or(board[0]=='o'and board[4]=='o'and board[8]=='o')or(board[2]=='o'and board[4]=='o'and board[6]=='o'): print('WINNER IS ',b, ' \(^O^)/') def repeatP1(): print(a,(' Please pick a spot(0-8):')) P1=int(input()) if board[P1]!='x' and board[P1]!='o': board[P1]='x' showboard() else: print("oops! it's taken!!") repeatP1() def repeatP2 (): print(b,(' Please pick a spot(0-8):')) P2=int(input()) if board[P2]!='x' and board[P2]!='o': board[P2]='o' showboard() else: print("oops! it's taken!!") repeatP1() z=0 while True : print(a,(' Please pick a spot(0-8):')) P1=int(input()) if board[P1]!='x' and board[P1]!='o': board[P1]='x' checkboard() showboard() else: print("oops! it's taken!!") repeatP1() check = True for i in range (9) : if board[i] != "x" and board[i] != "o" : check = False break if check == True : break print(b,(' Please pick a spot(0-8):')) P2=int(input()) if board[P2]!='x' and board[P2]!='o': board[P2]='o' checkboard() showboard() else: print("oops! it's taken!!") repeatP2() print("IT'S A DRAW!!!! \\(*____*)//")
5c6ce8379d2c4dc702b20cb252db1d584af6f997
215836017/PythonDemos
/DemoReptile/01_urllib/001_urllib_urlopen.py
1,821
3.515625
4
import urllib.request as request import urllib.parse as parse ''' 最基础的HTTP库有:urllib, httplib2, requests, treq等 ''' response = request.urlopen('https://www.python.org/') print('test 111 : ', response) # print('test 222 : ', response.read().decode('utf-8')) # 结果跟网页源代码是一样的 print('test 333 : ', type(response)) # test 333 : <class 'http.client.HTTPResponse'> --- 说明了urllib是一个Python内置的Http相关库 print('test 444: ', response.status) print('test 555: ', response.getheaders()) print('\ntest 666: ', response.getheader('Server')) print('test 666: ', response.getheader('Connection')) print('test 666: ', response.getheader('Content-Type')) print('test 666: ', response.getheader('Date')) print('test 666: ', response.getheader('Vary')) ''' urllib.request 模块提供了最基本的构造Http请求的方法,利用它可以模拟浏览器的一个请求发起过程。 同时它还带有处理授权验证、重定向、浏览器Cookies以及其他内容。 ''' ''' urlopen的其他参数: urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, *, cafile=None, capath=None, cadefault=False, context=None) data: 1. 要传递该参数,需要使用byte()方法将参数转化为字节。 2. 如果传递了该参数,那么请求方式就不再是Get方式,而是Post方式。 timeout: 超时时间,单位为妙 context: 必须是ssl.SSLContext类型,用来指定SSL设置 cafile: CA证书 capath: CA证书的路径 cadefault: 已经弃用 ''' data = bytes(parse.urlencode({'Python': "Hello"}), encoding='utf-8') response = request.urlopen('http://httpbin.org/post', data) # response = request.urlopen('http://httpbin.org/post', data, timeout=0.1) # 需要用try except print('\n\ntest 777 :', response.read())
d3d19fd1c3c69a151114b1e73aaab7df663665b9
ronicst/advpyDec2020
/my_modules/my_reduce.py
305
3.890625
4
from functools import reduce # reduce is part of the functional programmnig tools # using reducers def add_r(x, y): return x+y if __name__ == '__main__': print(reduce(add_r, range(1, 99, 3))) # start at 1, stop at 98, every third member print( reduce( lambda x, y: x * y, range(1,6) ) )
92881d6a747c8f9b0e3096a6c88d8dcabb0eb4e5
ronicst/advpyDec2020
/my_performance/thread_semaphore.py
882
3.796875
4
from threading import Thread, Event, Lock, BoundedSemaphore import time class DemoSem: def __call__(self, name): self.name = name global sem sem.acquire() time.sleep(2) sem.release() print(f'{self.name} done') if __name__ == "__main__": # we need a global semaphore instance sem = BoundedSemaphore(3) # this semaphore eill allow up to three threads at a time dX = DemoSem() dY = DemoSem() dZ = DemoSem() dA = DemoSem() dB = DemoSem() tA = Thread(target=dA, args=('A')) tB = Thread(target=dB, args=('B')) tX = Thread(target=dX, args=('X')) tY = Thread(target=dY, args=('Y')) tZ = Thread(target=dZ, args=('Z')) tA.start() tB.start() tX.start() tY.start() tZ.start() tA.join() tB.join() tX.join() tY.join() tZ.join() print('all done')
0e57e58c829c23f85e3a4a325fa73f0bd0ec9ab0
ronicst/advpyDec2020
/my_performance/threaded_class.py
1,310
3.96875
4
import sys import time import random from threading import Thread # Each thread has it's own stack # each thread SHARES the Heap, any Statics and any resources e.g. files # the Python kernel (single process) schedules the threads # declare a runnable class class MyRunnable(Thread): # if we extend the Thread class, we MUST provide a run method def __init__(self, name): Thread.__init__(self) self.name = name def run(self): for i in range(1,50): sys.stdout.write(self.name) # same as print() time.sleep( random.random()*0.1 ) if __name__ == "__main__": #call a function via start() (i.e. functional Threads) t3 = MyRunnable('Z') # this is more flexible than functional threads t2 = MyRunnable('Y') t1 = MyRunnable('X') # now we can start each thread (they all run in the SAME SINGLE process) # calling start invokes teh run() method of a runnable class t3.start() t2.start() t1.start() # the main calling thread is blocked until ALL threads terminate # the join method is also needed (so we know when they terminate) t1.join() # send any output back to the main thread t2.join() t3.join() # we will not be able to run ANY further code until ALL threads have terminated
0eb67f97c69a15f4a28b57bc32aef315ca01f6ed
ronicst/advpyDec2020
/my_performance/thread_callback.py
1,052
3.828125
4
from threading import Thread import time import sys import random # declare a callable class class MyCallable: # nb this is not a runnable, so we treat it like functional def __call__(self, name): for i in range(1,50): sys.stdout.write(name) # same as print() time.sleep( random.random()*0.1 ) if __name__ == "__main__": #call a function via start() (i.e. functional Threads) c3 = MyCallable() # this is like functional - we call the __call_ method c2 = MyCallable() c1 = MyCallable() # call the __call__ cllback t1 = Thread(target = c1, args=('M',)) t2 = Thread(target = c2, args=('N',)) t3 = Thread(target = c3, args=('P',)) # now we can start each thread (they all run in the SAME SINGLE process) t3.start() t2.start() t1.start() # the main calling thread is blocked until ALL threads terminate # the join method is also needed (so we know when they terminate) t1.join() # send any output back to the main thread t2.join() t3.join()
a35bdb250aa59a9b8c3ae66a582c34d313382a31
ronicst/advpyDec2020
/my_static/my_point_test.py
904
3.765625
4
import unittest from my_point import Point class testPoint(unittest.TestCase): # we need the TestCase class from unittest # set up the tests (this is run BEFORE each test) def setUp(self): self.point = Point(3, 5) self.pointDefault = Point() # default to 0, 0 # declare our suite of tests def testMoveBy(self): """testing the moveby method""" self.point.move_by(5, 2) # make an assertion self.assertEqual(self.point.__str__(), 'Point is at x:8 y:7') def testMoveByAgain(self): """testing the moveby method again""" self.point.move_by(-5, -2) # make an assertion self.assertEqual(self.point.__str__(), 'Point is at x:-2 y:3') def testDefault(self): self.assertEqual(self.pointDefault.__str__(), 'Point is at x:0 y:0') if __name__ == '__main__': # invoke the tests unittest.main()
017558f532bb7f977b12fd5687f7587f4e4bbaaf
ronicst/advpyDec2020
/using_db/my_insertmany_db.py
692
3.8125
4
import sqlite3 # we need a connection to the db conn = sqlite3.connect('books_db') # creates if not exist # now we can try to insert into the db cur = conn.cursor() # declare some data members b1 = [2, 'Climate', 'Greta', 'warm@chilly.se', 'bit of a hero'] b2 = [3, 'GGG', 'Timnit', 'ex@google.com', 'general good bod' ] b3 = [4, 'Miller', 'Gina', 'problem@gov.uk', '.....'] # id, surname, fname, email, notes cmd_str = ''' INSERT INTO book VALUES(?, ?, ?, ?, ?) ''' # consider injecting ' where 0=0 drop table - that is dangerous!!! try: for user in [b1, b2, b3]: cur.execute(cmd_str, user) except: pass # we really should handle eceptions! else: conn.commit() finally: conn.close()
f68c12017bd5d91b26671303872782ace9f70197
drafski89/interview-examples
/1_General/pairs_add_ten.py
501
3.71875
4
# Find pairs in an integer array whose sum is equal to 10 (bonus: do it in linear time) input_values = [5,2,3,5,6,2,8] if __name__ == "__main__": for first_value in range(0,len(input_values),1): for second_value in range(first_value,len(input_values),1): if input_values[first_value] + input_values[second_value] == 10: print "\nFirst value: \t" + str(input_values[first_value]) print "Second value: \t" + str(input_values[second_value])
29464287ca699df010e2a76086229b48eb7caa6b
drafski89/interview-examples
/1_General/rotated_array.py
765
3.953125
4
# Given 2 integer arrays, determine of the 2nd array is a rotated version of the 1st array. # Ex. Original Array A={1,2,3,5,6,7,8} Rotated Array B={5,6,7,8,1,2,3} a = [1,2,3,4,5,6,7,8] b = [5,6,7,8,1,2,3,4] def check_rotated_arrays(a, b): # check that the lengths are the same if len(a) != len(b): return False # check find the start point of a inside b start_position = 0 for x in range (0, len(a)): if b[x] == a[0]: start_position = x break # check if it is a rotation for a_pos in range(0, len(a)): b_pos = (start_position + a_pos) % len(a) if a[a_pos] != b[b_pos]: return False return True if __name__ == "__main__": print check_rotated_arrays(a, b)
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))
b2a16d0cf8c6db546496e8a3f16da54a1af67ece
lelong03/python_algorithm
/array/quick_sort.py
1,785
3.796875
4
def quicksort(alist): quicksort_helper(alist, 0, len(alist)-1) def quicksort_helper(alist, first, last): if last < first: return pivot = alist[first] split_point = partion(alist, first, last, pivot) quicksort_helper(alist, first, split_point-1) quicksort_helper(alist, split_point+1, last) def partion(alist, first, last, pivot): pivot_idx = first first = first + 1 while first <= last: while first <= last and alist[first] < pivot: first += 1 while first <= last and alist[last] > pivot: last -= 1 if first <= last: alist[first], alist[last] = alist[last], alist[first] alist[last], alist[pivot_idx] = alist[pivot_idx], alist[last] return last # def partion(alist, first, last, pivot): # pivot_idx = first # first = pivot_idx + 1 # while first <= last: # while first <= last and alist[first] < pivot: # first += 1 # # while first <= last and alist[last] > pivot: # last -= 1 # # if first <= last: # alist[first], alist[last] = alist[last], alist[first] # # alist[last], alist[pivot_idx] = alist[pivot_idx], alist[last] # return last # # # def find_kth_number(alist, k): # return find_kth_number_helper(alist, 0, len(alist)-1, k) # # # def find_kth_number_helper(alist, first, last, k): # pivot = alist[first] # split_point = partion(alist, first, last, pivot) # if k == split_point: # return alist[k] # elif k < split_point: # return find_kth_number_helper(alist, first, split_point-1, k) # else: # return find_kth_number_helper(alist, split_point+1, last, k-split_point) a = [10, 9, 5, 11, 15, 2, 4, 1, 18, 8] quicksort(a) print a