blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
362337f5ab892026790f7e604d5a9534cd61f366 | MNataliaCosta/lec4 | /lec4.py | 715 | 3.796875 | 4 | class Student():
def __init__ (self, name, type):
self.name = name
self.type = type #defines whether undergrad or grad
#set up other attributes
pass
def apply():
#student can apply to either university or college
#create an university instance, specifying with univerisity of college it is
pass
class Undergrad(Student):
def __init__ (self):
self.type = undergrad
pass
class Grad(Student):
pass
class University:
def __init__(self):
self.student = Student()
def enroll_undergrad():
#university can enroll only undergrads
pass
class College(University):
#enrolls grad students
pass
|
0663256ee03a3d6384ccb9243cc7928eaa7440be | browniwils/holbertonschool-interview | /0x09-utf8_validation/0-validate_utf8.py | 1,185 | 4.21875 | 4 | #!/usr/bin/python3
'''utf-8 validation'''
def validUTF8(data):
'''determines if a given data set represents a valid UTF-8 encoding
Args:
Data: represented by a list of integers
Return: True if data is a valid UTF-8 encoding, else return False
'''
num_bytes = 0
# Masks to check the most significant bits (8,7)
mask1 = 1 << 7
mask2 = 1 << 6
for num in data:
mask = 1 << 7
if num_bytes == 0:
# determine amount of bytes of data
while mask & num:
num_bytes += 1
mask = mask >> 1
# character has 1 byte
if num_bytes == 0:
continue
# if data has more than 4 bytes or equal to 1 are invalid
if num_bytes == 1 or num_bytes > 4:
return False
else:
# validate if next bytes of number follow utf-8 encoding (10xxxxxx)
if not (num & mask1 and not (num & mask2)):
return False
# decrease number of bytes for next number
num_bytes -= 1
# all data are utf-8 encoding valid
# there aren´t missing bytes
return num_bytes == 0
|
64768ff2ca15e80039bde357865ff927b35f8c4a | gulimran/data-science-machine-learning | /statistics-basic/covariance.py | 1,227 | 3.875 | 4 | # Covariance
# Covariance measures how two variables vary in tandem from their means.
# An e-commerce company interested in finding a correlation between page speed
# (how fast each web page renders for a customer) and how much a customer spends.
# numpy offers covariance methods, but we'll do it the "hard way" to show
# what happens under the hood. Basically we treat each variable as a vector of
# deviations from the mean, and compute the "dot product" of both vectors.
# Geometrically this can be thought of as the angle between the two vectors in
# a high-dimensional space, but you can just think of it as a measure of
# similarity between the two variables.
# Here page speed and purchase amount totally random and independent of
# each other; a very small covariance will result as there is no real correlation
import numpy as np
from pylab import *
def de_mean(x):
xmean = mean(x)
return [xi - xmean for xi in x]
def covariance(x, y):
n = len(x)
return dot(de_mean(x), de_mean(y)) / (n-1)
pageSpeeds = np.random.normal(3.0, 1.0, 1000)
purchaseAmount = np.random.normal(50.0, 10.0, 1000)
scatter(pageSpeeds, purchaseAmount)
show()
print covariance (pageSpeeds, purchaseAmount) |
d117a3b5fc1ff6f43a26cfd628c871a4df949e42 | saibi/python | /byte/listgen.py | 248 | 3.75 | 4 | #!/usr/bin/env python
# -*- coding: utf8 -*-
points = [ { 'x': 2, 'y':3 },
{ 'x' : 4, 'y' : 1 }]
print points
points.sort(key = lambda i : i['y'])
print points
listone = [2, 3, 4]
listtwo = [2*i for i in listone if i > 2]
print listtwo
|
ef1ae1aa0a24c308b30b1e7dd1c6216f344114bc | nemzutkovic/Carleton-University-CS-Guide | /COMP 1405/Tutorial 1 (100)/t1q6.py | 1,246 | 3.875 | 4 | # 1 - The numbers are 21 and 23.
# 2 - Starting with the number in question, you must divide it by two, and then either subtract or add one.
# 3
magicnum = 44
num1 = magicnum/2 - 1
num2 = magicnum/2 + 1
if num1 % 2 == 1 and num2 % 2 == 1:
print("The two numbers are: " + str(num1) + " and " + str(num2))
else:
print("No two consecutive numbers for " + str(magicnum) + " exists.")
# 4 / 5
# Go through entire list one number at a time.
# Keep track of the max number (n).
# If the current element is greater than n, overwrite n with the current element, otherwise proceed to the next number.
# 6
# Draw the base of the house with one horizontal line.
# Draw the sides of the house with two vertical lines. Each vertical line will connect to an end point of the bottom line.
# Draw the ceiling of the house by connnecting the top points of the vertical lines. You have now formed a square.
# Draw a 45 degree line from the top left corner of the square, so that it is extending above the top vertical line. Ensure that the line only goes halfway.
# Draw another 45 degree line from the top right corner of the square, so that it connects with the other 45 degree line.
# You have just drawn the frame of your house! |
40d29cae7ce4c9546de00dc1a907e9531f77a1c9 | mikilir/first-quarter | /first.py | 360 | 3.84375 | 4 | a = 10
b = 30
print('Переменные a и b - ', a,'и', b)
numb_1 = int(input('Введите первое число: '))
string_1 = input('Введите первую строку: ')
numb_2 = int(input('Введите второе число: '))
string_2 = input('Введите вторую строку: ')
print(numb_1, numb_2, string_1, string_2) |
a96c633507ae4615304f1948be7b69b44abad075 | joanna408/recipe_organizer | /RecipeOrganizer.py | 29,544 | 3.859375 | 4 | import json
class Ingredient:
""" Ingredient class contains ingredient name, amount and unit of measurement. """
def __init__(self, amount, unit, ing_name):
self.name = ing_name.lower()
self.unit = unit.lower()
self.amount = float(amount)
def __repr__(self):
return "%.2f" % self.amount + ' ' + str(self.unit) + ' ' + str(self.name)
class Recipe:
""" Recipe class contains all the information contained in a recipe, including name, source, categories, notes, \
estimated time, rating, difficulty level, ingredients. """
def __init__(self, rec_name, rec_source):
self.name = rec_name.title()
self.source = rec_source
self.categories = []
self.notes = []
self.rating = ''
self.level = ''
self.ingredients = []
self.time = ''
self.serving_size = ''
def set_categories(self, rec_categories):
self.categories.append(rec_categories.title())
def set_notes(self, rec_notes):
self.notes.append(rec_notes)
def set_rating(self, rec_rating):
self.rating = rec_rating
def add_ingredients(self, new_ingredients):
if not self.ingredients:
self.ingredients.append(new_ingredients)
else:
a = False
for k in self.ingredients:
if new_ingredients.name == k.name:
a = True
else:
a = False
if a:
for k in self.ingredients:
if new_ingredients.name == k.name:
if new_ingredients.unit == k.unit or new_ingredients.unit == (k.unit + 's'):
k.amount += new_ingredients.amount
else:
print('Please enter ingredient amount in ' + str(k.unit) + ' units.')
else:
self.ingredients.append(new_ingredients)
def set_level(self, skill_level):
self.level = skill_level
def set_time(self, rec_time):
self.time = rec_time
def set_serving_size(self, serving_size):
self.serving_size = serving_size
def __str__(self):
return ('\033[1m' + 'Name: ' + '\033[0m' + str(self.name) + '\n' + '\033[1m' + 'Source(s): ' + '\033[0m'
+ str(self.source) + '\n' + '\033[1m' + 'Categorie(s): ' + '\033[0m' + str(self.categories) + '\n'
+ '\033[1m' + 'Rating: ' + '\033[0m' + str(self.rating) + ' out of 5 stars \n' + '\033[1m'
+ 'Skill Level: ' + '\033[0m' + str(self.level) + '\n' + '\033[1m' + 'Estimated Time: ' + '\033[0m'
+ str(self.time) + '\n' + '\033[1m' + 'Extra Notes: ' + '\033[0m' + str(self.notes) + '\n' + '\033[1m'
+ 'Ingredients List ' + 'for ' + str(self.serving_size) + ' servings:' + '\033[0m'
+ str(self.ingredients))
def __repr__(self):
return str(self.name)
class MyFridge:
""" MyFridge class contains information about user's fridge inventory, specifically every ingredient name,
amount and unit of measurement."""
def __init__(self):
self.name = ''
self.amount = 0
self.unit = ''
self.inventory = json.load(open('fridgedata.txt'))
def update_fridge(self, inv_name, amount, unit):
# Update ingredient amount
self.name = inv_name.lower()
self.amount = amount
self.unit = unit.lower()
if self.name in self.inventory:
if self.unit == self.inventory[self.name][1] or self.unit == self.inventory[self.name][1] + 's':
current_inventory_value = float(self.inventory[self.name][0])
adding_value = float(self.amount)
current_inventory_value += adding_value
self.inventory[self.name] = [current_inventory_value, self.unit]
else:
print('Please enter ingredient amount in ' + str(self.inventory[self.name][1]) + ' units.')
else:
self.inventory[self.name] = [self.amount, self.unit]
return self.inventory
def __str__(self):
return 'Current inventory: ' + str(self.inventory)
class RecipeOrganizerController:
""" RecipeOrganizerController class contains the user's recipe database and carries out any action that seeks to
edit or access the recipe database"""
def __init__(self):
self.recipecollection = []
json_load = json.load(open('recipedata.txt'))
for j in json_load:
recipe_obj = Recipe(j["Name"], j["Source"])
recipe_obj.set_serving_size(j["Serving Size"])
recipe_obj.set_time(j["Time"])
recipe_obj.set_rating(j["Rating"])
recipe_obj.set_level(j["Level"])
for n in j["Notes"]:
recipe_obj.set_notes(n)
for cat in j["Categories"]:
recipe_obj.set_categories(cat)
for d in j["Ingredients"]:
ingredient_obj = Ingredient(d["Amount"], d["Units"], d["Name"])
recipe_obj.add_ingredients(ingredient_obj)
self.recipecollection.append(recipe_obj)
def add_recipes(self, recipe):
self.recipecollection.append(recipe)
def find_by_ingredient(self, ingredient_searched):
# Given a list of recipes and an ingredient, returns list of recipes that contain that ingredient. If user
# inputs a general query such as "cheese," all recipes with any kind of cheese ingredient will be returned.
found_recipes = []
for collection_item in self.recipecollection:
for ing_in_collection in collection_item.ingredients:
if ingredient_searched.lower() in ing_in_collection.name:
found_recipes.append(collection_item)
else:
continue
return found_recipes
def find_by_category(self, category):
# Given a list of recipes and a category, returns list of recipes within that category.
found_recipes = []
for recipe_item in self.recipecollection:
for rec_item in recipe_item.categories:
if rec_item == category.title():
found_recipes.append(recipe_item)
else:
continue
return found_recipes
def create_shopping_list(self, recipe_list):
# User selects the recipes they want and create_shopping_list creates a list of everything they
# need to buy
shopping_list = []
final_shopping_list = {}
recipe_name_list = []
for y in self.recipecollection:
recipe_name_list.append(y.name)
for p in recipe_list:
if p.title() not in recipe_name_list:
print(str(p) + ' ingredients unknown. Please return to main menu to add recipe to database.')
else:
for y in self.recipecollection:
if p.title() == y.name:
shopping_list.append(y.ingredients)
else:
continue
for shopping_item in shopping_list:
for z in shopping_item:
# If a list for ingredient name already exists, add z to that list
if z.name in final_shopping_list:
total_list = final_shopping_list[z.name]
for element in total_list:
# Set total to original amount of ingredient then add amounts from total list
if isinstance(element, float):
total = final_shopping_list[z.name][0]
total += element
final_shopping_list[z.name] = [total, z.unit, z.name]
else:
# If ingredient is not in the list, create new key-value pair in final_shopping_list
final_shopping_list[z.name] = [z.amount, z.unit, z.name]
return final_shopping_list
def update_shopping_list(self, current_inventory, shopping_list):
# Updates shopping list by looking at fridge inventory and gives the user the option to use what's available.
updated = {'Ingredients': 'Amount'}
for f in shopping_list:
for e in current_inventory.inventory:
# If ingredient name found in inventory, prompt user to choose whether they want to use available
# inventory. If yes, subtract needed amount from inventory and subtract amount needed from shopping
# list.
if e == f:
updated[f] = shopping_list[f]
needed = shopping_list[f][0]
existing = float(current_inventory.inventory[e][0])
if existing >= needed:
print(str(e).title() + ' found. Fridge inventory for ' + str(e) + ': '
+ str(existing) + ' ' + str(current_inventory.inventory[e][1]))
update_inv_option = input('Would you like to use the available inventory? Yes or No: ')
if update_inv_option.lower() == "yes":
existing -= needed
current_inventory.inventory[e][0] = existing
del updated[f]
print('\nFridge inventory updated. You have ' + str(current_inventory.inventory[e])
+ ' remaining \n')
elif update_inv_option.lower() == "no":
continue
else:
print('Invalid entry. Please enter Yes or No')
continue
else:
needed -= existing
current_inventory.inventory[e][0] = 0
updated[f] = [needed, shopping_list[f][1], shopping_list[f][2]]
elif f not in current_inventory.inventory:
updated[f] = shopping_list[f]
else:
continue
if len(updated) == 1:
recipe_shopping = ' No items needed. All ingredients availabe in fridge.'
else:
recipe_shopping_list = []
for u in updated:
recipe_shopping_list.append(str(updated[u]))
recipe_shopping = ' '.join(recipe_shopping_list[1:])
return 'Here\'s the shopping list based on your current inventory: ' + str(recipe_shopping) + '\n'
def check_inventory(self, current_inventory, recipe):
# Check if inventory has enough for a selected recipe
for product in recipe.ingredients:
for t in current_inventory.inventory:
if product.name not in current_inventory.inventory:
print('Missing from fridge: ' + str(product) + '\n')
break
if product.name == t:
inventory_value = float(current_inventory.inventory[t][0])
if inventory_value >= product.amount:
original_amount = inventory_value
print(str(t).title() + ' found. Fridge inventory for ' + str(t) + ': '
+ str(original_amount) + ' ' + str(current_inventory.inventory[t][1]))
update_inv_option = input('Would you like to use the available inventory? Yes or No: ')
if update_inv_option.lower() == "yes":
inventory_value -= product.amount
current_inventory.inventory[t][0] = inventory_value
print('Fridge inventory updated. You have ' + str(current_inventory.inventory[t])
+ ' remaining \n')
elif update_inv_option.lower() == "no":
continue
else:
print('Invalid entry. Please enter Yes or No')
continue
else:
print('Current fridge inventory only has ' + str(current_inventory.inventory[t])
+ '. ' + str(product) + ' needed \n')
return 'Your updated fridge inventory: ' + str(current_inventory.inventory) + '\n'
def __str__(self):
return str(self.recipecollection)
#############################################
# Sample Recipe Directory #
#############################################
SampleRecipeDirectory = RecipeOrganizerController()
#############################################
# Sample Inventory #
#############################################
SampleFridge = MyFridge()
#############################################
# User Interface #
#############################################
border = '-'
print(border.center(75, '-'))
welcome = 'Welcome to your Recipe Organizer!'
print('\033[1m' + welcome.center(75))
print('\033[0m' + border.center(75, '-'))
organizer = True
while organizer:
print('What would you like to do? \n')
print('1-add recipe\n')
print('2-search recipes by category\n')
print('3-search recipes by ingredient\n')
print('4-check or update my fridge\n')
print('5-create shopping list\n')
print('6-end program')
command = input('Enter one of the selections above to continue: ')
if command not in {'1', '2', '3', '4', '5', '6'}:
print('Invalid entry. Please enter a number between 1 - 6. ')
continue
if command == '1':
user_recipe_name = input('Please enter a recipe name: ')
for rec in SampleRecipeDirectory.recipecollection:
if rec.name == user_recipe_name:
user_prompt = input('Error: Recipe already exists. Type \'1\' to see recipe details or \'return\' to '
'return to main menu: ')
if user_prompt == '1':
print(rec)
else:
user_prompt = ''
if user_prompt == '1':
continue
if user_prompt == 'return':
continue
if user_recipe_name == '':
print('No recipe name was entered. Please try again.')
continue
user_recipe_source = input('Please enter a URL (followed by a space), or enter None: ')
if user_recipe_source == '':
print('No URL was entered. Please try again or enter None')
continue
user_recipe = Recipe(user_recipe_name, user_recipe_source)
SampleRecipeDirectory.add_recipes(user_recipe)
prompt = input('Would you like to fill out any more details for the recipe? Press any key for yes or enter '
'n for no. \n')
while prompt != 'n':
start = 'Let\'s fill out more details for this recipe!'
print(start.center(75, '-') + '\n')
options = [['a-set recipe category', 'b-give recipe a rating', 'c-set skill level'],
['d-set estimated time', 'e-add ingredients', 'f-set serving size'],
['g-add extra notes', 'h-see recipe', '']]
col_width = max(len(word) for row in options for word in row) + 2 # padding
for row in options:
print("".join(word.ljust(col_width) for word in row))
next_command = input("\nSelect from the menu above. (To exit, enter \"exit.\") ")
if next_command not in {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'exit'}:
print('Invalid entry. Please enter a letter between a-h, or exit to return to main menu.')
continue
if next_command == 'a':
user_recipe_category = input('Enter the category for this recipe (i.e. Meat, Pasta, Beverage, Dinner, '
'Lunch), or type \'skip\' to skip: ')
if user_recipe_category == '':
print('No category was entered. Please enter a category such as Meat, Vegetable, Dinner, etc.')
while user_recipe_category != 'skip':
if user_recipe_category.isdigit():
print('Invalid entry. Please enter a category such as Meat, Vegetable, Party, etc.')
continue
else:
user_recipe.set_categories(user_recipe_category)
user_recipe_category = input('Enter another category, or enter 1 to exit. ')
if user_recipe_category == '1':
break
if next_command == 'b':
user_recipe_rating = input('Enter the rating for this recipe. Rating is based on a 5 star scale, '
'or type \'end\' to skip. ')
if user_recipe_rating == 'end':
continue
elif user_recipe_rating == '':
print('Error: No rating was entered. Please try again.\n')
elif not user_recipe_rating.isdigit():
print('Error: Rating must be a number between 1-5.\n')
else:
if float(user_recipe_rating) > 5 or float(user_recipe_rating) < 1:
print('Error: Rating must be between 1-5, for this 5 star scale system.\n')
continue
else:
user_recipe.set_rating(user_recipe_rating)
if next_command == 'c':
user_recipe_level = input('Enter skill level for this recipe. Skill level scale: Easy, Medium, '
'Difficult. To skip, type \'skip\'. ')
if user_recipe_level == 'skip':
continue
elif user_recipe_level == '':
print('Error: No skill level was entered. Please try again.\n')
elif user_recipe_level.title() == 'Easy' or user_recipe_level.title() == 'Medium' \
or user_recipe_level.title() == 'Difficult':
user_recipe.set_level(user_recipe_level)
else:
print('Error: Invalid entry. Skill level must be Easy, Medium or Difficult.\n')
continue
if next_command == 'd':
user_recipe_time = input('Enter estimated time for this recipe. (i.e. 1 hour, 40 minutes) Please sum '
'up both prep time and cooking time. To skip, type \'skip\': ')
if user_recipe_time == 'skip':
continue
elif user_recipe_time == '':
print('Error: No time was entered. Please try again.\n')
elif not user_recipe_time[0].isdigit():
print('Error: Invalid format. Please enter amount of time plus unit of time i.e 5 minutes, '
'3 hours\n')
elif len(user_recipe_time.split()) < 2:
print('Error: Invalid entry. Please enter amount of time plus unit of time i.e 5 minutes, '
'3 hours\n')
continue
else:
user_recipe.set_time(user_recipe_time)
if next_command == 'e':
prompt2 = input('Let\'s get started! Press enter to continue or \'return\' for previous menu: ')
while prompt2 != 'return':
ingredient_name = input('Enter name of ingredient (i.e. salmon, broccoli, rice) or type \'skip\' '
'to skip: ')
if ingredient_name == '':
print('Error: Invalid entry. Please try again.\n')
continue
if ingredient_name == 'skip':
break
ingredient_amount = input('Enter amount of ingredient with units: '
'(i.e. 8 oz, 1.56 lb, 2 tsp, 2 whole (for eggs/fruits) or type '
'\'skip\' to skip: ').split()
if ingredient_amount != ['skip'] and len(ingredient_amount) < 2:
print('Error: Invalid entry. Please try again with the following format: 8 oz, 1.56 lb.\n')
continue
if ingredient_amount == ['skip']:
break
elif not ingredient_amount[1].isalpha():
print('Error: Invalid unit of measurement. Please try again\n')
continue
ingredient_amt = ingredient_amount[0]
if len(ingredient_amount) < 2:
ingredient_unit = input('Please enter the unit of measurement for this ingredient.')
ingredient_amount.append(ingredient_unit)
else:
ingredient_unit = ingredient_amount[1]
user_recipe_ingredients = Ingredient(ingredient_amt, ingredient_unit, ingredient_name.lower())
user_recipe.add_ingredients(user_recipe_ingredients)
if next_command == 'f':
user_recipe_serving = input(
'Enter serving size for this recipe (i.e. 1, 2, 3), or type \'skip\' to skip: ')
if user_recipe_serving == 'skip':
continue
elif user_recipe_serving == '':
print('No serving size was entered. Please try again.')
elif len(user_recipe_serving) > 1:
print('Please enter an integer.')
continue
else:
user_recipe.set_serving_size(user_recipe_serving)
if next_command == 'g':
user_recipe_notes = input('Enter additional notes for this recipe. (If none, type \'skip\' to skip): ')
while user_recipe_notes != 'skip':
user_recipe.set_notes(user_recipe_notes)
user_recipe_notes = input('Would you like to add anything else? (If no, type \'skip\' to skip): ')
if user_recipe_notes == 'skip':
continue
if next_command == 'h':
print(str(user_recipe) + '\n')
if next_command == 'exit':
break
if command == '2':
# Search recipes by category
category_list = []
for r in SampleRecipeDirectory.recipecollection:
for c in r.categories:
category_list.append(c)
category_list = set(category_list)
user_category = (input('Enter category (Available options: ' + str(category_list) + '): ')).title()
if SampleRecipeDirectory.find_by_category(user_category):
print('Found Recipes: ' + str(SampleRecipeDirectory.find_by_category(user_category)))
next_question = input('To see full recipe details, enter 1. To exit, enter "exit" ')
if next_question not in {'1', 'exit'}:
print('Invalid entry. Please enter 1 to see full recipe details or "exit" to exit. ')
if next_question == '1':
for x in SampleRecipeDirectory.find_by_category(user_category):
print(str(x) + '\n')
if next_question == 'exit':
continue
else:
category_list = []
for r in SampleRecipeDirectory.recipecollection:
for c in r.categories:
category_list.append(c)
category_list = set(category_list)
print('There were no matches. Here are the current categories in the database: '
+ str(category_list) + '\n')
if command == '3':
# Search recipes by ingredient
user_ingredient = input('Enter ingredient: ')
if SampleRecipeDirectory.find_by_ingredient(user_ingredient):
print('Found Recipes: ' + str(SampleRecipeDirectory.find_by_ingredient(user_ingredient)))
next_prompt = input('To see full recipe details, enter 1. To exit, enter "exit" ')
if next_prompt == '1':
for x in SampleRecipeDirectory.find_by_ingredient(user_ingredient):
print(str(x) + '\n')
else:
continue
else:
print('There were no matches.')
if command == '4':
# Check fridge for recipe ingredients and allow user to update fridge inventory
user_action = input("What would you like to do?\na: Check the fridge for a recipe\nb: Update what's in your "
"fridge\nEnter selection: ")
if user_action == 'a':
requested_recipe = input('Which recipe are you checking the fridge for? \nAvailable '
'options: '
+ str(SampleRecipeDirectory.recipecollection) + str(' '))
for item in SampleRecipeDirectory.recipecollection:
if requested_recipe.title() not in str(SampleRecipeDirectory.recipecollection):
print("Requested recipe is not in this database. Please select from the available "
"options below or return to the main menu to add new recipe. \nHere is the "
"current recipe database: " + str(SampleRecipeDirectory.recipecollection))
break
for ingredient in item.ingredients:
if item.name == requested_recipe.title():
print('Needed ingredients for ' + str(item.name) + ': ' + str(item.ingredients)
+ '\n')
user_inventory = SampleRecipeDirectory.check_inventory(SampleFridge, item)
print(user_inventory)
break
else:
break
if user_action == 'b':
print('\nLet\'s update what\'s in the fridge!\n')
inventory_prompt = ''
while inventory_prompt != 'q':
inventory_prompt = input('Enter the name of ingredient, or q to quit: ')
if inventory_prompt == 'q':
break
for v in SampleFridge.inventory:
if inventory_prompt.lower() == v:
print('Current inventory for ' + str(v) + ': ' + str(SampleFridge.inventory[v][0])
+ ' ' + str(SampleFridge.inventory[v][1]))
inv_amt = input('Enter the amount with units you\'d like to add to the fridge (Enter q to quit): '
'').split()
if inv_amt[0] == 'q':
break
else:
SampleFridge.update_fridge(inventory_prompt, inv_amt[0], inv_amt[1])
print('Updated inventory ' + str(SampleFridge.inventory[inventory_prompt]))
continue
if inventory_prompt == 'q':
continue
if command == '5':
# Create a shopping list
print('Let\'s create a shopping list! Here\'s the current recipe collection: '
+ str(SampleRecipeDirectory.recipecollection))
selected_option = input('Please enter the recipe(s) you\'d like to shop for (i.e. Sous Vide Salmon, Latte), '
'separated by ** (i.e. Latte ** Pork Chop, or q to quit: \n').split(' ** ')
if selected_option == 'q':
break
else:
initial_shopping_list = SampleRecipeDirectory.create_shopping_list(selected_option)
updated_shopping_list = SampleRecipeDirectory.update_shopping_list(SampleFridge, initial_shopping_list)
print(updated_shopping_list)
if command == '6':
json_data = []
for r in SampleRecipeDirectory.recipecollection:
json_ing = []
json_category = []
json_notes = []
name = r.name
source = r.source
categories = r.categories
notes = r.notes
ingredients = r.ingredients
rating = r.rating
level = r.level
time = r.time
serving = r.serving_size
for i in ingredients:
ing = {"Name": i.name, "Amount": i.amount, "Units": i.unit}
json_ing.append(ing)
for c in categories:
json_category.append(c)
for note in notes:
json_notes.append(note)
item = {"Name": name, "Source": source, "Categories": json_category, "Ingredients": json_ing,
"Notes": json_notes,
"Rating": rating, "Level": level, "Time": time, "Serving Size": serving}
json_data.append(item)
with open('recipedata.txt', 'w') as outfile:
json.dump(json_data, outfile)
with open('fridgedata.txt', 'w') as outputfile:
json.dump(SampleFridge.inventory, outputfile)
border = '-'
print(border.center(75, '-'))
thankyou = 'Thank you for using Recipe Organizer!'
print('\033[1m' + thankyou.center(75))
print('\033[0m' + border.center(75, '-'))
organizer = False
|
8aff573135893126d1397df3420a7d5d7c9abe4c | filipeferreira86/python | /.gitignore/lacos/continue.py | 335 | 4 | 4 | #finaliza o ciclo e reinicia do proximo ponto
num = int(input('Digite o numero para pular'))
for i in range(1,11,1):
if(i==num):
continue
print(i)
else:
print('escrevi de 1 a 10 pulando %d'%(num))
t=0
while(t<11):
t+=1
if(t%2==0):
continue
print('Somente impares')
print(t)
|
43fc64d8e2c284bccf651e74360f9ed9118eab63 | Siwangi/PythonDSA | /arrayreverse.py | 181 | 3.53125 | 4 | a = [1, 2, 3, 4, 5, 6, 10, 14]
#reverse the array
n = 0
b = []
length = len(a)
print(length)
for x in a:
length1 = length - n
b.append(a[length1-1])
n = n + 1
print(b)
|
d8ff0e05bfc5df1e0f9d05ace3f755a9bd43b816 | BarsTiger/Douson-ProgrammingWithPython | /Zverushka/ZverushkaWithAtribut.py | 929 | 3.9375 | 4 | class Critter(object):
def __init__(self, name):
print("Появилась на свет новая зверюшка!")
self.name = name
def __str__(self):
rep = "Объект класса Critter\n"
rep += "имя: " + self.name + "\n"
return rep
def talk(self):
print("Привет. Я - зверюшка - экземпляр класса Critter.")
crit1 = Critter("Барсик")
crit1.talk()
crit2 = Critter("Шарик")
crit2.talk()
print("Вывод объекта crit1 на экран: ")
print(crit1)
print("Непосредственный доступ к атрибуту crit1.name: ")
print(crit1.name)
print("\n")
print("Вывод объекта crit2 на экран: ")
print(crit2)
print("Непосредственный доступ к атрибуту crit2.name: ")
print(crit2.name)
input("\n\nНажмите Ent, чтобы выйти")
|
cda43141b8c690145ab640a06b6791e8da7854a2 | KevHg/tictactoe-cli | /main.py | 7,950 | 4 | 4 | import random
from copy import deepcopy
def print_board(board, max_width):
for row in range(len(board)):
for col in range(len(board)):
print("{:>{}}".format(board[row][col], max_width), end='')
print()
def win_check(board, player, n, row, col):
horizontal, vertical, diagonal_down, diagonal_up = True, True, True, True
# Check for horizontal win
for i in range(n):
if board[row][i] != player:
horizontal = False
# Check for vertical win
for i in range(n):
if board[i][col] != player:
vertical = False
# check for downwards diagonal (i.e. top left to bottom right)
for i in range(n):
if board[i][i] != player:
diagonal_down = False
# Check for upwards diagonal (i.e. bottom left to top right)
for i in range(n):
if board[i][n - 1 - i] != player:
diagonal_up = False
return horizontal or vertical or diagonal_down or diagonal_up
def vs_bot(board, n, possible_moves, difficulty):
max_width = len(str(n ** 2)) + 1
while True:
print_board(board, max_width)
num = int(input("Player - Input location: "))
if num < 0 or num >= (n ** 2):
print("Please choose a valid location!")
continue
row = num // n
col = num % n
if board[row][col] == 'O' or board[row][col] == 'X':
print("Cannot replace a player's piece!")
continue
board[row][col] = 'O'
possible_moves.remove(num)
if win_check(board, 'O', n, row, col):
print_board(board, max_width)
print("You win!")
break
if not possible_moves:
print_board(board, max_width)
print("Draw! Board is full.")
break
# Bot move begins here
print("Bot is thinking...")
bot_num = -1
check = random.randint(0, 100)
# Medium difficulty - 50% chance of bot being easy, 50% chance being abyssal
if difficulty == 2:
if check <= 50:
difficulty = 0
else:
difficulty = 4
# Hard difficulty - 20% chance of bot being easy, 80% chance being abyssal
elif difficulty == 3:
if check <= 20:
difficulty = 0
else:
difficulty = 4
print(possible_moves)
# Easy difficulty - Bot selects a random move
if difficulty == 1:
bot_num = random.choice(possible_moves)
# Abyssal difficulty - Bot utilizes minimax to find optimal move
elif difficulty == 4:
temp, bot_num = minimax(board, n, possible_moves, True)
if bot_num == -1:
print("Bot has forfeited! You won!")
break
row = bot_num // n
col = bot_num % n
board[row][col] = 'X'
possible_moves.remove(bot_num)
if win_check(board, 'X', n, row, col):
print_board(board, max_width)
print("You lost!")
break
if not possible_moves:
print_board(board, max_width)
print("Draw! Board is full.")
break
# Returns winning player (O or X), or D if draw
def find_winner(board, n):
for i in range(n):
horizontal = True
for j in range(0, n - 1):
if board[i][j] == '.':
break
if board[i][j] != board[i][j + 1]:
horizontal = False
if horizontal:
return board[i][0]
for i in range(n):
vertical = True
for j in range(0, n - 1):
if board[j][i] == '.':
break
if board[j][i] != board[j + 1][i]:
vertical = False
if vertical:
return board[0][i]
diagonal_down = True
for i in range(0, n - 1):
if board[i][i] == '.':
break
if board[i][i] != board[i + 1][i + 1]:
diagonal_down = False
if diagonal_down:
return board[0][0]
diagonal_up = True
for i in range(0, n - 1):
if board[i][n - 1 - i] == '.':
break
if board[i][n - 1 - i] != board[i + 1][n - 2 - i]:
diagonal_up = False
if diagonal_up:
return board[0][n - 1]
return 'D'
def minimax(board, n, possible_moves, maximizing_player):
best_move = -1
if not possible_moves:
winner = find_winner(board, n)
if winner == 'O':
return -1, best_move
elif winner == 'X':
return 1, best_move
else:
return 0, best_move
if maximizing_player:
value = -10
for move in possible_moves:
new_board = deepcopy(board)
new_possible = deepcopy(possible_moves)
row = move // n
col = move % n
new_board[row][col] = 'X'
new_possible.remove(move)
new_value, new_move = minimax(new_board, n, new_possible, False)
if new_value > value:
value = new_value
best_move = move
return value, best_move
else:
value = 10
for move in possible_moves:
new_board = deepcopy(board)
new_possible = deepcopy(possible_moves)
row = move // n
col = move % n
new_board[row][col] = 'O'
new_possible.remove(move)
new_value, new_move = minimax(new_board, n, new_possible, True)
if new_value < value:
value = new_value
best_move = move
return value, best_move
def vs_player(board, n, possible_moves):
max_width = len(str(n ** 2)) + 1
player = 'O'
while True:
print_board(board, max_width)
num = int(input("Player " + player + " - Input location: "))
if num < 0 or num >= (n ** 2):
print("Please choose a valid location!")
continue
row = num // n
col = num % n
if board[row][col] == 'O' or board[row][col] == 'X':
print("Cannot replace a player's piece!")
continue
board[row][col] = player
possible_moves.remove(num)
if not possible_moves:
print_board(board, max_width)
print("Draw! Board is full.")
break
if win_check(board, player, n, row, col):
print_board(board, max_width)
print("Player " + player + " wins!")
break
if player == 'O':
player = 'X'
else:
player = 'O'
def main():
while True:
n = int(input("Input size of tic-tac-toe board: "))
if n > 1:
break
else:
print("Board cannot be smaller than size 2!")
board = []
possible_moves = []
for i in range(n):
new_row = []
for j in range(n):
new_row.append(i * n + j)
possible_moves.append(i * n + j)
board.append(new_row)
print("Select game mode:")
while True:
print("1 - Easy bot")
print("2 - Medium bot")
print("3 - Hard bot")
print("4 - Abyssal bot (You're not expected to win!)")
print("5 - Multiplayer")
play_type = int(input("Your choice: "))
if play_type == 1:
vs_bot(board, n, possible_moves, 1)
break
elif play_type == 2:
vs_bot(board, n, possible_moves, 2)
break
elif play_type == 3:
vs_bot(board, n, possible_moves, 3)
break
elif play_type == 4:
vs_bot(board, n, possible_moves, 4)
break
elif play_type == 5:
vs_player(board, n, possible_moves)
break
else:
print("Invalid option!")
print("Game over! Press return to close...")
input()
main()
|
1e5899f646baf6504bc304deb3e894c3df02305f | conorheffron/python-sandbox | /src/main/python/practice1/test2.py | 527 | 3.734375 | 4 | NUM_ROWS = 5
NUM_COLS = 9
# construct a matrix
my_matrix = {}
for row in range(NUM_ROWS):
row_dict = {}
for col in range(NUM_COLS):
row_dict[col] = row * col
my_matrix[row] = row_dict
print(my_matrix)
# print the matrix
for row in range(NUM_ROWS):
for col in range(NUM_COLS):
print(my_matrix[row][col], end=" ")
print()
print([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 2, 4, 6, 8, 10, 12, 14, 16], [0, 3, 6, 9, 12, 15, 18, 21, 24], [0, 4, 8, 12, 16, 20, 24, 28, 32]]) |
dc279eac1a98741b39722cdcb3f66909bf6680be | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/nckemm001/question2.py | 993 | 4.03125 | 4 | # Emmalene Naicker
# NCKEMM001
# Question 2
import math
# Get vectors from the user and store it in a list
X = input("Enter vector A:\n").split(" ")
Y = input("Enter vector B:\n").split(" ")
# Convert string elements in arrays to integers
for i in range (len(X)):
X[i] = eval(X[i])
Y[i] = eval(Y[i])
add_vectors = [] # Add the vectors
for i in range(len(X)):
add_vectors.append(X[i] + Y[i])
dot_product = 0
for i in range(len(add_vectors)):\
dot_product += (X[i] * Y[i])
normal_X = 0
normal_Y = 0
for x in X:
normal_X += x**2 # Sum of squares
normal_X = math.sqrt(normal_X)# Square root of sum of squares
for y in Y:
normal_Y += y**2 # Sum of squares
normal_Y = math.sqrt(normal_Y) # Square root of sum of squares
# Print the output
print("A+B =", add_vectors)
print("A.B =", dot_product)
print("|A| =", "{:.2f}".format(normal_X, 3))
print("|B| =", "{:.2f}".format(normal_Y, 3))
|
ea7ffc44c38aaf1ee579c68f25e940ba94fee4f8 | lucasdiogomartins/curso-em-video | /python/ex018_trigonometry.py | 292 | 3.859375 | 4 | import math
ag = float(input('Digite o angulo em graus: '))
ar = math.radians(ag)
sen = math.sin(ar)
cos = math.cos(ar)
tan = math.tan(ar)
print(' Seno de {}° = {:.2f}\n'.format(ag, sen),
'Cosseno de {}° = {:.2f}\n'.format(ag, cos),
'Tangente de {}° = {:.2f}'.format(ag, tan))
|
52def5d929a5ee156839312cbee002614876443f | ushanirtt55/python | /Python Basics/Python_proj/yield/yyyyeee.py | 178 | 3.703125 | 4 | def yrange(n):
i = 0
while i < n:
print "Before yield", i
yield i
print "After yield", i
i += 1
for i in yrange(8):
print i
|
a186080b2d0259130f6e99daa025b2ab95a75673 | sankleta/glowing-funicular | /CodeJam for Women 2021/organization.py | 1,661 | 3.578125 | 4 | from collections import deque, defaultdict
class Graph:
def __init__(self, managers):
self._graph = defaultdict(set)
self.managers = managers
def add(self, node1, node2):
self._graph[node1].add(node2)
self._graph[node2].add(node1)
def find_path(self, a, b):
if b in self._graph[a]:
return 0
used = set()
queue = deque([(a, 0)])
while queue:
current_node, depth = queue.popleft()
if current_node == b:
return depth
used.add(current_node)
adjacent_nodes = self._graph[current_node]
for i in adjacent_nodes:
if i not in used:
if i == b:
return depth + 1
if i <= managers:
queue.append((i, depth + 1))
return None
test_cases_no = int(input())
for test in range(test_cases_no):
z = raw_input()
managers, nonmanagers, pairs = map(lambda x: int(x), z.split())
graph = Graph(managers)
ans = []
for i in range(managers + nonmanagers):
line = raw_input()
for s in range(len(line)):
if line[s] == 'Y':
if i != s:
graph.add(i + 1, s + 1)
for p in range(pairs):
a, b = map(int, raw_input().split())
out = graph.find_path(a, b)
if out is None:
ans.append(-1)
elif out == 0:
ans.append(0)
else:
k, l = divmod(out + 1, 3)
ans.append(2 * k + l - 1)
print("Case #{}: {}".format(test + 1, ' '.join(map(str, ans))))
|
731baacf35b3cc617649a75be14d1b26d63d81dc | HrithikArya/MyInitialProjects | /ToFindGivenGreater.py | 396 | 3.640625 | 4 | great = None
small = None
while True :
i = input('Enter response: ')
if i == 'done' :
break
if great == None :
great = int(i)
elif int(i) > great :
great = int(i)
elif int(i) < great :
if small == None :
small = int(i)
elif int(i) < small :
small = int(i)
print('great', great)
print('small', small)
|
aa9c8377a847776503eb1b9a9309cfebc82949d7 | Rustofaer/GeekUniversity-Python | /lesson-1/task2.py | 637 | 4.375 | 4 | # 2. Пользователь вводит время в секундах. Переведите время в часы, минуты и секунды и выведите в формате чч:мм:сс.
# Используйте форматирование строк.
time = input("Введите время в секундах: ")
if not time.isdecimal():
print("Неверный ввод!")
else:
time = int(time)
seconds = time % 60
time //= 60
minutes = time % 60
hours = time // 60
print(str.format("Ваше форматированное время {:02d}:{:02d}:{:02d}", hours, minutes, seconds))
|
16efec42c4163ba036aa982edb0cd7a1b108edaf | MarkEhler/dsc-1-05-06-selecting-data-lab-online-ds-pt-112618 | /sql_selects.py | 926 | 3.765625 | 4 | def select_all_columns_and_rows():
return '''SELECT * FROM planets;'''
def select_name_and_color_of_all_planets():
return'''SELECT (name, color) FROM planets;'''
def select_all_planets_with_mass_greater_than_one():
return '''SELECT (mass) FROM planets WHERE mass > 1;'''
def select_name_and_mass_of_planets_with_mass_less_than_equal_to_one():
return '''SELECT (name, mass) FROM planets WHERE mass <= 1;'''
def select_name_and_color_of_planets_with_more_than_10_moons():
return cursor.execute('''SELECT (name, color) FROM planets WHERE num_of_moons > 10;''').fetchall()
def select_all_planets_with_moons_and_mass_less_than_one():
return cursor.execute('''SELECT (mass, num_of_moons) FROM planets WHERE mass < 1 and num_of_moons > 0;''').fetchall()
def select_name_and_color_of_all_blue_planets():
return cursor.execute('''SELECT (name, color) FROM planets WHERE color = 'blue';''').fetchall()
|
7073c250b8e30e89989336847092bcd9f4ed6d27 | eszkatya/test | /ex07b_fourthPower.py | 671 | 3.90625 | 4 | # Write a Python function, fourthPower, that takes in one number and returns that value raised to the fourth power.
from .ex07a_square import square
# You should use the square procedure that you defined in an earlier exercise by importing the file's specific function
# and reusing it in your function via calling it
def fourthPower(y, x):
z = square(y)
while x > 2:
z = z * y
x -= 1
return z
print(fourthPower(2, 3))
# A feladatban az importálásnak kellett volna utána nézni egy másik fileból.
# A funkciók egymásba ágyazásával mit értél el, mi történik lépésenként a függvény hívásakor?
|
e9aacaa3f9c7d9a19b52f258e27a21f1d266b76d | yoniLavi/Open-Knesset | /video/utils/parse_dict.py | 1,336 | 3.546875 | 4 | # encoding: utf-8
def validate_dict(h,*args):
for arg in args:
if type(h).__name__=='dict' and type(arg).__name__=='list':
for key in arg:
if key not in h or h[key] is None:
return False
elif type(h).__name__=='dict' and type(arg).__name__=='dict':
for k in arg:
if k not in h or h[k] is None:
return False
v=arg[k]
val=h[k]
ans=validate_dict(val,v)
if ans==False:
return False
elif type(arg).__name__=='str':
if arg!=h:
return False
else:
return False
return True
def parse_dict(h,p,validate=None,default=None):
if type(h).__name__!='dict':
return default
if validate is not None and validate_dict(h,validate)==False:
return default
if type(p).__name__=='str':
if p in h and h[p] is not None:
return h[p]
else:
return default
elif type(p).__name__=='dict':
for k in p:
if k not in h or h[k] is None:
return default
else:
val=h[k]
v=p[k]
return parse_dict(val,v,default=default)
return default
|
dfceb7b3a65b2fab25d5e29571c8de4e0ea64a03 | 610yilingliu/leetcode | /Python3/285.inorder-successor-in-bst.py | 1,213 | 3.703125 | 4 | #
# @lc app=leetcode id=285 lang=python3
#
# [285] Inorder Successor in BST
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# class Solution:
# def inorderSuccessor(self, root: 'TreeNode', p: 'TreeNode'):
# if not root or not p:
# return None
# self.ls = []
# self.finder(root)
# if p == self.ls[-1]:
# return None
# for i in range(len(self.ls)):
# if self.ls[i] == p:
# return self.ls[i + 1]
# def finder(self, root):
# if not root:
# return
# self.finder(root.left)
# self.ls.append(root)
# self.finder(root.right)
# Sol2
class Solution(object):
def inorderSuccessor(self, root, p):
"""
:type root: TreeNode
:type p: TreeNode
:rtype: TreeNode
"""
ans = None
while root:
if p.val < root.val:
ans = root
root = root.left
else:
root = root.right
return ans
# @lc code=end
|
94f05441f54327bb3470efbe97f8dbb9aa1bfde0 | kishoreramesh84/python-75-hackathon | /str1.py | 287 | 4.46875 | 4 | print("To calculate the length of a string")
string1="Ramesh"
string2="kishore"
print("string1:",string1)
print("string2:",string2)
print("Length of string1:",len(string1))#In Python, it has default 'len' function to calculate length of a string
print("Length of string2:",len(string2))
|
90f31c4ca0aba01736ff4e62ec41896456bf312b | hmp36/python_aug_2017 | /instruction/hospital.py | 1,040 | 3.53125 | 4 | import random
class Patient(object):
def __init__(self, name, allergies):
self.id = random.randint(1, 10000)
self.name = name
self.allergies = allergies
self.bed_number = None
class Hospital(object):
def __init__(self, name):
self.patients = []
self.name = name
self.capacity = random.randint(10, 30)
def admit(self, patient):
if len(self.patients) == self.capacity:
print 'We are at full capacity'
return self
else:
self.patients.append(patient)
patient.bed_number = len(self.patients) - 1
class Something(Hospital):
def __init__(self):
super(Something, self).__init__('something')
# pass
class Works(Something):
def __init__(self):
super(Works, self).__init__()
# pass
x = Works()
print x.capacity
# a = Patient('Bob', [])
# b = Patient('Cody', [])
# c = Hospital('Codys Hospital')
# c.admit(a)
# c.admit(b)
# print a.bed_number
# print b.bed_number
|
da35b04f3b915e017c95645ed7f8935923eebf19 | Cryptoriser7/CursoPython-Mundo-2 | /ex036.py | 1,084 | 4.375 | 4 | '''Escreva um programa para aprovar o emprestimo bancario para a compra de uma casa.
#O programa vai perguntar o Valor da casa, o Salário do comprador e em quantos anos ele vai pagar.
#Calcule o valor da prestação mensal sabendo que ela nao pode exceder 30% do salário ou entao o emprestimo será negado.
'''
ValorCasa = int(input('Valor do Imóvel: '))
Salario = int(input('Salário: '))
Anos = int(input('Duração Emprestio: '))
prestacao = ValorCasa / (Anos * 12)
print('O valor da sua prestação será: {:.2f} €'.format(prestacao))
print('.' * 20)
if (prestacao / Salario) * 100 <= 30.0:
print('A prestação para o credito pedido representa {:.2f} % do seu salário'.format((prestacao / Salario) * 100))
print('Como a percentagem é inferior a 30 %, o seu crédito será \033[36mAPROVADO\033[0m!')
elif (prestacao / Salario) * 100 >= 30.0:
print('A prestação para o credito pedido representa {:.2f} % do seu salário'.format((prestacao / Salario) * 100))
print('Como a percentagem é superior a 30 %, o seu credito será \033[33mREPROVADO\033[0m')
|
dff0925f9e2df85229f7ad64a0d507fd577f10ed | fayinac/python-class | /1-3 unit converter.py | 445 | 4.09375 | 4 | inches = input('Enter distance in inches:')
inches = int(inches)
cm = inches * 2.54
print(inches, 'inches is equal to', cm, 'cm.')
pounds = input('Enter weight in pounds:')
pounds = int(pounds)
kg = pounds / 2.2
print(pounds, 'pounds is equal to', kg, 'kg.')
fahrenheit = input('Enter temperature in fahrenheit:')
fahrenheit = int(fahrenheit)
celcius = fahrenheit - 32 / (9/5)
print(fahrenheit, 'fahrenheit is equal to', celcius, 'celcius.')
|
a9e88a8240b6687d13fbdecc8dd4bd3bf9c59b7e | EmilioHermosa/POO_EmilioHermosa | /Assigments/Practice in Python/examples/examples.py | 446 | 4.09375 | 4 | name = "Wladymir"
age = 22
result = age ** 2
names = ["Stiven", "Dennis", "Adrian", "Jerico"]
names.append("Diego")
names.extend(["Armando", "Stalin"])
names.insert(0, "Wladymir")
return_name = names.pop
print(names)
print(return_name)
ages = [18, 60 ,23, 22, 26]
names.extend(ages)
print(names)
names_with_ages = zip(names, ages)
for student in names_with_ages:
print(student)
my_tuple = ("Stiven", "Dennis")
my_tuple[0] = "Emilio"
|
90004e9c58879762a09d36bafe3612de8a806fda | Alekseevnaa11/practicum_1 | /51.py | 1,326 | 3.90625 | 4 | """
Имя проекта: practicum-1
Номер версии: 1.0
Имя файла: 51.py
Автор: 2020 © Д.П. Юткина, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 04/12/2020
Дата последней модификации: 04/12/2020
Описание: Решение задачи 51 практикума № 1
#версия Python: 3.8
"""
"""
Заданы M строк символов, которые вводятся с клавиатуры. Найти количество символов
в самой длинной строке. Выровнять строки по самой длинной строке, поставив перед
каждой строкой соответствующее количество звёздочек.
"""
M = int(input("Введите количество строк: "))
x = []
for i in range(0, M):
print("Введите строку:", end=' ')
x.append(input())
maxx= 0
for y in x:
d = len(y)
if d > maxx:
maxx = d
print("Максимальная длина строки:", maxx)
for y in x:
d = len(y)
if d < maxx:
for i in range(0, maxx - d):
y = '*' + y
print(y)
|
b407a84fe466f76f8b91e2021ca2b74727a24f79 | DanielDruetta/frro-soporte-2019-25 | /practico_01/ejercicio-09.py | 434 | 3.953125 | 4 | # Implementar la función es_palindromo(), que devuelva un booleano en base a
# si palabra se lee igual de corrido como al revés.
# Ejemplos: arenera, radar, ojo, oso, salas.
# Resolver sin utilizar loops (for/while), sino con slicing.
def es_palindromo(palabra):
if palabra[:] == palabra[::-1]:
return True
else:
return False
assert es_palindromo('hola') == False
assert es_palindromo('neuquen') == True
|
26fd9409f5a314e337c83e48eecd0c8533ddbf7e | durgadevi68/guvi | /reverse.py | 81 | 3.59375 | 4 | a=int(input())
sum=0
while(a!=0):
b=a%10
sum=sum*10+b
a=a//10
print(sum)
|
4ed399a3f63c8d8d81b0caf63a7d51674c9d58b8 | spezifisch/leetcode-problems | /two-sum-ii-input-array-is-sorted/v1.py | 918 | 3.53125 | 4 | from bisect import bisect_left
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
if not numbers:
return []
len_numbers = len(numbers)
for i, num in enumerate(numbers):
wanted = target - num
if wanted > i:
idx = bisect_left(numbers, wanted, i + 1, len_numbers)
if idx != len_numbers and numbers[idx] == wanted:
return [1 + i, 1 + idx]
elif wanted < i:
idx = bisect_left(numbers, wanted, 0, i)
if idx != len_numbers and numbers[idx] == wanted:
return [1 + idx, 1 + i]
return []
# Runtime: 44 ms, faster than 50.43% of Python3 online submissions for Two Sum II - Input array is sorted.
# Memory Usage: 13.4 MB, less than 5.14% of Python3 online submissions for Two Sum II - Input array is sorted.
|
48f2e7f79f2e05d3748a243d316c9adc176593f2 | HomoCodens/adventofcode_2020_py | /aochc/aoc2020/day24.py | 3,279 | 3.71875 | 4 | def prepare(input):
return input.splitlines()
def init_floor(paths):
states = {}
for p in paths:
x, y, z = 0, 0, 0
# No really, python has no proper looping...
i = 0
while i < len(p):
instruction = p[i]
if instruction in ['n', 's']:
# Also, this:
instruction = p[i:(i+2)]
i += 1
# AND THIS! Waaaaagh!
if instruction == 'nw':
z -= 1
y += 1
elif instruction == 'ne':
z -= 1
x += 1
elif instruction == 'e':
x += 1
y -= 1
elif instruction == 'se':
z += 1
y -= 1
elif instruction == 'sw':
z += 1
x -= 1
else:
x -= 1
y += 1
i += 1
pos = (x, y, z)
if pos in states:
states[pos] = not states[pos]
else:
states[pos] = True # ya know, False feels "blacker" though...
return states
def part_a(paths):
floor = init_floor(paths)
return sum(floor.values())
def step_floor(floor): # get it? floors are for stepping on *laffs*
# nw, ne, e, se, sw, w
directions = [
(0, 1, -1),
(1, 0, -1),
(1, -1, 0),
(0, -1, 1),
(-1, 0, 1),
(-1, 1, 0)
]
tiles_to_look_at = []
for tile in floor.keys():
x, y, z = tile
tiles_to_look_at.append(tile)
for d in directions:
dx, dy, dz = d
neighbour = (x + dx, y + dy, z + dz)
tiles_to_look_at.append(neighbour)
neighbours = {}
for tile in set(tiles_to_look_at):
x, y, z = tile
n_black = 0
for d in directions:
dx, dy, dz = d
neighbour = (x + dx, y + dy, z + dz)
if neighbour in floor:
n_black += floor[neighbour]
neighbours[tile] = n_black
new_floor = {}
for tile in neighbours.keys():
# tile is white
if (not tile in floor) or (not floor[tile]):
new_floor[tile] = (neighbours[tile] == 2)
elif tile in floor and floor[tile]:
new_floor[tile] = 0 < neighbours[tile] <= 2
return new_floor
def part_b(paths):
floor = init_floor(paths)
for i in range(100):
print(i, flush = True)
floor = step_floor(floor)
return sum(floor.values())
if __name__ == '__main__':
example1 = prepare('''sesenwnenenewseeswwswswwnenewsewsw
neeenesenwnwwswnenewnwwsewnenwseswesw
seswneswswsenwwnwse
nwnwneseeswswnenewneswwnewseswneseene
swweswneswnenwsewnwneneseenw
eesenwseswswnenwswnwnwsewwnwsene
sewnenenenesenwsewnenwwwse
wenwwweseeeweswwwnwwe
wsweesenenewnwwnwsenewsenwwsesesenwne
neeswseenwwswnwswswnw
nenwswwsewswnenenewsenwsenwnesesenew
enewnwewneswsewnwswenweswnenwsenwsw
sweneswneswneneenwnewenewwneswswnese
swwesenesewenwneswnwwneseswwne
enesenwswwswneneswsenwnewswseenwsese
wnwnesenesenenwwnenwsewesewsesesew
nenewswnwewswnenesenwnesewesw
eneswnwswnwsenenwnwnwwseeswneewsenese
neswnwewnwnwseenwseesewsenwsweewe
wseweeenwnesenwwwswnew
''')
print(part_b(example1)) |
d50b7f42151d7a254db1924414fd6d0b7482fdf1 | Souzanderson/jogodavelhapython | /app.py | 2,573 | 3.625 | 4 |
class JogoDaVelha():
def __init__(self):
self.tab = {str(i):" " for i in range(9)}
self.ids = ["X","O"]
self.isid = 0
def tabuleiro(self):
j=0
print("")
for i in range(3):
print(" %s | %s | %s " % (self.tab[str(j+0)],self.tab[str(j+1)],self.tab[str(j+2)]))
if i<2:
print("___________")
j+=3
print("")
def jogada(self,pos,id):
if self.tab[str(pos)]!=" ":
print("Posição já ocupada!")
return False
else:
self.tab[str(pos)]=id
return True
def checkGame(self):
if(self.tab['0']==self.tab['1']==self.tab['2']!=" "):
print("Jogador vencedor: %s"%self.tab['0'])
return True
elif(self.tab['0']==self.tab['3']==self.tab['6']!=" "):
print("Jogador vencedor: %s"%self.tab['0'])
return True
elif(self.tab['0']==self.tab['4']==self.tab['8']!=" "):
print("Jogador vencedor: %s"%self.tab['0'])
return True
elif(self.tab['1']==self.tab['4']==self.tab['7']!=" "):
print("Jogador vencedor: %s"%self.tab['1'])
return True
elif(self.tab['2']==self.tab['5']==self.tab['8']!=" "):
print("Jogador vencedor: %s"%self.tab['2'])
return True
elif(self.tab['2']==self.tab['4']==self.tab['6']!=" "):
print("Jogador vencedor: %s"%self.tab['2'])
return True
elif(self.tab['3']==self.tab['4']==self.tab['5']!=" "):
print("Jogador vencedor: %s"%self.tab['3'])
return True
elif(self.tab['6']==self.tab['7']==self.tab['8']!=" "):
print("Jogador vencedor: %s"%self.tab['6'])
return True
elif(" " not in self.tab.values()):
print("Jogo empatado!")
return True
return False
def initGame(self):
self.tabuleiro()
while(1):
j = input("Jogada:")
try:
res = self.jogada(int(j),self.ids[self.isid])
if res:
self.isid+=1
if(self.isid>1):
self.isid=0
self.tabuleiro()
if self.checkGame():
return
except Exception as e:
print("Jogada inválida! Jogada deve ser uma posição entre 0 e 8.")
self.tabuleiro()
if __name__ == "__main__":
jg = JogoDaVelha()
jg.initGame()
|
d8b613108d9f62e6bc91d69b2af3b8a30967dd54 | AKXAT/binarytree | /BinarySearchTree.py | 2,981 | 3.90625 | 4 | class BinarySearchTreeNode:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def add_child(self,data):
if data == self.data:
return
if data<self.data:
#add data in the left sub tree
if self.left:
self.left.add_child(data)
else:
self.left = BinarySearchTreeNode(data)
else:
if self.right:
self.right.add_child(data)
else:
self.right = BinarySearchTreeNode(data)
#add data in the right sub tree
def in_order_traversal(self):
elements = []
if self.left:
elements += self.left.in_order_traversal()
#visiting the left tree
#now add the root or the base node to the element list
elements.append(self.data)
#now we need to visit the right sub tree
if self.right:
elements += self.right.in_order_traversal()
return elements
def search(self,value):
if self.data == value:
return True
if value < self.data:
#then the value might be in the left subtree
if self.left:#to check if we have a left subtree
return self.left.search(value)
else:
return False
if value > self.data:
#then the value might be in the right subtree
if self.right:#to check if we have a right subtree
return self.right.search(value)
else:
return False
def find_max(self):
if self.right:
return self.right.find_max()
return self.data
def find_min(self):
if self.left:
return self.left.find_max()
return self.data
def delete(self,value):
if value < self.data:
if self.left:
self.left = self.left.delete(value)
elif value > self.data:
if self.right:
self.right = self.right.delete(value)
else:
if self.left is None and self.right is None :
return None
elif self.left is None:
return self.right
elif self.right is None:
return self.left
min_value = self.right.find_min()
self.data = min_value
self.right = self.right.delete(min_value)
return self
def build_tree(element):
root = BinarySearchTreeNode(element[0])
for i in range(1,len(element)):
root.add_child(element[i])
return root
if __name__ == '__main__':
newtree = build_tree([3,4,6,7,32,5,6,7,54,34,56])
print(newtree.in_order_traversal())
#print(newtree.search(20))
#print(f'{newtree.find_max()} is the maximum')
#print(f'{newtree.find_min()} is the minimum')
newtree.delete(4)
print(newtree.in_order_traversal())
|
9bcd67d8a01e2e7638880dcac0eff17509c13f96 | ajlopez/RedPython | /samples/simple/primes.py | 271 | 4.125 | 4 |
def isprime(n):
k = 3
while k * k <= n:
if n % k == 0:
return 0
k = k + 2
printf("%d is prime\n", n)
def main():
n = 3
while n < 100:
isprime(n)
n = n + 2
|
7983c9cdd880295d585da15f03e07c02713ca29f | takadhi1030/hello-fuction | /app.py | 505 | 3.953125 | 4 | def hello():
print("Hello World")
# 引数もなくて返り値もない
hello()
def say_hello(name):
print(f"Hi {name} ")
say_hello("Bob")
# 引数はあって、返り値はない
def double(number):
return 2 * number
result_1 = double(3)
print(result_1)
# 引数も返り値もある
# 1分課題
def str_combine(str1, str2):
return str1 + str2
result = str_combine("Kazuma", "Takahashi")
print(result)
pass
str_combine("Kazuma", "Takahashi") # "Kazuma Tkahashi"を返す
|
c74644bef39b0779b8793d1735a0b17817c77326 | notesonartificialintelligence/07-01-20 | /chapter_5/cars.py | 310 | 4.28125 | 4 | #Gabriel Abraham
#notesonartificialintelligence
#Python Crash Course - Chapter 5
#This program will loop through the list checking for 'bmw',
#which, when found will be printed in upper case.
cars = ["audi","bmw","subaru","toyota"]
for car in cars:
if car == "bwm":
print(car.upper())
else:
print(car.title()) |
661dacc6731f8fce013d632d8ac4656d7f659c7d | mauricioZelaya/QETraining_BDT_python | /JulietaEscalera/Class scripts/Class practice/index.py | 231 | 3.65625 | 4 | from Employee import *
from Persona import *
nombre= input("Escribe el nombre: ")
apellido= input("Escribe el apellido: ")
x= Person(nombre, apellido)
y= Employee("Homer", "Simson", "1007")
print(x.Name())
print(y.getEmployee()) |
722348a3a180c7cba56f606ecddfeff669ff5837 | guoweifeng216/python | /python_basic/chapter16/test_my_math.py | 731 | 3.625 | 4 | #!/usr/bin/env python3
# coding=utf-8
"""
@athor:weifeng.guo
@data:2019/6/25 9:41
@filename:test_my_math
"""
import unittest
from chapter16 import my_math
class test_integer(unittest.TestCase):
def test_integers(self):
for x in range(-10, 10):
for y in range(-10, 10):
p = my_math.product(x, y)
self.assertEqual(p, x * y, 'Integer multiplication failed')
def test_floats(self):
for x in range(-10, 10):
for y in range(-10, 10):
x = x /10
y = y / 10
p = my_math.product(x, y)
self.assertEqual(p, x * y, 'Floats multiplication failed')
if __name__ == '__main__':
unittest.main() |
f5e22fa3278dbfcbc46f4461584b04bd76e6bec1 | JaahnaviGoli/pycbit-hackathon | /2_area_15.py | 457 | 3.640625 | 4 |
#area if c is height
area_c=0
#area if b is height
area_b=0
#area if a is height
area_a=0
def fu(a=6,b=8,c=10):
global area_c,area_b,area_a
area_a=(b*1.15)*(c*1.15)
area_b=(c*1.15)*(a*1.15)
area_c=(b*1.15)*(a*1.15)
try:
fu(float(input("enter a")),float(input("enter b")),float(input("enter c")))
print("if a is height ",area_c,"\nif b is height ",area_b,"\nif c is height",area_a)
except:
print("enter real numbers")
|
77512b48e492e493b47e61c4274688572a0e0b21 | miracle-zwc/miracle-zwc.github | /rasls.py | 3,237 | 4.25 | 4 | """
程序目标:RPSLS游戏
程序作者:张文聪
"""
import random
def name_to_number(name): #将游戏对象对应到不同的整数
if name=="石头" :
name=0
if name=="史波克" :
name=1
if name=="纸" :
name=2
if name=="蜥蜴" :
name=3
if name=="剪刀" :
name=4
return name
def number_to_name(number): #将整数 (0, 1, 2, 3, or 4)对应到游戏的不同对象
if number==0 :
number="石头"
if number==1 :
number="史波克"
if number==2 :
number="纸"
if number==3 :
number="蜥蜴"
if number==4 :
number="剪刀"
return number
def rpsls(player_choice):
computer=random.randint(0,5)
player_choice=choice_name
player=name_to_number(player_choice)
while player == name_to_number("石头"):
print("您的选择为" + number_to_name(0))
print("计算机的选择为"+number_to_name(computer))
if computer == 3 or computer == 4:
print("您赢了!")
if player==computer:
print("您和计算机出的一样")
if computer==1 or computer==2:
print("机器赢了")
break
while player==name_to_number("史波克"):
print("您的选择为" + number_to_name(1))
print("计算机的选择为" + number_to_name(computer))
if computer==4 or computer==0:
print("您赢了!")
if player==computer:
print("您和计算机出的一样")
if computer==2 or computer== 3:
print("机器赢了")
break
while player==name_to_number("纸") :
print("您的选择为" + number_to_name(2))
print("计算机的选择为" + number_to_name(computer))
if computer==1 or computer==0 :
print("您赢了!")
if player==computer:
print("您和计算机出的一样")
if computer==3 or computer==4 :
print("机器赢了")
break
while player==name_to_number("蜥蜴") :
print("您的选择为" + number_to_name(3))
print("计算机的选择为" + number_to_name(computer))
if computer==1 or computer==2 :
print("您赢了!")
if player==computer :
print("您和计算机出的一样")
if computer==0 or computer==4 :
print("计算机赢了")
break
while player==name_to_number('剪刀') :
print("您的选择为" + number_to_name(4))
print("计算机的选择为" + number_to_name(computer))
if computer==2 or computer==3 :
print("您赢了!")
if player==computer :
print("您和计算机出的一样")
if computer==0 or computer==1 :
print("计算机赢了")
break
return player
print("欢迎使用RPSLS游戏")
print("----------------")
print("请输入您的选择:")
choice_name=input()
if choice_name != "石头" and choice_name !="剪刀" and choice_name !="纸" and choice_name !="蜥蜴" and choice_name !="史波克":
print('Error: No Correct Name')
result=rpsls(choice_name)
|
4334d5e317c08262bff6b5defdeb84eddd82b1a7 | Gyagya00/algorithm | /3.string/4861_회문/행, 열 따로 1차원.py | 378 | 3.875 | 4 | matrix = [] # 가로방향으로 문자들을 가지고 와서 리스트에 저장
colmatrix = [] # 세로방향으로 문자들을 가지고 와서 리스트에 저장
for i in range(N):
matrix.append(input())
# print(matrix)
for i in range(N):
colstring = ''
for j in range(N):
colstring += matrix[j][i]
colmatrix.append(colstring)
# print(colmatrix) |
d70398b947b57cce8245404a75f02d5e954a8f95 | shanshay/Game-Answer-the-que | /victory.py | 1,251 | 3.640625 | 4 | while True:
answer = input('Хотите начать игру? ')
if answer == 'да':
count = 0;
bPushkin = input('Какой год рождения А.С. Пушкина?')
if bPushkin == '1799':
count = count+1
bMayak = input('Какой год рождения В.В. Маяковского?')
if bMayak == '1893':
count = count+1
bTyut = input('Какой год рождения Ф.И. Тютчева?')
if bTyut == '1803':
count = count+1
bBulg = input('Какой год рождения М.А. Булгакова?')
if bBulg == '1891':
count = count + 1
bDost = input('Какой год рождения Ф.М. Достоевского?')
if bDost == '1821':
count = count + 1
print('Количество верных ответов = ', count)
print('Количество неверных ответов = ', 5 - count)
print('Процент верных ответов = ', count * (100/5))
print('Процент неверных ответов = ', (5 - count) * (100/5))
if answer == 'нет':
print('Досвиданья')
break
|
fa0cf27c4852c5e5ca81e4aadf9333e123675941 | mgiridhar/code | /array/sort_array_swap.py | 861 | 4.25 | 4 | # https://www.geeksforgeeks.org/sort-array-swapping-special-element-allowed/
def swap(x, y):
return y, x
def sortBySwap(arr):
# moving space at the end
for i in range(0, len(arr)):
if arr[i] == 999:
arr[i], arr[len(arr) - 1] = arr[len(arr) - 1], arr[i]
break
i = 0
while i < len(arr) - 1:
if arr[i] == i + 1:
i += 1
continue
j = arr[i] - 1
#print arr
# two swaps with the space
arr[j], arr[len(arr) - 1] = swap(arr[j], arr[len(arr) - 1])
#print arr
arr[i], arr[j] = swap(arr[i], arr[j])
#print arr
arr[i], arr[len(arr) - 1] = swap(arr[i], arr[len(arr) - 1])
#print arr
#break
if __name__ == "__main__":
arr = map(int, raw_input().strip().split(','))
sortBySwap(arr)
print arr
|
94ceb9287049cea407d178b76d79a13954e297ed | prankuragarwal/python-beginner | /gcd.py | 279 | 3.734375 | 4 | import sys
a = int(input("Enter a number : "))
b = int(input("Enter another number : "))
if a<b:
c=a
a=b
b=c
gcd = 0
x=b
while x>=1:
if a%x==0 and b%x==0:
gcd = x
break
x-=1
print("The G.C.D of %d and %d is %d" % (a,b,gcd))
|
a73e5c8895fcb4538132296e4ba8d70cf32fb8ee | japnitahuja/Programming-Practice | /Python A-level/SH1/Worksheet 1/16.VendingMachine.py | 1,047 | 3.90625 | 4 | #Input
ten = int(input("Number of 10-cent coins inserted "))
twenty = int(input("Number of 20-cent coins inserted "))
fifty = int(input("Number of 50-cent coins inserted "))
one = int(input("Number of 1-dollar coins inserted "))
choice = float(input("Enter the price of the drink - 0.8 or 1.2 "))
total = .1 * ten + .2 * twenty + .5 * fifty + 1 * one
ten = 0
twenty = 0
fifty = 0
one = 0
print ("Amount inserted: " + str(total)) #Amount Inserted
# Deducting the drink price
if (choice == 1.2):
total -= 1.2
elif (choice == .8):
total -= .8
else:
print ("enter a valid input")
print ("The machine returns: " + str(total))
# Returning the change
total *= 10
while total >= 10:
total -= 10
one += 1
while total >= 5:
total -= 5
fifty += 1
while total >= 2:
total -= 2
twenty += 1
while total >= 1:
total -= 1
ten += 1
print (str(one) + " x 1 dollar coins")
print (str(fifty) + " x .50 dollar coins")
print (str(twenty) + " x .20 dollar coins")
print (str(ten) + " x .10 dollar coins")
|
6de0884e64a166f57ad1893958f8f953a5bfcd68 | FINCoding/Train | /tasks/task4_packman_in_array.py | 678 | 3.765625 | 4 | class Point:
def __init__(self, row, col):
self.row = row
self.col = col
def GetPacManResult(N, M, point):
if point.row < 0 or point.row > N or point.col < 0 or point.col > M:
raise Exception("wrong input data")
start = 0
end = M - 1
direction = 1
pointsCount = 1
for i in range(1,N+1):
for j in range(start, end + direction, direction):
if (i == point.row and j == point.col - 1):
return pointsCount
pointsCount += 1
direction *= -1
start, end = end, start
return pointsCount
if __name__ == '__main__':
print(GetPacManResult(3,3,Point(1,3)))
|
393d3e21d7d0da1d101bd08364cf2a43182ee75b | mervozturk/Bilimsel-hesaplamlar | /denklem çözümü.py | 443 | 3.546875 | 4 | def matris(m):
n=len(m)-1
x=len(m[0])
k=0
a=0
for i in range(n,-1,-1):
k=(-m[i][a]/m[a][a])
for j in range(0,x):
m[i][j]=k*m[a][j]+m[i][j]
a+=1
for i in range(n+1):
for j in range(x-1,-1,-1):
m[i][j]=m[i][j]/m[i][i]
print("cözüm kümesi:")
for i in range(n+1):
print(m[i][x-1],end=" ")
denk=[[1,2,1],[3,4,-2]]
matris(denk) |
573c1f86555fca5e0ff4ded6030add416929cbf1 | yoyo906012/Python-Data-Structure | /array1.py | 592 | 3.9375 | 4 | #input UTF-8
#-*- coding: utf-8 -*-
#行列式計算機
#決定陣列的維度
N = 2
arr = [[None]*N for row in range(N)]
print("|a1 b1|")
print("|a2 b2|")
#input 行列式
arr[0][0] = input("請輸入a1: ")
arr[0][1] = input("請輸入b1: ")
arr[1][0] = input("請輸入a2: ")
arr[1][1] = input("請輸入b2: ")
#求行列式的值
result = ((int(arr[0][0])*int(arr[1][1]))-(int(arr[0][1]*int(arr[1][0]))))
print('|%d %d|' %(int(arr[0][0]),int(arr[0][1])))
print('|%d %d|' %(int(arr[1][0]),int(arr[1][1])))
print("行列式的值= %d" %result)
|
54f4af9cc6a97f2de8ebb0e67b8df7c9af7f4858 | CodingDojoDallas/python_jan_2017 | /Troy_Maikowski/tm_bubblesort.py | 583 | 4.09375 | 4 | from datetime import datetime
import random
a = []
for x in range(3000):
a.append(round(random.random()*10000))
def bubble_sort(arr):
start_time = datetime.now()
print "Start Time:", start_time
length = len(arr) - 1
good = False
while not good:
good = True
for x in range(length):
if arr[x] > arr[x+1]:
good = False
arr[x], arr[x+1] = arr[x+1], arr[x]
end_time = datetime.now()
print "End Time:", end_time
print "Running Time:", end_time - start_time
return a
bubble_sort(a) |
a44954bb0b6840d4e4b2fb189cbe11933d1c500d | e911/Eulers-Project-Solution | /euler-21.py | 991 | 3.84375 | 4 | import math
import time
def sum_of_divisors(num):
sum_t = 1
# a step to ignore iteration of even integer for odd numbers
step = 1 if num % 2 == 0 else 2
for i in range(2, int(math.sqrt(num)) + 1, step):
if (num % i == 0):
sum_t += i
sum_t += num / i
return sum_t
# brute method
# return sum([fact for fact in range(1, num) if num % fact == 0])
def amicable(n):
a = time.time()
amicables = set()
for num in range(1, n + 1):
if num in amicables:
continue
sum_fact = sum_of_divisors(num)
sum_fact2 = sum_of_divisors(sum_fact)
if num == sum_fact2 and num != sum_fact:
amicables.add(num)
amicables.add(sum_fact2)
return (sum(amicables), time.time() - a)
if __name__ == "__main__":
a = int(input("Enter a number up to which the sum of amicable numbers are needed"))
sum_total, time_elapsed = amicable(a)
print(sum_total, time_elapsed)
|
05302d75464c3ac253d68b4bac4eda35505bd2e4 | samshuster/2048_Explore | /solver_2048/src/manual_driver.py | 287 | 3.53125 | 4 | '''
Created on Mar 14, 2014
@author: samshuster
'''
from board import Board
b = Board()
print b
move = raw_input()
while(True):
try:
b.make_move(move,non_random=True)
except KeyError:
pass
else:
print b.score
print b
move = raw_input()
|
d36a374201e9e1c7a64d63df76a404e116c33ac0 | edgardozenteno/Prueba_diagnostico | /Solo_pares_Primeros_n_pares.py | 618 | 3.8125 | 4 |
# generar los N numeros primeros numeros pares a partir del 0
def contar_pares(n = 100):
pares = []
contador = 0
numero = 0
while contador < n:
if numero % 2 == 0:
pares.append(numero)
contador += 1
numero += 1
return pares
# solicita el numero de pares que necesita mediante entrada en caso de cumplirese mostrara la cantidad
# en este caso pares positivos,
n = int(input('esciba el numero: '))
if n >= 0:
pares = contar_pares(n)
print(pares)
print('Cantidad de pares:', len(pares))
else:
print('escriba un numero')
|
f11e3dd5fc4918e3cfefcfffeaa5a2cd7dac42ed | Raghav714/compiler-programs | /ll1table.py | 3,701 | 3.515625 | 4 | from collections import OrderedDict
def reverse_dict(dictx):
reverse_dict = OrderedDict()
key_list = []
for key in dictx:
key_list.append(key)
key_list.reverse()
for key in key_list:
reverse_dict[key] =dictx[key]
return reverse_dict
def first(grammar,terminal):
first_dict = OrderedDict()
grammar_first = reverse_dict(grammar)
for key in grammar_first:
each_prod = []
for element in grammar.copy()[key]:
if element[0:1] in terminal:
each_prod.append(element[0:1])
elif element in terminal:
each_prod.append(element)
if not each_prod:
each_prod = first_dict[element[0:1]]
first_dict[key] = each_prod
return first_dict
def check_prod(check_key,grammar):
dic = {}
for key in grammar:
pos_list = []
for element in grammar[key]:
pos = element.find(check_key)
if pos >= 0:
pos_list.append(pos)
if pos_list:
dic[key] = pos_list
return dic
def follow(grammar,terminal,first_dict):
follow_dict = OrderedDict()
for key in grammar:
each_prod = []
if key == "E":
each_prod.append("$")
elif check_prod(key,grammar):
pos = check_prod(key,grammar)
for found_key in pos:
for element in grammar[found_key]:
if key in element:
string = element
if (int(pos[found_key][0])+1)==len(string) and (found_key!=key):
each_prod.extend(follow_dict[found_key])
elif (int(pos[found_key][0])+1)!=len(string) and (key != found_key) :
each_prod.extend(first_dict[grammar[found_key][0][int(pos[found_key][0])+1]])
if "epsln" in each_prod:
each_prod.remove("epsln")
each_prod.extend(follow_dict[found_key])
elif key == found_key and (int(pos[found_key][0])+1)!=len(string):
each_prod.append(grammar[key][0][int(pos[found_key][0])+1])
follow_dict[key]=list(set(each_prod))
return follow_dict
def table(grammar,first_grammar,follow_grammar):
table = OrderedDict()
non_terminal = []
terminal = []
for nt in grammar:
non_terminal.append(nt)
terminal.extend(first_grammar[nt])
terminal.extend(follow_grammar[nt])
non_terminal = list(set(non_terminal))
terminal = list(set(terminal))
terminal.remove("epsln")
print "non terminal",non_terminal
print "terminal",terminal
for nt in non_terminal:
prod = []
for ter in terminal:
if ter in first_grammar[nt]:
if len(grammar[nt])==1:
prod.append(grammar[nt])
else:
for single_prod in grammar[nt]:
if single_prod[0] is ter:
prod.append([single_prod])
elif single_prod is ter:
prod.append([single_prod])
elif "epsln" in first_grammar[nt] and ter in follow_grammar[nt]:
prod.append(["epsln"])
else:
prod.append("error")
table[nt]=prod
return table
'''grammar = {}
le = input("length")
for i in range(le):
key = raw_input("key")
l = input("number of production")
lis = list()
for i in range(0,l):
lis.append(raw_input())
grammar.update({key:lis})'''
grammar = OrderedDict()
grammar["E"] = ["TA"]
grammar["A"] = ["+TA","epsln"]
grammar["T"] = ["FP"]
grammar["P"] = ["*FP","epsln"]
grammar["F"] = ["(F)","id"]
terminal = ["+","*","(",")","id","epsln"]
print "Original grammar"
for key, value in grammar.items():
print(key, value)
print "----------------------------------------------"
print "First"
first_grammar = first(grammar,terminal)
for key, value in first_grammar.items():
print(key, value)
print "----------------------------------------------"
print "Follow"
follow_grammar = follow(grammar,terminal,first_grammar)
for key, value in follow_grammar.items():
print(key, value)
print "----------------------------------------------"
ll1table=table(grammar,first_grammar,follow_grammar)
for key, value in ll1table.items():
print(key, value)
|
f675d451eff756fe1034cc9b0848e215e19bf246 | rupindermonga/euler62CubicPermutations | /euler62CubicPermutations.py | 1,816 | 4.03125 | 4 | '''
The cube, 41063625 (3453), can be permuted to produce two other cubes: 56623104 (3843) and 66430125 (4053). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.
Find the smallest cube for which exactly five permutations of its digits are cube.
'''
def CubicPermutations(x,y):
# in our case: x is cube and y is the number of permutations (5)
i = 2
break_point = 0
while True:
new_list = []
final_count = 0
while True:
if len(str(i**x)) == len(str((i-1)**x)) or i == break_point:
new_list.append(i**x)
elif len(new_list)<y:
break_point = i
break
else:
for j in range(len(new_list)):
count = 0
final_number = new_list[j]
final_list = []
str_to_check = str(final_number)
list_to_check = list(str_to_check)
list_to_check.sort()
for k in range(len(new_list)):
new_str = str(new_list[k])
new_list_to = list(new_str)
new_list_to.sort()
if list_to_check == new_list_to:
count += 1
final_list.append(new_list[k])
if count > y:
break
if count == y:
final_count = count
break
if final_count == y:
break
else:
i += 1
if final_count == y:
break
return final_list
final = CubicPermutations(3,5)
print(final) |
53ba242fc7b2d065aa3ed5226351d87124f976a7 | yuqli/tools | /check_euler.py | 2,692 | 3.515625 | 4 | #### 20190412
#### check in a given folder how many meshes are closed
import os
from argparse import ArgumentParser
from collections import deque
def parse_obj(path):
"""
a function to read and parse obj files
@ param path: absolute path to obj file
"""
with open(path) as fp:
lines = fp.readlines()
lines = [x for x in lines if x[0] != '#']
all_v = [x.split(' ')[1:] for x in lines if x[0] == 'v'] # all verices
all_f = [x.split(' ')[1:] for x in lines if x[0] == 'f'] # all verices
return all_v, all_f
def check_euler(all_f):
"""
check Euler‐Poincaré formula on a mesh's faces
If a manifold is closed, then V + F - E = 2
V : vertices
F : faces
E : edges
http://graphics.stanford.edu/courses/cs468-10-fall/LectureSlides/02_Basics.pdf
!!! Note: this algorithm is not every efficient as in counting edges it will
compare every edge and see if it's already in the edges list ...
BUT we can't have a set of set so this is the best I can come up at the moment
"""
F = len(all_f)
V = 0
all_edges = [] # store all edges ...
# iterate through all faces to count number of edges
for f in all_f:
items = deque(f) # a method to rotate the list, faster than slicing
items.rotate(-1)
curr_edges = list(zip(f, list(items)))
curr_edges = [set(x) for x in curr_edges] # make edges unordered
# print(curr_edges)
for e in curr_edges:
if e not in all_edges:
all_edges.append(e)
# print(all_edges)
num = [int(x) for x in f]
if max(num) > V:
V = max(num) # find the largest index of vertices, which is also number of vertices!
E = len(all_edges)
if V + F - E == 2:
return True
else:
return False
def main():
parser = ArgumentParser()
parser.add_argument("-f", "--folder",
help="the folder containing .obj files")
parser.add_argument("-q", "--quiet",
action="store_false", default=True,
help="don't print status messages to stdout")
args = parser.parse_args()
folder = args.folder
print(folder)
files = os.listdir(folder)
valid_objs = 0
invalid_objs = 0
for file in files:
path = os.path.join(folder, file)
all_v, all_f = parse_obj(path)
if check_euler(all_f) == True:
valid_objs += 1
else:
invalid_objs += 1
print("Valid objs:\t {0}".format(valid_objs))
print("Invalid objs:\t {0}".format(invalid_objs))
print("Done!")
return
if __name__ == "__main__":
main()
|
fd75513502365b4d0c3511f44621b838dc3c9725 | mayanbhadage/LeetCode | /280.WiggleSort/wiggle_sort_swap.py | 398 | 3.671875 | 4 | class Solution:
def wiggleSort(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
nums.sort()
ptr1 = 1
ptr2 = ptr1 + 1
while(ptr2 <= len(nums)-1):
nums[ptr1],nums[ptr2] = nums[ptr2], nums[ptr1]
ptr1 += 2
ptr2 = ptr1 + 1
|
9cc9a405ecdbc7e7f74562ca4ee1a9979f3c5198 | GreatGingerKing/Quest_For_The_Master_Sword | /loot.py | 951 | 3.546875 | 4 | from random import random, randint
def loot(inventory, level):
luck=random()
#items=""
if level==1:
if luck>.99:
inventory[1]=1
print "An Iron sword, how lucky!!"
return inventory
elif luck>.95:
inventory[3]=1
print "An, Iron Shield. That's quite rare."
return inventory
elif luck >.6:
luck2=randint(1,3)
if luck2==1:
inventory[4]+=2
print "Two potions. That's pretty good."
return inventory
elif luck2==2:
inventory[4]+=1
inventory[5]+=1
print "A potion and A magic scroll. Nice!"
return inventory
elif luck2==3:
inventory[5]+=2
print "Two magic scrolls. How exciting!"
return inventory
elif luck>.4:
inventory[5]+=1
print "A magic scroll."
return inventory
elif luck>.05:
inventory[4]+=1
print "A potion."
return inventory
else:
print "How unlucky, you didn't get anything."
return inventory
|
f43dd0f942317d4cd7792e6e2f8277dd3f811c25 | JakubKoroluk/Pystart | /Week3/arg funkcji.py | 482 | 3.703125 | 4 | # def get_salary(hours, hourly_rate=25):
# return hours * hourly_rate
#
#
# def calculate_tax(salary, tax_rate=0.19):
# return salary - (salary * tax_rate)
#
#
# hours = int(input('Ilość przepracowanych godzin: '))
# rate = int(input('Twoja stawka godzinowa: '))
#
# salary_with_tax = get_salary(hours, rate)
# salary_netto = calculate_tax(salary_with_tax)
#
# print('Twoje wynagrodzenie wynosi: ')
# print(f'Brutto: {salary_with_tax}')
# print(f'Netto: {salary_netto}')
|
71b3d299e3739eddced31a5e9032dd5386de5c1f | JulienKhlt/TP-1-de-TD-Log | /SolitaireState.py | 2,066 | 3.9375 | 4 | class SolitaireState:
"""A hash key generated form the current state of a solitaire game.
The state is defined by the deck and hand."""
def __init__(self, deck, hand, max_value):
self.deck = sorted(deck)
self.hand = sorted(hand)
# The hashing function depends of the size of the deck
self.state_size = len(self.deck) + len(self.hand)
# Important bc the hashing function is gonna count in that base
self.max_value = max_value
def __eq__(self, other_state):
if len(self.deck) != len(other_state.deck) or len(self.hand) != len(other_state.hand):
return False
for domino in self.deck:
if domino not in other_state.deck:
return False
for domino in self.hand:
if domino not in other_state.hand:
return False
return True
def update_state(self, deck, hand):
self.deck = sorted(deck)
self.hand = sorted(hand)
self.state_size = len(self.hand) + len(self.deck)
@staticmethod
def hash_2(x, y):
return x + (x + y) * (x + y + 1) / 2
@staticmethod
def hash_3(x, y, z):
return SolitaireState.hash_2(SolitaireState.hash_2(x, y), z)
@staticmethod
def hash(int_list):
"""Bijection between N^len(int_list) and N
Should work because we split the state in size
before hashing them and the size of the hand is fixed."""
if len(int_list) == 1:
return SolitaireState.hash_2(int_list[0].rvalue, int_list[0].lvalue)
return SolitaireState.hash_3(int_list[0].rvalue, int_list[0].lvalue, SolitaireState.hash(int_list[1:]))
def __hash__(self):
"""Returns a unique identifier between 0 and max_value ** #(deck + hand)"""
hash_value = 0
full_list = self.deck + self.hand
for index, domino in enumerate(full_list):
hash_value += (self.max_value ** index) * domino.rvalue + (self.max_value ** (index + 1)) * domino.lvalue
return hash_value |
e5ef45deaaa9bf8d5a665dca0d94beb173f287a2 | Ghasemih/Architecture-Design-Assignments | /A1/src/testSeqs.py | 3,796 | 3.515625 | 4 | ## @file testSeqs.py
# @author Hamid Ghasemi 400028420
# @brief Provides the SeqT class to show the sequence
# @date 22/1/2018
from SeqADT import *
from CurveADT import *
## @brief Tests the add funtion method of the SeqT class
# @detail Checks for the index in sequence, if i is within the length it will add otherwise it adds at the end
# the value to its desired position else at the end of the list
t = SeqT()
def test_add():
t.add(0, 1)
t.add(1, 2)
t.add(2, 3)
t.add(1, 4)
# t = [1, 4, 2, 3]
try:
assert t.seq[0] == 1 and t.seq[1] == 4
print ("add test passed")
except AssertionError:
print ("add test failed")
## @brief test_rm function remove the value that user has input
# @detail If index i is in the list return a value
# return value
def test_rm():
# t = [1, 4, 2, 3]
t.rm(1)
# t = [1, 2, 3]
try:
assert t.seq[1] == 2
print ("remove test passed")
except AssertionError:
print ("remove test failed")
## @brief test_set it tests and set value
# @detail Test the cases where input i is in the list
# set a value 3 to 4
def test_set():
# t = [1, 2, 3]
t.set(2, 4)
# t = [1, 2, 4]
try:
assert t.seq[2] == 4
print ("set test passed")
except AssertionError:
print ("set test failed")
## @brief test_get tests if the required value is outputted
# @detail Test the cases where input i (index) is in the list
# return value 2
def test_get():
# t = [1, 2, 4]
t.get(1)
# t [1] = 2
try:
assert t.seq[1] == 2
print ("get test passed")
except AssertionError:
print ("get test failed")
## @brief Verifies the size of the sequence
def test_size():
# t = [1, 2, 4]
try:
assert t.size() == 3
print ("size test passed")
except AssertionError:
print ("size test failed")
## @brief tests if the input value is between two numbers within a sequence
# @detail a real value in the middle
# it must return a index 1
def test_indexInSeq():
# t = [1, 2, 4]
# after using indexInSeq it should give us i = 0
t.indexInSeq(3)
try:
assert t.indexInSeq(3) == 1
print ("indexinseq test passed")
except AssertionError:
print ("indexinseq test failed")
"TESTING CurveADT File"
## @brief Tests the y from the method linVal
# @detail checks for value within a value in the middle of the sequence
# Check a value within the sequence
d = CurveT("1.txt")
def test_linVal(x):
# xcontains: x = [1, 3, 4, 6]
# ycontains: y = [4, 6, 8, 11]
d.linVal(3.4)
try:
assert d.linVal(3.4) == 6.8
print ("linVal test passed")
except AssertionError:
print ("linVal test failed")
## @brief Tests the yvalue from the method quadVal
# @detail checks for value within a value in the middle of the sequence
# Check value whithin sequence
def test_quadVal(x):
# xcontains: x = [1, 3, 4, 6]
# ycontains: y = [4, 6, 8, 11]
d.quadVal(3.4)
try:
assert round(d.quadVal(3.4)) == 7
print ("quadVal test passed")
except AssertionError:
print ("quadVal test failed")
## @brief npolyVal tests the y value with n degree
# @detail input number is 1 for n and 3 for x which return 6.54
def test_npolyval(n, x):
# xcontains: x = [1, 3, 4, 6]
# ycontains: y = [4, 6, 8, 11]
c = d.npolyVal(1,3)
try:
assert round(c, 2) == 6.54
print ("npolyval test passed")
except AssertionError:
print ("npolyval test failed")
test_add()
test_rm()
test_set()
test_get()
test_size()
test_indexInSeq()
test_linVal("1.txt")
test_quadVal("1.txt")
test_npolyval(1, 3)
|
345a2347647e4d3b8ed51d781c4cc7051f3c91f9 | Dmitry1212/PythonBase | /dz5_5.py | 716 | 4.0625 | 4 | # 5. Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами.
# Программа должна подсчитывать сумму чисел в файле и выводить ее на экран.
from random import randint
res = [randint(0, 10) for x in range(25)]
print(res)
line1 = ''
for i in res:
line1 += str(i) + ' '
file = open('text_5_5.txt', 'r+', encoding='utf-8')
file.write(line1)
file.seek(0)
sum1 = 0
for i in file:
temp = list(map(int, i.split()))
for j in temp:
sum1 += j
print(f'Сумма чисел в строке: {sum1}')
file.close()
|
1d5bf0f1be7c4850c9b93e13bf681b0a5419d680 | iceandfire/Blackjack-Python3 | /blackjack.py | 6,373 | 3.984375 | 4 | '''
A simple BlackJack game written in Python 3 using object oriented programming principles
- written by Arham Jamal.
'''
import random
suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10,
'Queen':10, 'King':10, 'Ace':11}
playing = True
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return f"{self.rank} of {self.suit}"
class Deck:
def __init__(self):
self.deck = [] # start with an empty list
for suit in suits:
for rank in ranks:
self.deck.append(Card(suit, rank))
def __str__(self):
comp = ''
for card in self.deck:
comp += '\n' + card.__str__()
return comp
def shuffle(self):
# In place
random.shuffle(self.deck)
def deal(self):
# self.shuffle()
single_card = self.deck.pop()
return single_card
class Hand:
def __init__(self):
self.cards = [] # start with an empty list as we did in the Deck class
self.value = 0 # start with zero value
self.aces = 0 # add an attribute to keep track of aces
def add_card(self, card):
self.cards.append(card)
if card.rank == "Ace":
self.adjust_for_ace()
self.value += self.aces
else:
self.value += values[card.rank]
def adjust_for_ace(self):
if self.value + 11 > 21:
self.aces = 1
else:
self.aces = 11
class Chips:
def __init__(self):
self.total = 0
while self.total == 0:
try:
self.total = int(input('Please enter a value > 0 of the starting amount of chips the player wants: '))
# This can be set to a default value or supplied by a user input
except:
print("Please enter a correct value in numbers.")
continue
else:
break
self.bet = 0
def win_bet(self):
self.total += self.bet
def lose_bet(self):
self.total -= self.bet
def take_bet(chips):
while True:
try:
chips.bet = int(input("Please enter the betting amount:"))
except:
print("Please enter a correct amount in digits.")
continue
else:
if chips.bet <= chips.total:
break
else:
print("The betting amount is greater than chips available.")
continue
def hit(deck,hand):
#dealtcard = deck.deal()
# print(dealtcard)
hand.add_card(deck.deal())
def hit_or_stand(deck,hand):
global playing # to control an upcoming while loop
while True:
x = input('Hit or Stand?')
if x[0].lower() == 'h':
hit(deck,hand)
break
elif x[0].lower() == 's':
print("Player stands. Dealer's turn.")
playing = False
break
else:
print("Something's wrong. Enter again.")
continue
def show_some(player, dealer):
print("Dealer's hand: ")
print(dealer.cards[0])
print('\n')
print("Player's hand: ")
print(*player.cards)
print('\n')
def show_all(player, dealer):
print("Dealer's hand: ")
# asterisk * symbol is used to print every item in a collection
print(*dealer.cards)
print("Dealer's value ", dealer.value)
print('\n')
print("Player's hand: ")
print(*player.cards)
print("Player's hand: ", player.value)
print('\n')
def player_busts(player, dealer, chips):
chips.lose_bet()
print("Player busted")
def player_wins(player, dealer, chips):
chips.win_bet()
print("Player won!")
def dealer_busts(player, dealer, chips):
chips.win_bet()
print("Dealer busted")
def dealer_wins(player, dealer, chips):
chips.lose_bet()
print("Dealer won!")
def push(player, dealer):
print("Dealer and player tie. PUSH")
while True:
# Print an opening statement
print("Welcome to the game of BlackJack")
# Create & shuffle the deck, deal two cards to each player
playing_deck = Deck()
playing_deck.shuffle()
player1 = Hand()
dealer = Hand()
player1.add_card(playing_deck.deal())
player1.add_card(playing_deck.deal())
dealer.add_card(playing_deck.deal())
dealer.add_card(playing_deck.deal())
# Set up the Player's chips
player_chips = Chips()
# Prompt the Player for their bet
take_bet(player_chips)
# Show cards (but keep one dealer card hidden)
show_some(player1, dealer)
while playing: # recall this variable from our hit_or_stand function
# Prompt for Player to Hit or Stand
hit_or_stand(playing_deck, player1)
# Show cards (but keep one dealer card hidden)
show_some(player1, dealer)
# If player's hand exceeds 21, run player_busts() and break out of loop
if player1.value > 21:
player_busts(player1, dealer, player_chips)
break
# If Player hasn't busted, play Dealer's hand until Dealer reaches 17
if player1.value <= 21:
while dealer.value < 17:
hit(playing_deck, dealer)
# Show all cards
show_all(player1, dealer)
# Run different winning scenarios
if dealer.value > 21:
dealer_busts(player1, dealer, player_chips)
elif dealer.value > player1.value:
dealer_wins(player1, dealer, player_chips)
elif player1.value > dealer.value:
player_wins(player1, dealer, player_chips)
else:
push(player1, dealer)
# Inform Player of their chips total
print("Player 1 the total number of chips that you have are: ", player_chips.total)
# Ask to play again
play_again = input("Would you like to play again? Enter Y for Yes and N for No: ").lower()
if play_again == 'y' or play_again == 'yes':
playing = True
continue
elif play_again == 'n' or play_again == 'no':
break
else:
print("Please enter a correct value!")
continue
|
b37ae49d37b0185b7fdc63d286cdbdd750e8becc | qqqlllyyyy/LintCode-Python | /09-High-Frequency/25 Trailing Zeros.py | 483 | 3.8125 | 4 | # Trailing Zeros
# Write an algorithm which computes the number of trailing
# zeros in n factorial.
#
# Example
# 11! = 39916800, so the out should be 2
#
# Challenge
# O(log N) time
#
#
class Solution:
# @param n a integer
# @return ans a integer
def trailingZeros(self, n):
sum = 0
# It will be determined by how many 5's there are.
while n != 0:
sum += n / 5
n = n / 5
return sum
|
a19d773d5ef3c8d6ecad6a6023afdf33bcf95157 | varshajoshi36/practice | /leetcode/python/easy/MinStack.py | 907 | 3.90625 | 4 | '''
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
'''
class MinStack(object):
def __init__(self):
self.stack = []
self.minimum = []
def push(self, x):
self.stack.append(x)
if len(self.minimum) is 0 or x <= self.getMin():
self.minimum.append(x)
def pop(self):
if len(self.stack) is None:
return None
pop = self.stack[len(self.stack) - 1]
if pop is self.getMin():
self.minimum.pop()
self.stack.pop()
def top(self):
if len(self.stack) is 0:
return None
return self.stack[len(self.stack) - 1]
def getMin(self):
if len(self.minimum) == 0:
return None
return self.minimum[len(self.minimum) - 1]
|
ccf914675bb33ca164414b3b9913ca45fa5073d0 | Asunqingwen/LeetCode | /easy/Jewels and Stones.py | 1,034 | 4.125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/8/13 0013 14:58
# @Author : 没有蜡笔的小新
# @E-mail : sqw123az@sina.com
# @FileName: Jewels and Stones.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/Asunqingwen
# @GitHub :https://github.com/Asunqingwen
"""
You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A".
Note:
S and J will consist of letters and have length at most 50.
The characters in J are distinct.
"""
def numJewelsInStones(J: str, S: str) -> int:
j_dict = {}
count = 0
for j in J:
j_dict[j] = 0
for s in S:
if s in j_dict:
count += 1
return count
if __name__ == '__main__':
J = "z"
S = "ZZ"
result = numJewelsInStones(J, S)
print(result)
|
66330cfad5b34aefee40998d6e51f242d2f10b9c | alexeykostyukov/LeetCode | /Sum of Even Numbers After Queries/main.py | 974 | 3.75 | 4 | # https://leetcode.com/problems/sum-of-even-numbers-after-queries/
class Solution:
def sumEvenAfterQueries(self, a: [int], queries: [[int]]) -> [int]:
even_sum = 0
for num in a:
if num % 2 == 0:
even_sum += num
result = []
for value, i in queries:
if a[i] % 2 == 0: # a[i] was even
if value % 2 == 0: # a[i] will stay even
even_sum += value
else: # a[i] become odd
even_sum -= a[i]
a[i] += value
else: # a[i] was odd
if value % 2 == 0: # a[i] will stay odd
a[i] += value
else: # a[i] become even
a[i] += value
even_sum += a[i]
result.append(even_sum)
return result
print(Solution().sumEvenAfterQueries([2, 0, 1, 1], [[1, 0], [1, 0], [-2, 0], [-2, 3], [-1, 3], [10, 3]]))
|
0f2a39b2cb7eecc61d724450d3fe4d154b3713b7 | Timothy254/Playing-with-Python | /Basics/6 Collections.py | 1,918 | 4.03125 | 4 | #are containers used for storing data and are commonly known as data structures, such as lists, tuples, arrays, dictionaries
#counter It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values.
# Counts are allowed to be any integer value including zero or negative counts.
'''
from collections import Counter
a = "aaaabbbcccc"
mycounter = Counter(a)
print(mycounter)
print(mycounter.most_common(1))
print(list(mycounter.elements()))
'''
#namedtuple Python's namedtuple() is a factory function available in collections .
# It allows you to create tuple subclasses with named fields.
'''
from collections import namedtuple
Point = namedtuple('Point', 'x,y')
pt = Point(1, -4)
print(pt)
print(pt.x, pt.y)
'''
#OrderedDict is a dict subclass that preserves the order in which key-value pairs, commonly known as items, are inserted into the dictionary.
#When you iterate over an OrderedDict object, items are traversed in the original order.
#If you update the value of an existing key, then the order remains unchanged.
'''
from collections import OrderedDict
ordered_dict = OrderedDict()
ordered_dict['a'] = 1
ordered_dict['b'] = 2
ordered_dict['c'] = 3
ordered_dict['d'] = 4
print(ordered_dict)
'''
#defaultdict means that if a key is not found in the dictionary, then instead of a KeyError being thrown, a new entry is created.
'''
from collections import defaultdict
d = defaultdict(int)
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
print(d['g'])
'''
#deque is a double-ended queue that's useful for implementing elegant, efficient, and Pythonic queues and stacks
from collections import deque
d = deque()
d.append(1)
d.append(2)
d.appendleft(3)
d.append(4)
d.pop()
d.popleft()
#d.clear()
d.extend([5,6,7])
d.extendleft([8,9,10])
d.rotate(1)
d.rotate(-2)
print(d) |
e285d2c6b5cd1faad8a2eecef8cc8f6489110508 | priyalorha/python | /dijkstra.py | 1,279 | 3.984375 | 4 | graph={'a':{'b':8,'c':2},
'b':{'a':8,'f':13},
'c':{'a':2,'d':2},
'd':{'a':5,'b':2,'c':2,'e':1,'f':6,'g':3},
'e':{'c':5,'d':1,'g':1},
'f':{'b':13,'d':6,'g':2,'h':3},
'g':{'e':1,'d':3,'f':2,'h':6},
'h':{'g':6,'f':3}}
def dijkstra(graph,start,destination):
shortest_distance={}
predecessor={}
unseenNodes=graph
infinity=999999
path=[]
shortest_distance={key:infinity for key in graph}
shortest_distance[start]=0
while unseenNodes:
minNode=None
for node in unseenNodes:
if minNode is None:
minNode=node
elif shortest_distance[node]<shortest_distance[minNode]:
minNode=node
print(graph[minNode].items())
for childNode,weight in graph[minNode].items():
if weight + shortest_distance[minNode]<shortest_distance[childNode]:
shortest_distance[childNode]=weight + shortest_distance[minNode]
predecessor[childNode]=minNode
unseenNodes.pop(minNode)
currentNode=destination
while currentNode!=start:
try:
path.insert(0,currentNode)
currentNode=predecessor[currentNode]
except KeyError:
print('Path not reachable')
break
if shortest_distance[destination]!=infinity:
print('Shortest distance ' + str(shortest_distance[destination]))
print('and the path is ' + str(path))
dijkstra(graph,'a','h')
|
9af174f8ffd8b85fcc627de2a24157c30e720a5b | desertSniper87/leetcode | /merge-intervals.py | 731 | 3.890625 | 4 | from typing import List
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key= lambda x: x[0])
result = []
for [i, j] in intervals:
if not result:
result.append([i, j])
continue
current = result[-1]
if i <= current[1] and j >= current[1]:
result[-1] = [current[0], j]
elif i <= current[1] and j <= current[1]:
continue
else:
result.append([i, j])
return result
if __name__ == "__main__":
s = Solution()
# print(s.merge([[1,3],[2,6],[8,10],[15,18]]))
print(s.merge([[1,4],[4,5]]))
|
49014b1a4d483d58065abffc39d6e1dcf77249b2 | ivan-yosifov88/python_oop | /iterators_and_generators/exercise/dictionary_iterator.py | 523 | 3.640625 | 4 | class dictionary_iter:
def __init__(self, dict_object):
self.dict_object = dict_object
self.dict_keys = list(dict_object.keys())
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index == len(self.dict_keys):
raise StopIteration
key = self.dict_keys[self.index]
value = self.dict_object[key]
self.index += 1
return key, value
result = dictionary_iter({1: "1", 2: "2"})
for x in result:
print(x)
|
caed1d2f299521d550fc810dc78a906c3071a040 | klq/euler_project | /euler21.py | 1,304 | 3.875 | 4 | import math
def euler21():
"""
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110;
therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.
"""
N = 10000
divisor_sums = [0]*2
for i in range(2,N):
divisor_sums.append(divisor_sum(i))
amicable_total = 0
for i in range(2,N):
j = divisor_sums[i]
# if amicable:
if j<N and i == divisor_sums[j] and i!=j:
amicable_total = amicable_total + i + j
print i, j
amicable_total /= 2
return amicable_total
def divisor_sum(n):
"""
returns the sum of proper divisors of n (numbers less than n which divide evenly into n)
"""
divisors = [1]
upper = int(math.sqrt(n))
for i in range(2, upper+1):
if n % i == 0:
divisors.append(i)
if i*i != n:
divisors.append(n/i)
return sum(divisors)
print euler21() #31626 |
91ceb0731b036c09dfc46263650e3f30033d9867 | brittanylindberg98/homework3 | /solution-321.py | 292 | 3.796875 | 4 | n=int(input("Enter cost in cents:"))
change=100-n
quarters=int(change//25) # 1 quarters=25 cents
dimes=int((change-25*quarters)//10) # 1 dime=10 cents
pennies=int((change-25*quarters-10*dimes)) # 1 penny=1 cent
print(quarters,"quarters")
print(dimes,"dimes")
print(pennies,"pennies")
|
f743950e071fdb8cf854e30b69ca1fa9bae29735 | busz/my_leetcode | /python/reverse_integer.py | 969 | 3.71875 | 4 | '''
Created on 2014-2-19
leetcode reverse integer
Problem :
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Solve :
str() and int() and cut
@author: xqk
'''
class Solution:
# @return an integer
#===========================================================================
# def reverse(self, x):
# x = str(x);
# if x[0] == '-':
# x = x[1:]
# x = x[::-1]
# x = '-'+x
# else:
# x = x[::-1]
# return int(x)
#===========================================================================
#or
def reverse(self , x):
r = 0;
if x == 0 :
return 0
f = x/abs(x);
x = x*f
while(x):
r = r*10 + x%10
x = x/10
return r*f
a = -123
a = 0
test = Solution()
print test.reverse(a) |
4808f515c0d7ff4ee0718a4db417814b4b533411 | JuanDiazUPB/LogicaProgramacionUPB | /Laboratorios/Lab1903/Ejercicios for 8.py | 451 | 3.65625 | 4 | print('Ejercicio 8: Escribir un programa que permita al usuario ingresar dos años y luego imprima todos los años en ese rango, que sean bisiestos y múltiplos de 10.')
anioInicio = int(input("Año inicial: "))
anioFin = int(input("Año final: "))
for anio in range(anioInicio, anioFin+1):
if not anio % 10 == 0:
continue
if not anio % 4 == 0:
continue
if anio % 100 != 0 or anio % 400 == 0:
print(anio)
|
d6b735d5468b020b99b1997605a3f3f3852b170b | sotojcr/100DaysOfCode | /PythonLearningStep1/modulesLearning/01osModule.py | 772 | 4.09375 | 4 | #os module
import os
# print(dir(os)) #list all the functions
os.chdir('D:\\pkworkspace\\100DaysDataScience\\PythonLearningStep1\\modulesLearning')
print(os.getcwd()) #path of ur current directory
print(os.listdir()) #list the files in current directory
# os.mkdir('OsDemoFolder1') #create directory
# os.mkdirs is used to create the deep folders
'''
os.mkdirs('osdemo2/ossubdir') --> create osdemo2 and inside it
create ossubdir
'''
#to remove dir
# os.rmdir('OsDemoFolder1')
#print all infor
# print(os.stat('OsDemoFolder'))
'''os.walk() give all the info from top to bottom approach
'''
for dirPath, dirName, fileName in os.walk('D:\\pkworkspace'):
print('Current Path: ', dirPath)
print('Directories: ', dirName)
print('Files', fileName)
|
02dcb322b27d1d251514ce17075e365f5d1d06ef | Srinivas-Voore/My-Python-Programs | /python Basics-2/8.sets.py | 621 | 3.875 | 4 | #sets
s1=set()
s2={}
s3=set([1,2,3,4])
s4={1,2,3,4}
print(s1)
print(s2)
print(s3)
print(s4)
#adding add(),update()
s1=set()
s1.add(1)
s1.add((2,3))
s1.add(1)
print(s1)
s1.update([11,12])
print(s1)
#accessing
s1=set([1,2,3])
for i in s1:
print(i,end=" ")
print()
#removing remove(),discard(),poop(),clear()
sx=set([1,2,3,4,5,6])
sx.remove(5)
print(sx)
sx.discard(2)
print(sx)
sx.pop()
print(sx)
sx.pop()
print(sx)
#frozen set a set which is immutable
sy={1,2,3,4,5,1,2,3,4,5}
fs=frozenset(sy)
print(fs)
sy.add(10)
print(sy)
sy.add(6)
print(sy)
|
32ffe0248e95b1d32d6c9edb1575b3c2529ac98a | NehaNagmule/Marvellous-Infosystem-Python-Assignments | /Assignments1/Assignment1_9.py | 401 | 3.5 | 4 | def ChkEven(iNo):
if iNo % 2 == 0:
return True
def main():
iNo = int(input("Enter number : "))
iCheckCount = 0
iCnt = 1
while iCheckCount < 10:
if ChkEven(iCnt) == True:
print(iCnt, " ", end='')
iCheckCount = iCheckCount + 1
if iCheckCount == iNo:
break
iCnt = iCnt + 1
if __name__ == "__main__":
main()
|
21469c7ae754e36b14229c8348606d7bff17f1c6 | syurskyi/Python_3_Deep_Dive_Part_2 | /Section 10 Context Managers/100. Not just a Context Manager.py | 1,588 | 4.0625 | 4 | print('#' * 52 + ' ### Not Just a Context Manager')
f = open('test.txt', 'w')
f.writelines('this is a test')
f.close()
print('#' * 52 + ' On the other hand we can also use it with a context manager:')
with open('test.txt') as f:
print(f.readlines())
print('#' * 52 + ' We can implement classes that implement their own functionality'
' as well as a context manager if we want to.')
class DataIterator:
def __init__(self, fname):
self._fname = fname
self._f = None
def __iter__(self):
return self
def __next__(self):
row = next(self._f)
return row.strip('\n').split(',')
def __enter__(self):
self._f = open(self._fname)
return self
def __exit__(self, exc_type, exc_value, exc_tb):
if not self._f.closed:
self._f.close()
return False
with DataIterator('nyc_parking_tickets_extract.csv') as data:
for row in data:
print(row)
print('#' * 52 + ' Of course, we cannot use this iterator without also using the context manager'
' since the file would not be opened otherwise:')
data = DataIterator('nyc_parking_tickets_extract.csv')
# for row in data:
# print(row) # TypeError: 'NoneType' object is not an iterator
print('#' * 52 + ' But I want to point out that creating the context manager and using the `with` statement'
' can be done in two steps if we want to:')
data_iter = DataIterator('nyc_parking_tickets_extract.csv')
with data_iter as data:
for row in data:
print(row)
|
c9bf4f9ded392b6edc183e9ec0fea6583cf481c6 | ohdnf/algorithms | /programmers/high-score-kit/stack_queue/tower.py | 1,117 | 3.9375 | 4 | # def solution(heights):
# answer = [0 for _ in range(len(heights))]
# while len(heights) > 1:
# height = heights.pop()
# i = len(heights)
# for j in range(len(heights)-1, -1, -1):
# if heights[j] > height:
# answer[i] = j+1
# break
# return answer
# 강사님 풀이
# 순방향 순회
# def solution(heights):
# answer = []
# for i in range(len(heights)):
# for j in range(i, -1, -1):
# if heights[i] < heights[j]:
# answer.append(j+1)
# break
# else:
# answer.append(0)
# return answer
# 스택 활용
def solution(heights):
answer = []
for i in range(len(heights)):
stack = []
for j in range(i):
if heights[i] < heights[j]:
stack.append(j+1)
if stack:
answer.append(stack.pop())
else:
answer.append(0)
return answer
if __name__ == "__main__":
print(solution([6,9,5,7,4]))
print(solution([3,9,9,3,5,7,2]))
print(solution([1,5,3,6,7,6,5])) |
c65b2dcd46b3301267bfd0739368d2dfadf23c7f | jacobmetcalfe/Machine_Learning | /first_application.py | 3,394 | 3.78125 | 4 | import scipy as sp
import matplotlib.pyplot as plt
# hypothetical web start-up company When do we have to request additional servers in the cloud to serve all the
# incoming requests successfully without paying for unused ones
# Reading in the data
# Says get from the text and the delimiter means that the data will be a tab away
data = sp.genfromtxt("web_traffic.tsv", delimiter="\t")
# Gets first ten pieces of data so we know it's grabbing something
print(data[:10])
# Prints what we need to limit the data into
print(data.shape)
print('The data is 743 rows and 2 columns')
print('\n Cleaning the Data')
# Pre processing and cleaning the data
# we will separate this into two vectors
# First Vector = Hours (Every row of the first column)
x = data[:, 0]
# Second Vector = web hits (Every row of the second column)
y = data[:, 1]
print('This is how many values of web hits are nan')
print(sp.sum(sp.isnan(y)))
print('We are missing 8/743 entries, so we can remove them')
# Sp.isnan returns an array of Booleans indicating whether an entry is a number or not
# We are negating those numbers so that it is the array minus the values in column 2 that are nan
x = x[~sp.isnan(y)]
y = y[~sp.isnan(y)]
# Visualizing our data
# Plots points with size = 10
plt.scatter(x, y, s=10)
plt.title("Web traffic over the last month")
plt.xlabel("Time")
plt.ylabel("Hits/Hour")
plt.xticks([w * 7 * 24 for w in range(10)], ['week %i' % w for w in range(10)])
plt.autoscale(tight=True)
# Drawing a grid
plt.grid(True, linestyle='-', color='.75')
# Choosing the right model and learning algorithm
print('Steps to choose the right model and learning algorithm')
print('-------------------------------------------------------')
print('1. Find the real model behind the noisy data points')
print('2, Following this, use the model to extrapolate into the future to find the point in time where our '
'infrastructure has to be extended')
# Before building
# Simple theoretical approximations of complex reality
# There is going to be approximation error
def error(f, x, y):
return sp.sum((f(x) - y) ** 2)
# Starting with a simple straight line Putting this line, in the into the chart so that it results in the smallest
# approximation error polyfit() does exactly that. Given data x and y and the desired order of the polynomial (
# Straight line has an order of 1), it finds the model function that minimizes the error function defined earlier
fp1, residuals, rank, sv, rcond = sp.polyfit(x, y, 1, full=True)
# Polyfit() returns the parameters of the fitted model function, fp1
# By setting full = True we get extra information
print("Model parameters: %s" % fp1)
print('So your equation is 2.59619213x + 989.02487106')
print('Error of Approximation')
print(residuals)
# poly1d() is then used to create a model function from the model parameters
f1 = sp.poly1d(fp1)
print(error(f1, x, y))
# x values
fx = sp.linspace(0, x[-1], 1000) # generate X-values for plotting
plt.plot(fx, f1(fx), linewidth=4, c='green')
plt.legend(["d=%i" % f1.order, "Number of Hits / Time"], loc="upper left")
plt.show()
# Although the graph doesn't look bad, it's not great
# How bad actually is the error 317,389,767.34?
# Number doesn't mean much, however we can compare it to other graphs and find the lower error
|
75052b07d3015645e95abf84cf46377091b8f267 | parambole/LeetCode | /Trees/max-width.py | 809 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def widthOfBinaryTree(self, root: TreeNode) -> int:
max_width = 0
if not root:
return max_width
queue = deque()
queue.append((root,0))
while queue:
level = len(queue)
_, curr = queue[0]
for _ in range(level):
node, val = queue.popleft()
if node.left:
queue.append((node.left, 2 * val))
if node.right:
queue.append((node.right, 2 * val + 1))
max_width = max(max_width, val - curr + 1)
return max_width
|
cfc3748c5ba7d694698f4605133ba87392a079f7 | mankal-27/Age_Month_Calculator | /Month_Days.py | 1,191 | 4.125 | 4 | import calendar
import time
#Check For Leap year
def leap_year(year):
if calendar.isleap(year):
return True
else:
return False
#Return the Number of days in months
def days_month(month,leap_year):
if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12 :
return 31
elif month == 4 or month == 6 or month == 9 or month == 11 :
return 30
elif month == 2 and leap_year:
return 29
elif month == 2 and (not leap_year):
return 28
name = input("Enter Your Name : ")
age = int(input("Enter your age : "))
localtime = time.localtime(time.time())
year = int(age)
month = year * 12 + localtime.tm_mon
day = 0
begin_year = int(localtime.tm_year) - year
end_year = begin_year + year
# calculate the days
for y in range(begin_year, end_year):
if (leap_year(y)):
day = day + 366
else:
day = day + 365
leap_year = leap_year(localtime.tm_year)
for m in range(1, localtime.tm_mon):
day = day + days_month(m, leap_year)
day = day + localtime.tm_mday
print("%s's age is %d years or " % (name, year), end="")
print("%d months or %d days" % (month, day))
|
091cec0d7c266556187abb66e08e8bca3696ca3a | pratik3333/python-oop | /Classes_and_Instances.py | 506 | 3.765625 | 4 | class Employee:
def __init__(self,first,last,pay,country):
self.first=first
self.last=last
self.pay=pay
self.email=first+last+'123@gmail.com'
self.country=country
def fullname(self):
return '{} {}'.format(self.first,self.last)
emp_1=Employee('Corey','Schafer',80000,'New York')
emp_2=Employee('Pratik','Kagale',78000,'India')
print(emp_1.fullname())
print(emp_2.fullname())
print(emp_1.email)
print(emp_2.email)
print(emp_1.country)
print(emp_2.country) |
52923cad74528bd430283081525c94e7505da87e | informatorio2020com07/actividades | /meza_cristian/002/main.py | 1,920 | 4.15625 | 4 | """
Realizar un función que reciba como parámetro una cantidad de segundos, y devuelva una tupla con la cantidad de segundos
expresada en hh,mm,ss.
Realizar una función que reciba como parámetros cantidades de horas, minutos y/o segundos.
Y que retorne la suma de estos expresanda en segundos. (Los parámetros, son opcionales y por defecto sus valores 0.)
En otro archivo, importar las funciones creadas.
Realizar un programa que:
Primero pregunte por una cantidad de segundos, y diga cuantas horas, minutos y segundos son.
Luego, preguntar por una cantidad de minutos y decir a cuantas horas, minutos y segundos representa.
Después, solicitar al usuario ingresar una cantidad de tiempo expresada en una cadena de cáracter como "hs:mm:ss".
Mostrar cuantas horas ingresó el usuario, cuantos minutos, y cuantos segundos en distintas lineas.
Luego mostrar a cuanto tiempo expresado en segundos equivale.
Horas: 10
Minutos: 30
Segundos: 25
Equivale a: 37825 Segundos.
"""
from conversor import *
seg = int(input("Ingresar Cantidad de Segundos: "))
print("Segundos Expresados en HH:MM:SS = {}:{}:{}".format(*segundos_HMS(seg)))
min = int(input("Ingresar Cantidad de Minutos: "))
print("Minutos Expresados en HH:MM:SS = {}:{}:{}".format(*segundos_HMS(min * 60)))
cadena = input("Ingresar Horas Minutos y Segundos con el siguiente formato = hs:mm:ss : ")
cadena=cadena.split(":")
hs = 0
min = 0
seg = 0
for x in range(0, len(cadena)):
if cadena == ['']:
break
if (x == 0):
hs = int(cadena[0])
if (x == 1):
min = int(cadena[1])
if (x == 2):
seg = int(cadena[2])
print("Horas: ", hs)
print("Minutos: ", min)
print("Segundos: ", seg)
convert = total_segundos(int(hs), int(min), int(seg))
print("Equivale a: {seg} Segundos.".format(seg=convert))
print("Segundos Expresados en HH:MM:SS = {}:{}:{}".format(*segundos_HMS(convert)))
|
1c3b8acca9866751683d13b6593105ffa9e4e317 | weak-head/leetcode | /leetcode/p0160_intersection_of_two_linked_lists.py | 2,513 | 3.921875 | 4 | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def getIntersectionNode_math(headA: ListNode, headB: ListNode) -> ListNode:
"""
If there is an intersection of A and B,
then we know that the length of A is a + c,
and the length of B is b + c, where:
a - length of A head
b - length of B head
c - length of A/B intersection
So we can use this property, to traverse the
A and B at the same time, to find the intersection.
For example we have two lists:
A -> [1 2 9 a b]
B -> [1 2 3 4 5 6 7 8 9 a b]
where intersection is: [9 a b]
A length = 2 + 3
B length = 8 + 3
Traverse A and B at the same time while A or B are not none
a -> [1 2 9 a b] => None
b -> [1 2 3 4 5] => [6 7 8 9 a b]
Let A point to B head:
a -> [1 2 3 4 5 6 7 8 9 a b]
b -> [6 7 8 9 a b]
Keep traversing:
a -> [1 2 3 4 5 6] => [7 8 9 a b]
b -> [6 7 8 9 a b] => None
Let B point to A head:
a -> [7 8 9 a b]
b -> [1 2 9 a b]
Keep traversing:
a -> [7 8] => [9 a b]
b -> [1 2] => [9 a b]
If there is no intersection,
on the second iteration
both pointers would be None.
Time: O(n + m)
Space: O(1)
n - length of A
m - length of B
"""
pA, pB = headA, headB
while pA != pB:
pA = headB if pA is None else pA.next
pB = headA if pB is None else pB.next
return pA
def getIntersectionNode_fastslow(headA: ListNode, headB: ListNode) -> ListNode:
"""
- Create cycle in A.
- Detect cycle in B.
- If there is a cycle in B, find the start of the cycle
Slow, complex and not efficient.
Time: O(n + m)
Space: O(1)
n - length of A
m - length of B
"""
if headA is None or headB is None:
return None
tailA = headA
while tailA.next is not None:
tailA = tailA.next
# create cycle in A
tailA.next = headA
# detect cycle in B
fastB = slowB = headB
while fastB and fastB.next:
slowB = slowB.next
fastB = fastB.next.next
if fastB == slowB:
break
# no cycle in B
if fastB is None or fastB.next is None:
tailA.next = None
return None
# detect start of the cycle
slowB = headB
while fastB != slowB:
fastB = fastB.next
slowB = slowB.next
tailA.next = None
return fastB
|
7c217f4ffc5bdd97f796307fd9fa9dd3b2dedfaa | prashant97sikarwar/leetcode | /Graph/FloodFill.py | 1,255 | 4 | 4 | #Problem Link :- https://leetcode.com/problems/flood-fill/
""" An image is represented by a 2-D array of integers, each integer representing the
pixel value of the image (from 0 to 65535).Given a coordinate (sr, sc) representing the
starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood
fill" the image.To perform a "flood fill", consider the starting pixel, plus any pixels
connected 4-directionally to the starting pixel of the same color as the starting pixel,
plus any pixels connected 4-directionally to those pixels (also with the same color as
the starting pixel), and so on. Replace the color of all of the aforementioned pixels
with the newColor. """
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
def flood(mat,x,y,prev,k):
if x < 0 or y < 0 or x >= len(mat) or y >= len(mat[0]) or mat[x][y] != prev or mat[x][y] == k:
return
mat[x][y] = k
flood(mat,x-1,y,prev,k)
flood(mat,x+1,y,prev,k)
flood(mat,x,y+1,prev,k)
flood(mat,x,y-1,prev,k)
prev = image[sr][sc]
flood(image,sr,sc,prev,newColor)
return image
|
2112933e651c11ad10486ec1520a72818fc29900 | newton-li/GIS6345 | /Exercise9.2.3.py | 241 | 3.703125 | 4 | fin = open('words.txt')
total = 0
count = 0
for line in fin:
word = line.strip()
letter = 'e'
total = total + 1
if letter not in word:
print(word)
count = count + 1
print(count/total * 100)
|
5bbb57ebc3273bd63125300387db84cea251399d | ix-ds-lisbon-s1-2019/week-1-project-madeleinehoang | /poker_game.py | 1,887 | 3.984375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 28 15:54:29 2019
@author: student
"""
#%%
import random
def game( number_of_players ):
names =[input( "Please enter your name: ") for i in range( number_of_players ) ]
cards = [ "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3", "2" ] * 4
values = {"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
"10": 10,
"J": 11,
"Q": 12,
"K": 13,
"A": 14}
hand = {}
ordered_hand = {}
for name in names:
hand[ name ] = []
ordered_hand[ name ] = []
for i in range ( 0, 5 ):
choice = random.choice( cards )
hand[ name ] += [ choice ]
value = values.get( choice )
ordered_hand[ name ] += [ value ]
cards.remove( choice )
print("{}'s hand is {}, {}, {}, {}, {}.".format(
name,
hand[name][0],
hand[name][1],
hand[name][2],
hand[name][3],
hand[name][4]))
ordered_hand[name].sort( reverse = True )
compare = {}
for name, value in ordered_hand.items():
if not compare:
compare[name] = value
continue
for i in range( 0, 5 ):
if value[ i ] == list( compare.values() )[ 0 ][ i ]:
continue
elif value[ i ] > list( compare.values() )[ 0 ][ i ]:
compare = { name: value }
break
break
result = "The winner is {}.".format( list( compare.keys()) [ 0 ] )
return result
game( 8 ) |
503324e2f9cfdbbd356a9307c97a774338cd1b1f | EricGao-Byte/My_Python_Practice | /python教程练习/条件运算符.py | 197 | 3.90625 | 4 | # 三元运算符: 语句1 if 表达式 else 语句2
a=10
b=20
print('a的值比较大') if a>b else print('b的值比较大')
# 第二种写法
if a>b:
print("a big")
else:
print('b big')
|
1855c4c7b9d822b672ebef4b10324e9295f9251f | sophiarora/CS61A | /scheme/ok_test.py | 1,378 | 3.578125 | 4 | >>> from scheme import *
>>> env = create_global_frame()
>>> twos = Pair(2, Pair(2, nil))
>>> plus = PrimitiveProcedure(scheme_add) # + procedure
>>> scheme_apply(plus, twos, env)
Choose the number of the correct choice:
0) 4
1) SchemeError
>>> from scheme import *
>>> env = create_global_frame()
>>> twos = Pair(2, Pair(2, nil))
>>> oddp = PrimitiveProcedure(scheme_oddp) # odd? procedure
>>> scheme_apply(oddp, twos, env)
Choose the number of the correct choice:
0) SchemeError
1) True
2) False
>>> from scheme import *
>>> env = create_global_frame()
>>> two = Pair(2, nil)
>>> eval = PrimitiveProcedure(scheme_eval, True) # eval procedure
>>> scheme_apply(eval, two, env) # be sure to check use_env
>>> from scheme import *
>>> env = create_global_frame()
>>> args = nil
>>> def make_scheme_counter():
... x = 0
... def scheme_counter():
... nonlocal x
... x += 1
... return x
... return scheme_counter
>>> counter = PrimitiveProcedure(make_scheme_counter()) # counter
>>> scheme_apply(counter, args, env) # only call procedure.fn once!
def retrieve_element(exp):
values = []
if len(exp) == 2:
values = [exp.first]
return values
else:
while scheme_listp(exp):
exp = exp.first
values += [exp]
exp = exp.second
values += [retrieve_element(exp)]
return values
|
0b173113a90292805ad99810cbe68fb73e6a5a97 | ramranganath/Python | /dataScproj/oneDScatterPlot.py | 866 | 3.640625 | 4 | # reading the 1D scatter plot which is important for study
import numpy as np
import seaborn as sns
iris_setosa =iris.loc(iris["species"]== "setosa"];
iris_verginica =iris.loc(iris["species"]== "virginica"];
iris_versicolor =iris.loc(iris["species"]== "versicolor"];
#print(iris_setosa["petalLength"])
plt.plot(iris_setosa["PetalLength"], np.zeros_like(iris_setosa['PetalLength']);
plt.plot(iris_virginica["PetalLength"], np.zeros_like(iris_virginica['PetalLength']);
plt.plot(iris_versicolor["PetalLength"], np.zeros_like(iris_versicolor['PetalLength']);
plt.show();
# Disadvantages of 1D Scatter plot is
# 1. Overlapping of lot of points
# 2. We need to discover better ways to visualize the 1 D Scatter plot.
sns.FacetGrid(iris hue="specis", size =5) \
. map(sns.distplot, "PetalLength") \
.add_legend();
plt.show(); |
0d5c0e4a92131b011d2a0c07acca98b5cd4c4664 | 106368404ZhouHouCheng/hello-world | /ex03.py | 1,405 | 4.46875 | 4 | #Integer
#print "count chickenns"
print "I will now count my chickens:"
#print and calculate the numbers of 'Hens'
print "Hens", 25+30/6
#print and calculate the numbers of 'Roosters'
print "Roosters", 100-25*3%4
#print "count eggs"
print "Now I will count the eggs:"
#calculate 3+2+1-5+4%2-1/4+6
print 3+2+1-5+4%2-1/4+6
#print and calculate 3+2
print "What is 3+2?", 3+2
#print and calculate 5-7
print "What is 5-7?", 5-7
#print Oh, that's why it's False.
print "Oh, that's why it's False."
#print How about some more.
print "How about some more."
#compare 5,-2
print "Is it greater?", 5 > -2
print "Is it greate or equal?",5 >= -2
print "Is it less or equal?", 5 <= -2
print "\n-------------------------\n"
#float
#print "count chickenns"
print "I will now count my chickens:"
#print and calculate the numbers of 'Hens'
print "Hens", 25.0+30/6
#print and calculate the numbers of 'Roosters'
print "Roosters", 100.0-25*3%4
#print "count eggs"
print "Now I will count the eggs:"
#calculate 3+2+1-5+4%2-1/4+6
print 3.0+2+1-5+4%2-1/4+6
#print and calculate 3+2
print "What is 3+2?", 3.0+2
#print and calculate 5-7
print "What is 5-7?", 5.0-7
#print Oh, that's why it's False.
print "Oh, that's why it's False."
#print How about some more.
print "How about some more."
#compare 5,-2
print "Is it greater?", 5.0 > -2.0
print "Is it greate or equal?",5.0 >= -2.0
print "Is it less or equal?", 5.0 <= -2.0
|
924312f24fac5d77638f088c958d22214e5d7fc2 | SahilMund/A_ML_Cheatsheets | /Machine Learning A-Z Template Folder/Part 6 - Reinforcement Learning/Section 33 - Thompson Sampling/ThompsonSampling.py | 1,397 | 3.5625 | 4 | # Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Ads_CTR_optimisation.csv')
N=10000 #Representing the number of customers
d=10 #Representing the no of ad versions
ads_selected=[]
#[0] * d represents a vector containing only zeros of size d. It is because initially the numbers_of_rewards_1 and snumbers_of_rewards_0 of each round is 0
numbers_of_rewards_1=[0] * d #no. of times ad gets reward 1 upto round n
numbers_of_rewards_0=[0]*d #no. of times ad gets reward 0 upto round n
total_reward=0
#calculating avg reward and confidence at each round
import random
for n in range(0,N): #for all customers on social media
max_random=0
ad=0
for i in range(0,d): #for all add versions
random_beta=random.betavariate(numbers_of_rewards_1[i]+1,numbers_of_rewards_0[i]+1)
if random_beta>max_random:
max_random=random_beta
ad=i
ads_selected.append(ad)
reward=dataset.values[n,ad]
if reward==1:
numbers_of_rewards_1[ad]=numbers_of_rewards_1[ad]+1
else:
numbers_of_rewards_0[ad]=numbers_of_rewards_0[ad]+1
total_reward=total_reward + reward
#Visualizing the results
plt.hist(ads_selected)
plt.title('Histogram of Ads selections')
plt.xlabel('Ads')
plt.ylabel('No.of times each ad was selected')
plt.show()
|
0bdbfb107cc552b511e64f9a36fc1aa1c10eef07 | friskycodeur/DS-ALGO | /Linked List/implementation.py | 732 | 4.09375 | 4 | class Node:
def __init__(self,data=None,next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def insert_at_beginning(self,data):
node = Node(data,self.head)
self.head = node
def print_linked_list(self):
if self.head is None:
print("Linked List is empty")
return
itr = self.head
llstr = ''
while itr:
llstr += str(itr.data) +' '
itr = itr.next
print(llstr)
if __name__ == '__main__':
ll = LinkedList()
ll.insert_at_beginning(1)
ll.insert_at_beginning(2)
ll.insert_at_beginning(3)
ll.print_linked_list() |
3a6289fcc1b74ddad4e47dfa3ffb247f8be91220 | temitopeakin1/csc-algorithms | /computational-science-and-numerical-methods/Bisection Algorithm (with error).py | 485 | 4.03125 | 4 | print('Bisection Algorithm - Error')
import math
def f(x):
fx = math.pow(x,3) - (3 * x) + 1
return fx
a, b = 0, 1
old_value = a
err = 0.05
abs_err = 1
while(abs_err >= err):
c = (a+b)/2
if (f(a)*f(c))<0:
a, b = a, c
else:
a, b = c, b
abs_err = abs(c - old_value)
old_value = c
print("The root of the equation is %0.4f"%c)
print("The function of the equation is %0.4f"%f(c))
print("The absolute error of the equation is %0.4f"%abs_err) |
0041e5acc7d6f19a349df8f467c15d4db3c82798 | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/sbysiz002/mymath.py | 294 | 3.96875 | 4 | def get_integer(letter):
l = input ("Enter "+letter+":\n")
while not l.isdigit ():
l = input("Enter "+letter+":\n")
l = eval (l)
return l
def calc_factorial(l):
nfactorial = 1
for i in range (1, l+1):
nfactorial *= i
return nfactorial |
067d39529b85acb4cb4fa71e08fd13027da45370 | Kakarhot/Unscramble-Computer-Science-Problems | /Task4.py | 1,853 | 4.1875 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
# import pandas as pd
# calls = pd.read_csv('calls.csv', header=None, names=['sending_number', 'receiving_number', 'time', 'duration'])
# texts = pd.read_csv('texts.csv', header=None, names=['sending_number', 'receiving_number', 'time'])
# receiving_numbers = calls.receiving_number.append([texts.sending_number, texts.receiving_number]).unique()
# marketing_numbers = []
# for number in calls.sending_number.unique():
# if number not in receiving_numbers:
# marketing_numbers.append(number)
# print("These numbers could be telemarketers: ")
# for number in sorted(marketing_numbers):
# print(number)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
calls_list = []
for entry in calls:
calls_list.append(entry[0])
non_call_list = []
for entry in calls:
non_call_list.append(entry[1])
for entry in texts:
non_call_list.append(entry[0])
non_call_list.append(entry[1])
calls_set = set(calls_list)
non_calls_set = set(non_call_list)
marketing_numbers = []
for number in calls_set:
if number not in non_calls_set:
marketing_numbers.append(number)
print("These numbers could be telemarketers: ")
for number in sorted(marketing_numbers):
print(number)
|
9f49a90f18786285141e0c43de7c530034ad05f1 | shivesh01/Python-Basics | /tuples/tuple_10.py | 196 | 3.78125 | 4 | #tuple methods this two methods are available in tuple
my_tuple = ('a', 'p', 'p', 'l', 'e')
print(my_tuple.count('p'))
print(my_tuple.index('l'))
print('a' in my_tuple)
print('g' in my_tuple) |
ce76353fb1acc9ccb55576ba2152e09df62e5444 | PetarSP/SoftUniFundamentals | /Final Exam Retake 10.04.2020/03. Need for Speed III.py | 1,843 | 3.90625 | 4 | # 10:20
number_of_cars = int(input())
car_dict = {}
for cars in range(number_of_cars):
car_input = input()
car, mileage, fuel = car_input.split("|")
car_dict[car] = {}
car_dict[car]["mileage"] = int(mileage)
car_dict[car]["fuel"] = int(fuel)
command = input()
while not command == "Stop":
command = command.split(" : ")
instruction = command[0]
car = command[1]
if instruction == "Drive":
distance = int(command[2])
fuel = int(command[3])
if car_dict[car]["fuel"] <= fuel:
print(f"Not enough fuel to make that ride")
else:
car_dict[car]["mileage"] += distance
car_dict[car]["fuel"] -= fuel
print(f"{car} driven for {distance} kilometers. {fuel} liters of fuel consumed.")
if car_dict[car]["mileage"] > 100000:
print(f"Time to sell the {car}!")
del car_dict[car]
elif instruction == "Refuel":
fuel = int(command[2])
if car_dict[car]["fuel"] + fuel > 75:
fuel_needed = 75 - car_dict[car]["fuel"]
car_dict[car]["fuel"] += fuel_needed
print(f"{car} refueled with {fuel_needed} liters")
else:
car_dict[car]["fuel"] += fuel
print(f"{car} refueled with {fuel} liters")
elif instruction == "Revert":
kilometers = int(command[2])
car_dict[car]["mileage"] -= kilometers
if car_dict[car]["mileage"] < 10000:
car_dict[car]["mileage"] = 10000
else:
print(f"{car} mileage decreased by {kilometers} kilometers")
command = input()
sorted_car_dict = sorted(car_dict.items(), key=lambda x: (-x[1]["mileage"], x[0]))
for car in sorted_car_dict:
print(f"{car[0]} -> Mileage: {car[1]['mileage']} kms, Fuel in the tank: {car[1]['fuel']} lt.")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.