blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
3.06M
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
3.06M
|
---|---|---|---|---|---|---|
81c1f5f69ba843cc0b996778d4f3993fbf497564 | mayIlearnloopsbrother/Python | /chapters/chapter_7/ch7a.py | 422 | 3.953125 | 4 | #!/usr/bin/python3
#7-4 Pizza Toppings
info = "enter pizza toppings "
info += "\n'quit' to finish: "
topps = ""
while topps != 'quit':
topps = input(info)
if topps != 'quit':
print("\nAdding " + topps + " to your pizza\n")
print("\n")
#7-5 Movie Tickets
age = input("age? ")
age = int(age)
if age < 3:
print("ticket is free")
elif age < 12:
print("$10 for a ticket")
elif age > 12:
print("$15 for a ticket")
|
06ce2b33b58fde002588bf8bdf6b93d7d7f3e94d | mayIlearnloopsbrother/Python | /chapters/chapter_6/ch6c.py | 693 | 3.90625 | 4 | #!/usr/bin/python3
#6-8 Pets
petname = { 'chicken':'bob'}
petname2 = {'giffare': 'rob'}
petname3 = { 'dinosaur':'phineas'}
petname4 = {'dog': 'ben'}
pets = [petname, petname2, petname3, petname4]
for pet in pets:
print(pet)
print("\n")
#6-9 Favorite Places
favorite_places = {
'bob': ['italy', 'jtaly', 'ktaly'],
'rob': ['england', 'fngland'],
'dob': ['france']
}
for name, place in favorite_places.items():
print(name + " favorite places " + str(place))
print("\n")
#6-10 favorite Numbers
favorite_numbers = {
'chad': [5,2,3,4],
'dhad': [7,3],
'ehad': [0],
'ghad': [1,2,3]
}
for name, number in favorite_numbers.items():
print(name + " favorite numbers: " + str(number))
|
ecf4b82877c2884532f159e46e16be8a1c6e029b | benbovy/4learners_python | /notebooks/Day2_AM1/temp_module.py | 1,086 | 3.765625 | 4 | absolute_zero_in_celsius = -273.15
def fahrenheit_to_kelvin(temperature):
"""This function turns a temperature in Fahrenheit into a temperature in Kelvin"""
return (temperature - 32) * 5/9 - absolute_zero_in_celsius
def kelvin_to_celsius(temperature):
"""This function turns a temperature in Kelvin into a temperature in Celsius
This string is a doc string. It uses triple quotes to allow line breaks and contains information about your function that is carried around. You can access it by calling help(function) for any function that provides it. May editors will also show it if you hover over the function."""
return temperature + absolute_zero_in_celsius
def fahrenheit_to_celsius(temperature):
temp_in_kelvin = fahrenheit_to_kelvin(temperature)
return kelvin_to_celsius(temp_in_kelvin)
absolute_zero_in_fahrenheit = fahrenheit_to_celsius(absolute_zero_in_celsius)
# The magic variable __name__ contains the name of the module.
# If the file is run as a script it instead is set to "__main__"
# print(f"You have loaded the module {__name__}")
|
83a49d59eecbcceefc04ab923b85f939e97f33f1 | brennannicholson/ancient-greek-char-bert | /data_prep/greek_data_prep/split_data.py | 2,172 | 3.78125 | 4 | """Splits the sentence tokenized data into train, dev and test sets. This script shuffles the sentences. As a result the dataset created this way can't be used for next sentence prediction."""
from greek_data_prep.utils import write_to_file
import random as rn
import math
def get_data(filename):
with open(filename, "r") as f:
data = f.read().splitlines()
return data
def split_data(data, train_split, val_split, test_split):
assert train_split + val_split + test_split == 1.0
train = []
val = []
test = []
# we want to be able to reproduce this split
rn.seed(42)
rn.shuffle(data)
nb_of_texts = len(data)
total_len = sum([len(text) for text in data])
print("Total number of chars: " + str(total_len))
train_target_len = math.floor(total_len * train_split)
val_target_len = math.floor(total_len * (train_split + val_split))
current_len = 0
train_end = 0
val_end = 0
for i, text in enumerate(data):
current_len += len(text)
if current_len < train_target_len:
# keep updating the train end index until current len >= train_target_len
train_end = i
if current_len > val_target_len:
val_end = i
# now that we're finished, correct the train_end index
train_end += 1
break
train = data[0 : train_end + 1]
val = data[train_end + 1 : val_end + 1]
test = data[val_end + 1 :]
assert len(train) + len(val) + len(test) == len(data)
train_len = sum([len(text) for text in train])
val_len = sum([len(text) for text in val])
test_len = sum([len(text) for text in test])
print(f"Train length: {train_len}")
print(f"Val length: {val_len}")
print(f"Test length: {test_len}")
return train, val, test
def ninty_eight_one_one_spilt():
filename = "char_BERT_dataset.txt"
print("Splitting data...")
data = get_data(filename)
train, val, test = split_data(data, 0.98, 0.01, 0.01)
write_to_file("train.txt", train)
write_to_file("dev.txt", val)
write_to_file("test.txt", test)
if __name__ == "__main__":
ninty_eight_one_one_spilt()
|
867d4f98f69124194b73b20d3bb442093e9445c9 | meldhose/profile_values | /profile_values/profile_encoding.py | 3,829 | 3.921875 | 4 | """Analysing the encoding styles"""
import pandas as pd
def encoding_analysis(df_column):
"""
Checks the encoding style of the strings and
Args:
df_column (pandas DataFrame): Input pandas DataFrame
Returns:
dict (dict)
"""
dict_encoding_analysis = {}
contains_unusual_char = info_compatible_encoding(df_column)
if contains_unusual_char:
df1, df2 = info_list_unusual_chars(contains_unusual_char, df_column)
# Storing the return values in dictionary
dict_encoding_analysis['contains_unusual_chars'] = contains_unusual_char
dict_encoding_analysis['unusual_strings'] = df1
dict_encoding_analysis['strings_with_unusual_chars'] = df2
return dict_encoding_analysis
def info_compatible_encoding(df_column):
"""
Returns if the given data frame has strings that
contain unusual characters.
Args:
df_column (pandas DataFrame): Input pandas DataFrame
Returns:
contains_unusual_char (bool)
"""
col_title = df_column.columns.get_values()[0]
contains_unusual_char = False
data_frame = df_column
for each in data_frame.iterrows():
curr_attr = each[1][col_title]
try:
curr_attr.encode('ascii')
except ValueError:
contains_unusual_char = True
break
# if "\\x" in ascii(curr_attr):
# contains_unusual_char = True
return contains_unusual_char
def info_list_unusual_chars(contains_unusual_char, df_column):
"""
Returns 2 lists of strings with unusual characters and strings along
with indicated unusual characters.
Args:
contains_unusual_char(bool): Input bool
df_column (pandas DataFrame): Input pandas DataFrame
Returns:
df1,df2 (tuple of pandas DataFrames)
"""
data_frame = df_column
col_title = df_column.columns.get_values()[0]
non_ascii_str = []
list_str_chr = []
if contains_unusual_char:
for each in data_frame.iterrows():
non_ascii_char_string = ''
curr_attr = each[1][col_title]
try:
curr_attr.encode('ascii')
except:
for letter in curr_attr:
if ord(letter) < 32 or ord(letter) > 126:
non_ascii_str += [curr_attr]
if non_ascii_char_string == '':
non_ascii_char_string = letter
else:
non_ascii_char_string = non_ascii_char_string + \
' , ' + letter
list_str_chr.append([curr_attr, non_ascii_char_string])
df1 = print_unusual_str(non_ascii_str)
df2 = print_mapping_unusual(list_str_chr)
return df1, df2
def print_unusual_str(list_unusual_strings):
"""
Returns a DataFrame of strings that contain unusual characters.
Args:
list_unusual_strings (list): Input list
Returns:
unusualStringsDataFrame (pandas DataFrame)
"""
unusual_strings_data_frame = pd.DataFrame(list_unusual_strings,
columns=['String'])
return unusual_strings_data_frame
def print_mapping_unusual(list_unusual_mapping):
"""
Returns a DataFrame with 2 columns of strings and the
unusual characters in each.
Args:
list_unusual_mapping (list): Input list
Returns:
stringsWithUnusualChar (pandas DataFrame)
"""
strings_with_unusual_char = pd.DataFrame(list_unusual_mapping,
columns=['String', 'Unusual Character'])
return strings_with_unusual_char
|
743f5fd285c9045048bbf81c376c7e4d39d13fc2 | bcarlier75/python_bootcamp_42ai | /day01/ex00/recipe.py | 2,439 | 3.859375 | 4 | class Recipe:
def __init__(self, name, cooking_lvl, cooking_time, ingredients, description, recipe_type):
# Init name
if isinstance(name, str):
self.name = name
else:
print('Type error: name should be a string')
# Init cooking_lvl
if isinstance(cooking_lvl, int):
if cooking_lvl in range(1, 6):
self.cooking_lvl = cooking_lvl
else:
print('Value error: cooking_lvl should be between 1 and 5')
else:
print('Type error: cooking_lvl should be an integer')
# Init cooking_time
if isinstance(cooking_time, int):
if cooking_time > 0:
self.cooking_time = cooking_time
else:
print('Value error: cooking_time should be a positive integer')
else:
print('Type error: cooking_time should be an integer')
# Init ingredients
flag = 0
if isinstance(ingredients, list):
for elem in ingredients:
if not isinstance(elem, str):
flag = 1
if flag == 0:
self.ingredients = ingredients
elif flag == 1:
print('Value error: at least one element of ingredients is not a string')
else:
print('Type error: ingredients should be a list')
# Init description
if description is not None:
if isinstance(description, str):
self.description = description
else:
print('Type error: description should be a string')
# Init recipe_type
if isinstance(recipe_type, str):
if recipe_type in ["starter", "lunch", "dessert"]:
self.recipe_type = recipe_type
else:
print('Value error: recipe_type should be "starter", "lunch" or "dessert"')
else:
print('Type error: recipe_type should be a string')
def __str__(self):
"""Return the string to print with the recipe info"""
txt = ""
txt = f'This is the recipe for {self.name}.\n' \
f'Cooking level: {self.cooking_lvl}\n' \
f'Cooking time: {self.cooking_time}\n' \
f'Ingredients: {self.ingredients}\n' \
f'This recipe is for {self.recipe_type}.\n' \
f'{self.description}\n'
return txt
|
9c051053eec8ffb84bc16b987c2fefa664e38415 | bcarlier75/python_bootcamp_42ai | /day00/ex04/operations.py | 1,290 | 3.953125 | 4 | from sys import argv
if len(argv) == 1:
print(f'Usage: python operations.py\n'
f'Example:\n'
f'\tpython operations.py 10 3')
elif len(argv) == 3:
try:
my_sum = int(argv[1]) + int(argv[2])
my_diff = int(argv[1]) - int(argv[2])
my_mul = int(argv[1]) * int(argv[2])
if int(argv[2]) != 0:
my_div = int(argv[1]) / int(argv[2])
my_mod = int(argv[1]) % int(argv[2])
else:
my_div = 'ERROR (div by zero)'
my_mod = 'ERROR (modulo by zero)'
print(f'Sum:\t\t {my_sum}\n'
f'Difference:\t {my_diff}\n'
f'Product:\t {my_mul}\n'
f'Quotient:\t {my_div}\n'
f'Remainder:\t {my_mod}')
except ValueError as e:
print(f'InputError: only numbers\n'
f'Usage: python operations.py\n'
f'Example:\n'
f'\tpython operations.py 10 3')
elif len(argv) > 3:
print(f'InputError: too many arguments\n'
f'Usage: python operations.py\n'
f'Example:\n'
f'\tpython operations.py 10 3')
elif len(argv) == 2:
print(f'InputError: too few arguments\n'
f'Usage: python operations.py\n'
f'Example:\n'
f'\tpython operations.py 10 3') |
aad16f725e29145b9217e9d0fd70d675fca9fc64 | bcarlier75/python_bootcamp_42ai | /day01/ex02/vector.py | 3,787 | 3.53125 | 4 | class Vector:
def __init__(self, values, size, my_range):
flag = 0
if values:
if isinstance(values, list):
for elem in values:
if not isinstance(elem, float):
flag = 1
if flag == 0:
self.values = values
self.length = int(len(self.values))
else:
print('The list should only contain float values.')
else:
print('Init error: expect a list of float for parameter values')
elif size:
if isinstance(size, int):
self.values = [float(i) for i in range(0, size)]
self.length = len(self.values)
else:
print('Init error: expect an integer for parameter size.')
elif my_range:
if isinstance(my_range, tuple) and len(my_range) == 2:
for elem in my_range:
if not isinstance(elem, int):
flag = 1
if flag == 0:
self.values = [float(i) for i in range(my_range[0], my_range[1])]
self.length = len(self.values)
else:
print('The tuple should only contain int values.')
else:
print('Init error: expect a tuple with 2 integer for parameter my_range.')
else:
print('Init error: expect either a list of float, an integer or tuple with 2 integer.')
def __add__(self, vec_or_scalar):
if isinstance(vec_or_scalar, Vector) and self.length == vec_or_scalar.length:
for i in range(0, self.length):
self.values[i] = self.values[i] + vec_or_scalar.values[i]
elif isinstance(vec_or_scalar, float):
for i in range(0, self.length):
self.values[i] = self.values[i] + vec_or_scalar
else:
print(f'Value error: {vec_or_scalar} is not an instance of class Vector or a float'
'or vectors have different length.')
def __radd__(self, vec_or_scalar):
pass
def __sub__(self, vec_or_scalar):
if isinstance(vec_or_scalar, Vector) and self.length == vec_or_scalar.length:
for i in range(0, self.length):
self.values[i] = self.values[i] - vec_or_scalar.values[i]
elif isinstance(vec_or_scalar, float):
for i in range(0, self.length):
self.values[i] = self.values[i] - vec_or_scalar
else:
print(f'Value error: {vec_or_scalar} is not an instance of class Vector or a float '
'or vectors have different length.')
def __rsub__(self, vec_or_scalar):
pass
def __truediv__(self, scalar):
if isinstance(scalar, float):
for i in range(0, self.length):
self.values[i] = self.values[i] / scalar
else:
print('Value error: scalar should be a float')
def __rtruediv__(self, vec_or_scalar):
pass
def __mul__(self, vec_or_scalar):
if isinstance(vec_or_scalar, Vector) and self.length == vec_or_scalar.length:
for i in range(0, self.length):
self.values[i] = self.values[i] * vec_or_scalar.values[i]
elif isinstance(vec_or_scalar, float):
for i in range(0, self.length):
self.values[i] = self.values[i] * vec_or_scalar
else:
print(f'Value error: {vec_or_scalar} is not an instance of class Vector or a float '
'or vectors have different length.')
def __rmul__(self, vec_or_scalar):
pass
def __str__(self):
pass
def __repr__(self):
pass
|
e65ff801f6792b85f1878d3520b994f2e9dfa682 | Ernestbengula/python | /kim/Task3.py | 269 | 4.25 | 4 | # Given a number , check if its pos,Neg,Zero
num1 =float(input("Your Number"))
#Control structures -Making decision
#if, if else,elif
if num1>0:
print("positive")
elif num1==0 :
print("Zero")
elif num1<0:
print(" Negative")
else:
print("invalid") |
1bf95b285168d5e332de9f082227a89833161fde | Ernestbengula/python | /kim/Payroll.py | 448 | 3.859375 | 4 | # create a payroll
#Gross_Pay
salary =float(input("Enter salary"))
wa =float(input("Enter wa"))
ha=float(input("Enter ha"))
ta =float(input("Enter ta"))
Gross_Pay =(salary+wa+ha+ta)
print("Gross Pay ", Gross_Pay)
#Deduction
NSSF =float(input("Enter NSSF"))
Tax =float(input("Enter Tax"))
Deductions=(NSSF+Tax)
print("Deductions: ", Deductions)
#formula Net_Pay =Gross_Pay-Deduction
Net_pay =Gross_Pay-Deductions
print("Your net_pay",Net_pay)
|
3e021c8066e885499ca01ada8d90b3dd60b956d7 | Gholamrezadar/data-structures | /Quera_3_HanoiTowers.py | 437 | 3.78125 | 4 | From = []
Aux = []
To = []
def hanoi(n, A, B, C):
if n==1:
B.append(A.pop())
show_towers()
return
hanoi(n-1, A, C, B)
B.append(A.pop())
show_towers()
hanoi(n-1, C, B, A)
def show_towers():
print(sum(From), sum(Aux), sum(To))
def fill_bars():
for i in range(n,0,-1):
From.append(i)
n = int(input())
fill_bars()
show_towers()
hanoi(n, From, To, Aux)
|
319365deb464f4b690e1066ca52e69c9ce2622a9 | Evgen8906/homework_modul_14 | /calc.py | 1,199 | 3.796875 | 4 | """calc v5.0"""
def input_number():
num=input("Vvedite chislo: ")
if num == '':
return None
try:
num=float(num)
except ValueError:
num = num
return num
def input_oper():
oper=input("Operaciya('+','-','*','/','^','**'): ")
if oper == '':
oper = None
return oper
def calc_me(x=None,y=None,oper=None):
if x is None:
return "ERROR: send me Number1"
if y is None:
return "ERROR: send me Number1"
if (not isinstance(x, (int, float))) or (not isinstance(y, (int, float))):
return "ERROR: now it is does not supported"
if oper=='*':
return x*y
elif oper=='/':
if y==0:
return "ERROR: Divide by zero!"
else:
return x/y
elif oper=='+':
return x+y
elif oper=='-':
return x-y
elif oper == '^' or oper == '**':
return x ** y
else:
return "ERROR: Uknow operation"
def body():
num1 = input_number()
oper = input_oper()
num2 = input_number()
result = calc_me(num1,num2,oper)
print(result)
if __name__=='__main__':
body()
|
de3d8e0821036c101002cdfb771f190f4e1eb5b7 | Armadillan/TensorFlow2048 | /pg_implementation.py | 16,201 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Class for a visual interface for the 2048 environment using pygame.
Playable by both humans and robots.
"""
import time
import os
import pygame
import numpy as np
class Game:
"""
Class for a visual interface for the 2048 environment using pygame.
Playable by both humans and robots.
Use arrow keys or WASD to control.
r restarts the game
b turns bot on or off
"""
# Whether the game always stays square with
# background color on the sides, or fills the
# whole window.
# Setting this to False currently results in font weirdness when
# the window is much taller than it's wide. It's fixable but I
# haven't had time to fix it yet.
SQUARE = True
BACKGROUND_COLOR = ("#bbada0") # Background color (duh?)
LIGHT_TEXT_COLOR = pygame.Color("#f9f6f2") # Lighter color of digits
DARK_TEXT_COLOR = ("#776e65") # Darker color of digits
# Which tiles to use the lighter font for
# All other tiles will use the darker font
VALUES_WITH_DARK_TEXT = (2, 4)
# Dictionary mapping tiles to their color
TILE_COLOR = {
0: ("#cdc1b4"),
2: pygame.Color("#eee4da"),
4: pygame.Color("#eee1c9"),
8: pygame.Color("#f3b27a"),
16: pygame.Color("#f69664"),
32: pygame.Color("#f77c5f"),
64: pygame.Color("#f75f3b"),
128: pygame.Color("#edd073"),
256: pygame.Color("#edcc62"),
512: pygame.Color("#edc950"),
1024: pygame.Color("#edc53f"),
2048: pygame.Color("#edc22e"),
"BIG": pygame.Color("#3c3a33") # Tiles bigger than 2048
}
def __init__(self, env, bot=None, bot_delay=0.1):
"""
Iniitalizes the object.
Parameters
----------
env : PyEnvironment or TFPyEnvironment
An environment from env.py,
possibly wrapped using TFPyEnvironment
bot : TFPolicy or PyPolicy or TFPyPolicy or equivalent, optional
A robot to play the game.
Must have an action(TimeStep) method that
returns and action compatible with the environment.
The default is None.
bot_delay : float, optional
The delay in seconds between bot moves. The default is 0.1.
Returns
-------
None.
"""
# Adds text to caption if there is no bot
if bot is None:
self.caption_end = " " * 10 + "NO BOT ATTACHED"
else:
self.caption_end = ""
self.env = env
self.bot = bot
self.bot_delay = bot_delay
# Initial size for the window
self.w = 600
self.h = 600
# Initializes pygame
pygame.init()
# Initializes fonts
self.initialize_fonts()
def initialize_fonts(self):
"""
Initializes fonts based on current screen size
Must be called every time screen size changes
"""
# Using the original font from 2048
self.tile_font_5 = pygame.font.Font(
os.path.join("assets", "ClearSans-Bold.ttf"),
int(self.h * 6/29 * 7/12)
)
self.tile_font_4 = pygame.font.Font(
os.path.join("assets", "ClearSans-Bold.ttf"),
int(self.h * 6/29 * 6/12)
)
self.tile_font_3 = pygame.font.Font(
os.path.join("assets", "ClearSans-Bold.ttf"),
int(self.h * 6/29 * 5/12)
)
self.tile_font_2 = pygame.font.Font(
os.path.join("assets", "ClearSans-Bold.ttf"),
int(self.h * 6/29 * 4/12)
)
self.tile_font_1 = pygame.font.Font(
os.path.join("assets", "ClearSans-Bold.ttf"),
int(self.h * 6/29 * 3/12)
)
# If that is not possible for some reason,
# Arial can be used:
# self.tile_font_5 = pygame.font.SysFont(
# "Arial", int(self.h * 5/29)
# )
# self.tile_font_4 = pygame.font.SysFont(
# "Arial", int(self.h * 4/29)
# )
# self.tile_font_3 = pygame.font.SysFont(
# "Arial", int(self.h * 3/29)
# )
# self.tile_font_2 = pygame.font.SysFont(
# "Arial", int(self.h * 2/29)
# )
# self.tile_font_1 = pygame.font.SysFont(
# "Arial", int(self.h * 1/29)
# )
self.gameover_font_1 = pygame.font.SysFont(
"Arial", int(self.h * (1/10)), bold=True
)
self.gameover_size_1 = self.gameover_font_1.size("GAME OVER")
self.gameover_text_1 = self.gameover_font_1.render(
"GAME OVER", True, (20,20,20)
)
self.gameover_font_2 = pygame.font.SysFont(
"Arial", int(self.h * (1/20),), bold=True
)
self.gameover_size_2 = self.gameover_font_2.size(
"Press \"r\" to restart"
)
self.gameover_text_2 = self.gameover_font_2.render(
"Press \"r\" to restart", True, (20,20,20)
)
def tile(self, x, y, n):
"""
Used to render tiles
Parameters
----------
x : int
x coordinate of tile.
y : int
y coordinate of tile.
n : int
Value of tile.
Returns
-------
pygame.Rect
Rectangle making up the tiles background.
pygame.Surface
The text (number) on the tile.
tuple
(x, y) coordinates of the text on the tile.
"""
# Coordinates of tile
rect_x = (x+1) * self.w/29 + x * self.w * (6/29)
rect_y = (y+1) * self.h/29 + y * self.h * (6/29)
# Rectangle object
rect = pygame.Rect(
rect_x, rect_y, self.w * (6/29), self.h * (6/29))
# Does not render text if the tile is 0
if not n:
text_render = pygame.Surface((0,0))
text_x = 0
text_y = 0
else:
# Get string from int and it's length
text = str(n)
l = len(text)
# Chooses color for text
if n in self.VALUES_WITH_DARK_TEXT:
text_color = self.DARK_TEXT_COLOR
else:
text_color = self.LIGHT_TEXT_COLOR
# Chooses font size based on length of text
if l < 3:
font = self.tile_font_5
elif l == 3:
font = self.tile_font_4
elif l == 4:
font = self.tile_font_3
elif l < 7:
font = self.tile_font_2
else:
font = self.tile_font_1
# Renders font
text_render = font.render(text, True, text_color)
# Gets size of text
size = font.size(text)
# Calculates text coordinates
text_x = (x+1) * self.w/29 \
+ (x+0.5) * self.w * (6/29) - size[0] / 2
text_y = (y+1) * self.h/29 \
+ (y+0.5) * self.h * (6/29) - size[1] / 2
return rect, text_render, (text_x, text_y)
def check_action(self, action):
"""
Checks whether action would change the state of the game
Parameters
----------
action : int
The action to to check. int in (0,1,2,3).
Returns
-------
bool
"""
modifiers = {
0: (0, -1),
1: (+1, 0),
2: (0, +1),
3: (-1, 0)
}
x_mod, y_mod = modifiers[action]
try:
board_array = self.env.current_time_step().observation.numpy()[0]
except AttributeError:
board_array = self.env.current_time_step().observation
for x in range(4):
for y in range(4):
try:
if board_array[y][x] != 0 and \
((board_array[y+y_mod][x+x_mod] == 0) or \
(board_array[y][x] == board_array[y+y_mod][x+x_mod])):
return True
except IndexError:
pass
return False
def main(self):
"""
Starts the game.
This is the main game loop.
"""
# Initial status
playing = True
gameover = False
bot_active = False
score = 0
moves = 0
# Gets initial game state
ts = self.env.reset()
# This is for compatibility with different types of environments
try:
# TF environments
board_array = ts.observation.numpy()[0]
except AttributeError:
# Py environments
board_array = ts.observation
# Environments with flat observations
board_array = np.reshape(board_array, (4,4))
# Keeps a counter of score and moves made in the caption
pygame.display.set_caption(
"2048" + " " * 10 + "Score: 0 Moves: 0" + self.caption_end
)
# Initializes window and a drawing surface
win = pygame.display.set_mode((self.w, self.h), pygame.RESIZABLE)
surface = win.copy()
# Main game loop
while playing:
moved = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
playing = False
break
if event.type == pygame.VIDEORESIZE:
# Handles window resizing
self.w, self.h = win.get_size()
# Sets width and height equal if SQUARE is True
if self.SQUARE:
if self.w > self.h:
self.w = self.h
else:
self.h = self.w
# Makes new drawing surface
surface = win.copy()
# Re-initalizes fonts based on new window size
self.initialize_fonts()
if event.type == pygame.KEYDOWN:
# Handles user input
if event.key == pygame.K_r:
#Restarts the game
ts = self.env.reset()
score = 0
moves = 0
moved = True
gameover = False
surface.fill(self.BACKGROUND_COLOR)
elif event.key == pygame.K_b:
# Turns bot off and on
if bot_active:
bot_active = False
pygame.display.set_caption(
"2048" + " " * 10 + f"Score: {int(score)}"
+ f" Moves: {moves}"
)
elif self.bot is not None:
bot_active = True
elif not gameover:
# Handles human player moves
action_keymap = {
pygame.K_UP: 0, pygame.K_w: 0,
pygame.K_RIGHT: 1, pygame.K_d: 1,
pygame.K_DOWN : 2, pygame.K_s: 2,
pygame.K_LEFT: 3, pygame.K_a: 3,
}
if event.key in action_keymap:
action = action_keymap[event.key]
if self.check_action(action):
ts = self.env.step(action)
moved = True
moves += 1
# Breaks loop if game is over
if not playing:
break
# Updates game state if a move has been made by the player
if moved:
try:
board_array = ts.observation.numpy()[0]
score += ts.reward.numpy()
except AttributeError:
board_array = ts.observation
score += ts.reward
board_array = np.reshape(board_array, (4,4))
# Handles bot movement
if not gameover:
if bot_active:
old_board = board_array.copy()
# Gets action from bot
actionstep = self.bot.action(ts)
action = actionstep.action
ts = self.env.step(action)
moves += 1
# Updates game state
try:
board_array = ts.observation.numpy()[0]
score += ts.reward.numpy()
except AttributeError:
board_array = ts.observation
score += ts.reward
board_array = np.reshape(board_array, (4,4))
# Checks if the board has changed
if not np.array_equal(old_board, board_array):
moved = True
# Waits before bot makes another move
time.sleep(self.bot_delay)
# Adds "- Bot" to caption
pygame.display.set_caption(
"2048 - Bot" + " " * 10 + f"Score: {int(score)}"
+ f" Moves: {moves}"
)
else:
# Updates caption without "- Bot"
pygame.display.set_caption(
"2048" + " " * 10 + f"Score: {int(score)}"
+ f" Moves: {moves}"+ self.caption_end
)
# Checks if the game is over
if ts.is_last():
gameover = True
# Draws all the graphics:
surface.fill(self.BACKGROUND_COLOR)
# Draws every tile
for x in range(4):
for y in range(4):
# Gets the tile "data"
n = board_array[y][x]
rect, text, text_coords = self.tile(x, y, n)
# Gets the color of the tile
try:
tile_color = self.TILE_COLOR[n]
except KeyError:
tile_color = self.TILE_COLOR["BIG"]
# Draws the background
pygame.draw.rect(
surface=surface,
color=tile_color,
rect=rect,
border_radius=int((self.w+self.h)/2 * 1/150)
)
# Blits the text surface to the drawing surface
surface.blit(text, text_coords)
# Displays "gameover screen" if game is over
if gameover:
x_1 = self.w / 2 - self.gameover_size_1[0] / 2
y_1 = self.h / 2 - self.h * 6/80
x_2 = self.w / 2 - self.gameover_size_2[0] / 2
y_2 = self.h / 2 + self.h * 1/30
surface.blit(self.gameover_text_1, (x_1, y_1))
surface.blit(self.gameover_text_2, (x_2, y_2))
# Fill window with background color
win.fill(self.BACKGROUND_COLOR)
# Blits drawing surface to the middle of the window
w, h = win.get_size()
if w > h:
win.blit(surface, ((win.get_width()-self.w)/2,0))
else:
win.blit(surface, (0, (win.get_height()-self.h)/2))
# Updates display
pygame.display.update()
# Quits pygame outside of the main game loop, if the game is over
pygame.quit()
if __name__ == "__main__":
# Plays the game without a bot attached :)
# from env import PyEnv2048
from env import PyEnv2048NoBadActions
# Creates Game object, passing an environment to the constructor
# game = Game(PyEnv2048())
game = Game(PyEnv2048NoBadActions())
# Starts the interface
game.main()
|
ff55c37cedb184c2d2c8399ca9717e775bd34e9c | txkxyx/atcoder | /practice/abc081a.py | 471 | 3.8125 | 4 | import sys
# 0 と 1 のみから成る 3 桁の番号 s が与えられます。1 が何個含まれるかを求めてください。
class ABC081():
def __init__(self, s):
self.s = s
def checkCount(self):
count = 0
for c in s:
if c == '1':
count += 1
return count
if __name__ == '__main__':
args = sys.argv
s = args[1]
abc081 = ABC081(s)
count = abc081.checkCount()
print(count) |
e326bc60c7ca49876b9948df9dc5758455a9ce64 | JianxiangWang/LeetCode | /70 Climbing Stairs/solution.py | 525 | 3.671875 | 4 | # encoding: utf-8
# dp[i] = dp[i-1] + dp[i-2]: 跨到第i台阶 == 从i-1跨过来的次数 + 从i-2跨过来的次数
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0: return 0
if n == 1: return 1
dp = [None] * n
dp[0] = 1
dp[1] = 2
for idx in range(2, n):
dp[idx] = dp[idx - 1] + dp[idx - 2]
return dp[n-1]
if __name__ == '__main__':
print Solution().climbStairs(3) |
42e46dadf6d6e53f7c42146761113cf4e6e3f848 | JianxiangWang/LeetCode | /129 Sum Root to Leaf Numbers/solution.py | 921 | 3.734375 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(node, s, res):
if node is None:
return
s += str(node.val)
if node.left is None and node.right is None:
res.append(int(s))
dfs(node.left, s, res)
dfs(node.right, s, res)
res = []
dfs(root, "", res)
return sum(res)
if __name__ == '__main__':
root = TreeNode(0)
a = TreeNode(1)
b = TreeNode(3)
c = TreeNode(4)
d = TreeNode(5)
e = TreeNode(6)
root.left = a
root.right = b
# a.left = c
# a.right = d
# c.left = e
print Solution().sumNumbers(root)
|
8eee6e6b52fd476f0de22c3e59cb37317597aa45 | JianxiangWang/LeetCode | /Intersection of Two Arrays II/solution.py | 842 | 3.71875 | 4 |
def intersect(nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
dict_num1_to_count = {}
dict_num2_to_count = {}
for x in nums1:
if x not in dict_num1_to_count:
dict_num1_to_count[x] = 0
dict_num1_to_count[x] += 1
for x in nums2:
if x not in dict_num2_to_count:
dict_num2_to_count[x] = 0
dict_num2_to_count[x] += 1
t = []
for common_num in dict_num1_to_count:
if common_num in dict_num2_to_count:
t.extend([common_num] * min(dict_num1_to_count[common_num], dict_num2_to_count[common_num]))
return t
if __name__ == '__main__':
nums1 = [1, 1]
nums2 = [1]
print intersect(nums1, nums2) |
9d12f4df1ade28b51f2f562ff900fbb75f808d11 | JianxiangWang/LeetCode | /203 Remove Linked List Elements/solution.py | 807 | 3.53125 | 4 | #encoding: utf-8
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
point = head
while point:
if point.next != None and point.next.val == val:
p = point
point = point.next
while point.next != None and point.next.val == val:
point = point.next
point = point.next
p.next = point
else:
point = point.next
if head != None and head.val == val:
head = head.next
return head
|
d2c1cd0d01c93d0c59ba25541031a78ce7e0bbe9 | JianxiangWang/LeetCode | /130 Surrounded Regions/solution.py | 2,024 | 3.578125 | 4 | # encoding: utf-8
class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if len(board) <= 0:
return
m, n = len(board), len(board[0])
visited = [[False]*n for x in range(m)]
for i in range(m):
for j in range(n):
if board[i][j] == 'O' and not visited[i][j]:
surrounded, union_filed = self.bfs(board, i, j, m, n, visited)
if surrounded:
for x, y in union_filed:
board[x][y] = 'X'
# flood fill, 使用bfs找到union field
# 判断他是不是被包围, 如果是,返回被包含区域
def bfs(self, board, x, y, m, n, visited):
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
union_filed = []
surrounded = True
# 放进queue之前,先visit
visited[x][y] = True
for i, j in [(x + d_i, y + d_j) for d_i, d_j in directions]:
#
if i < 0 or i >= m or j < 0 or j >= n:
surrounded = False
continue
union_filed.append((x, y))
queue = [(x, y)]
while queue:
i_, j_ = queue.pop(0)
# 将相邻节点放入queue
for i, j in [(i_ + d_i, j_ + d_j) for d_i, d_j in directions]:
#
if i < 0 or i >= m or j < 0 or j >= n:
surrounded = False
continue
if not visited[i][j] and board[i][j] == "O":
visited[i][j] = True
union_filed.append((i, j))
queue.append((i, j))
return surrounded, union_filed
if __name__ == '__main__':
board = [
["X", "X", "X", "O"],
["X", "O", "O", "X"],
["X", "O", "X", "O"],
["X", "X", "X", "X"]
]
Solution().solve(board)
print board |
9181573ba65b9aca1551f88c49f69650a2af4ad7 | JianxiangWang/LeetCode | /47 Permutations II/solution.py | 737 | 3.625 | 4 |
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def dfs(seq, ans, res):
seq = sorted(seq)
prev_x = None
for idx, x in enumerate(seq):
if x == prev_x:
continue
prev_x = x
ans_ = ans + [x]
tmp = seq[:idx] + seq[idx + 1:]
if tmp == []:
res.append(ans_)
dfs(tmp, ans_, res)
res = []
dfs(nums, [], res)
return res
# return list(map(list, set(res)))
if __name__ == '__main__':
print Solution().permuteUnique([3, 3, 0, 3]) |
ab061ca7ac9f33f8fd5f2e7c9e3c1530e59b2024 | alvdena/SWMM-EPANET_User_Interface | /src/core/inputfile.py | 15,166 | 3.515625 | 4 | import inspect
import traceback
from enum import Enum
class InputFile(object):
"""Input File Reader and Writer"""
def __init__(self):
self.file_name = ""
self.sections = []
self.add_sections_from_attributes()
def get_text(self):
section_text_list = []
try:
for section in self.sections:
try: # Make sure each section text ends with one newline, two newlines after join below.
section_text_list.append(section.get_text().rstrip('\n') + '\n')
except Exception as e1:
section_text_list.append(str(e1) + '\n' + str(traceback.print_exc()))
return '\n'.join(section_text_list)
except Exception as e2:
return(str(e2) + '\n' + str(traceback.print_exc()))
def set_text(self, new_text):
self.set_from_text_lines(new_text.splitlines())
def read_file(self, file_name):
try:
with open(file_name, 'r') as inp_reader:
self.set_from_text_lines(iter(inp_reader))
self.file_name = file_name
except Exception as e:
print("Error reading {0}: {1}\n{2}".format(file_name, str(e), str(traceback.print_exc())))
def write_file(self, file_name):
if file_name:
with open(file_name, 'w') as writer:
writer.writelines(self.get_text())
self.file_name = file_name
def set_from_text_lines(self, lines_iterator):
"""Read as a project file from lines of text.
Args:
lines_iterator (iterator): Produces lines of text formatted as input file.
"""
self.__init__()
self.sections = []
section_index = 1
section_name = ""
section_whole = ""
for line in lines_iterator:
if line.startswith('['):
if section_name:
self.add_section(section_name, section_whole, section_index)
section_index += 1
section_name = line.rstrip()
section_whole = line
else:
section_whole += line
if section_name:
self.add_section(section_name, section_whole, section_index)
section_index += 1
self.add_sections_from_attributes()
def add_sections_from_attributes(self):
"""Add the sections that are attributes of the class to the list of sections."""
for attr_value in vars(self).itervalues():
if isinstance(attr_value, Section) and attr_value not in self.sections:
self.sections.append(attr_value)
def add_section(self, section_name, section_text, section_index):
attr_name = InputFile.printable_to_attribute(section_name)
try:
section_attr = self.__getattribute__(attr_name)
except:
section_attr = None
new_section = self.find_section(section_name)
if section_attr is None: # if there is not a class associated with this name, read it as generic Section
if new_section is None:
new_section = Section()
new_section.name = section_name
new_section.index = section_index
new_section.value = section_text
new_section.value_original = section_text
else:
section_class = type(section_attr)
if section_class is list:
if new_section is None:
new_section = Section()
new_section.name = section_name
new_section.index = section_index
new_section.value_original = section_text
section_list = []
else:
section_list = new_section.value
list_class = section_attr[0]
for row in section_text.splitlines()[1:]: # process each row after the one with the section name
if row.startswith(';'): # if row starts with semicolon, the whole row is a comment
comment = Section()
comment.name = "Comment"
comment.index = section_index
comment.value = row
comment.value_original = row
section_list.append(comment)
else:
try:
if row.strip():
make_one = list_class()
make_one.set_text(row)
section_list.append(make_one)
except Exception as e:
print("Could not create object from row: " + row + "\n" + str(e))
new_section.value = section_list
else:
if new_section is None:
new_section = section_class()
if hasattr(new_section, "index"):
new_section.index = section_index
if hasattr(new_section, "value"):
new_section.value = section_text
if hasattr(new_section, "value_original"):
new_section.value_original = section_text
try:
new_section.set_text(section_text)
except Exception as e:
print("Could not call set_text on " + attr_name + " (" + section_name + "):\n" + str(e))
if new_section is not None and new_section not in self.sections:
self.sections.append(new_section)
if section_attr is not None:
self.__setattr__(attr_name, new_section)
def find_section(self, section_title):
""" Find an element of self.sections, ignoring square brackets and capitalization.
Args:
section_title (str): Title of section to find.
"""
compare_title = InputFile.printable_to_attribute(section_title)
for section in self.sections:
if hasattr(section, "SECTION_NAME"):
this_section_name = section.SECTION_NAME
else:
this_section_name = section.name
if InputFile.printable_to_attribute(str(this_section_name)) == compare_title:
return section
return None
@staticmethod
def printable_to_attribute(name):
"""@param name is as it appears in text input file, return it formatted as a class attribute name"""
return name.lower().replace(' ', '_').replace('[', '').replace(']', '')
class Section(object):
"""Any section or sub-section or value in an input file"""
field_format = " {:19}\t{}"
def __init__(self):
self.name = "Unnamed"
"""Name of the item"""
if hasattr(self, "SECTION_NAME"):
self.name = self.SECTION_NAME
self.value = ""
"""Current value of the item as it appears in an InputFile"""
self.value_original = None
"""Original value of the item as read from an InputFile during this session"""
self.index = -1
"""Index indicating the order in which this item was read
(used for keeping items in the same order when written)"""
self.comment = ""
"""A user-specified header and/or comment about the section"""
def __str__(self):
"""Override default method to return string representation"""
return self.get_text()
def get_text(self):
"""Contents of this section formatted for writing to file"""
txt = self._get_text_field_dict()
if txt:
return txt
if isinstance(self.value, basestring) and len(self.value) > 0:
return self.value
elif isinstance(self.value, (list, tuple)):
text_list = [self.name]
for item in self.value:
text_list.append(str(item))
return '\n'.join(text_list)
elif self.value is None:
return ''
else:
return str(self.value)
def _get_text_field_dict(self):
""" Get string representation of attributes represented in field_dict, if any.
Private method intended for use by subclasses """
if hasattr(self, "field_dict") and self.field_dict:
text_list = []
if self.name and self.name.startswith('['):
text_list.append(self.name)
if self.comment:
text_list.append(self.comment)
for label, attr_name in self.field_dict.items():
attr_line = self._get_attr_line(label, attr_name)
if attr_line:
text_list.append(attr_line)
if text_list:
return '\n'.join(text_list)
return '' # Did not find field values from field_dict to return
def _get_attr_line(self, label, attr_name):
if label and attr_name and hasattr(self, attr_name):
attr_value = getattr(self, attr_name)
if isinstance(attr_value, Enum):
attr_value = attr_value.name.replace('_', '-')
if isinstance(attr_value, bool):
if attr_value:
attr_value = "YES"
else:
attr_value = "NO"
if isinstance(attr_value, list):
attr_value = ' '.join(attr_value)
if attr_value or attr_value == 0:
return (self.field_format.format(label, attr_value))
else:
return None
def set_text(self, new_text):
"""Read properties from text.
Args:
new_text (str): Text to parse into properties.
"""
self.__init__() # Reset all values to defaults
self.value = new_text
for line in new_text.splitlines():
self.set_text_line(line)
def set_text_line(self, line):
"""Set part of this section from one line of text.
Args:
line (str): One line of text formatted as input file.
"""
# first split out any comment after a semicolon
comment_split = str.split(line, ';', 1)
if len(comment_split) == 2:
line = comment_split[0]
this_comment = ';' + comment_split[1]
if self.comment:
if this_comment in self.comment:
this_comment = '' # Already have this comment, don't add it again
else:
self.comment += '\n' # Separate from existing comment with newline
self.comment += this_comment
if not line.startswith('[') and line.strip():
# Set fields from field_dict if this section has one
attr_name = ""
attr_value = ""
tried_set = False
if hasattr(self, "field_dict") and self.field_dict:
(attr_name, attr_value) = self.get_field_dict_value(line)
else: # This section does not have a field_dict, try to set its fields anyway
line_list = line.split()
if len(line_list) > 1:
if len(line_list) == 2:
test_attr_name = line_list[0].lower()
if hasattr(self, test_attr_name):
attr_name = test_attr_name
attr_value = line_list[1]
else:
for value_start in (1, 2):
for connector in ('', '_'):
test_attr_name = connector.join(line_list[:value_start]).lower()
if hasattr(self, test_attr_name):
attr_name = test_attr_name
attr_value = ' '.join(line_list[value_start:])
break
if attr_name:
try:
tried_set = True
self.setattr_keep_type(attr_name, attr_value)
except:
print("Section.text could not set " + attr_name)
if not tried_set:
print("Section.text skipped: " + line)
def get_field_dict_value(self, line):
"""Search self.field_dict for attribute matching start of line.
Args:
line (str): One line of text formatted as input file, with field name followed by field value.
Returns:
Attribute name from field_dict and new attribute value from line as a tuple:
(attr_name, attr_value) or (None, None) if not found.
"""
if hasattr(self, "field_dict") and self.field_dict:
lower_line = line.lower().strip()
for dict_tuple in self.field_dict.items():
key = dict_tuple[0]
# if this line starts with this key followed by a space or tab
if lower_line.startswith(key.lower()) and lower_line[len(key)] in (' ', '\t'):
test_attr_name = dict_tuple[1]
if hasattr(self, test_attr_name):
# return attribute name and value to be assigned
return(test_attr_name, line[len(key) + 1:].strip())
return(None, None)
def setattr_keep_type(self, attr_name, attr_value):
"""Set attribute attr_name = attr_value.
If existing value of attr_name is int, float, bool, or Enum,
try to remove spaces and convert attr_value to the same type before setting.
Args:
attr_name (str): Name of attribute of self to set.
attr_value: New value to assign to attr_name.
"""
try:
old_value = getattr(self, attr_name, "")
if type(old_value) == int:
if isinstance(attr_value, str):
attr_value = attr_value.replace(' ', '')
setattr(self, attr_name, int(attr_value))
elif type(old_value) == float:
if isinstance(attr_value, str):
attr_value = attr_value.replace(' ', '')
setattr(self, attr_name, float(attr_value))
elif isinstance(old_value, Enum):
if not isinstance(attr_value, Enum):
try:
attr_value = type(old_value)[attr_value.replace('-', '_')]
except KeyError:
attr_value = type(old_value)[attr_value.upper().replace('-', '_')]
setattr(self, attr_name, attr_value)
elif type(old_value) == bool:
if not isinstance(attr_value, bool):
attr_value = str(attr_value).upper() not in ("NO", "FALSE")
setattr(self, attr_name, attr_value)
else:
setattr(self, attr_name, attr_value)
except Exception as e:
print("Exception setting {}: {}".format(attr_name, str(e)))
setattr(self, attr_name, attr_value)
|
5930c2407c62aeee242a0a1340e49d2372d27d0c | Vishnushetty14/assignments | /swapping_of_two_numbers.py | 109 | 3.875 | 4 | a=float(input("enter a value"))
b=float(input("enter b value"))
temp=a
a=b
b=temp
print("a=",a)
print("b=",b) |
c06b507656eb5fa8e0471507532ef4de8a3167d9 | easyra/Sprint-Challenge--Data-Structures-Python | /names/names.py | 1,548 | 3.546875 | 4 | import time
import sys
sys.path.append('../search')
#from binary_search_tree import BinarySearchTree
start_time = time.time()
class BinarySearchTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, value):
direction = "right" if value > self.value else 'left'
if getattr(self, direction) is None:
setattr(self, direction, BinarySearchTree(value))
return
else:
self = getattr(self,direction)
self.insert(value)
pass
def contains(self, target):
if target == self.value:
return True
if target < self.value:
if self.left is None:
return False
else:
self = self.left
elif target > self.value:
if self.right is None:
return False
else:
self = self.right
return self.contains(target)
def get_max(self):
while self.right is not None:
self = self.right
return self.value
pass
f = open('names_1.txt', 'r')
names_1 = f.read().split("\n") # List containing 10000 names
bst_1 = BinarySearchTree(names_1[0])
for name in names_1[1:]:
bst_1.insert(name)
f.close()
f = open('names_2.txt', 'r')
names_2 = f.read().split("\n") # List containing 10000 names
f.close()
duplicates = []
for name in names_2:
if bst_1.contains(name):
duplicates.append(name)
end_time = time.time()
print (f"{len(duplicates)} duplicates:\n\n{', '.join(duplicates)}\n\n")
print (f"runtime: {end_time - start_time} seconds")
|
400be22da09455720e76805e79cda13b8e025a83 | PinkLego/MyPythonProjects | /InventYourOwnGamesWithPython/All projects/packages.py | 356 | 3.90625 | 4 | import random # generates random values
#members = ['Mary', 'John', 'Bob', 'Mosh']
#leader = random.choice(members)
#print(leader)
#for i in range(3):
#print(random.randint(10, 20))
class Dice:
def roll(self):
first = random.randint(1, 6)
second = random.randint(1, 6)
return first, second
dice = Dice()
print(dice.roll) |
2a048d0c0cd4709d4b9b856b03190105f8006cee | PinkLego/MyPythonProjects | /InventYourOwnGamesWithPython/All projects/Loops!!.py | 275 | 3.875 | 4 | Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> for x in range(0, 5):
print('hello')
hello
hello
hello
hello
hello
>>> print(list(range(10, 20)))
|
df441f7479925dbf77b009cd401a692876965abb | PinkLego/MyPythonProjects | /InventYourOwnGamesWithPython/All projects/Varibles.py | 429 | 3.890625 | 4 | print("Create your character")
name = input("What is you character called?")
age = input("How old is your character?")
strengths = input("What is your character's strenghts?")
weakness = input("What are your character's weaknesses?")
print("Your character's name is", name)
print("Your character is", age, "years old")
print("Strenghts:", strenghts)
print("Weaknesses", weaknesses)
print(name, "says, 'Thanks for creating me!'") |
b124c829284bc4aea81d34cfa8d487eadb6f180e | PinkLego/MyPythonProjects | /InventYourOwnGamesWithPython/All projects/Mass Defense.py | 1,373 | 3.734375 | 4 | #
#
#
#
import turtle
import random
wn = turtle.Screen()
wn.setup(1200, 800)
wn.bgcolor("black")
wn.title("Mass Defense Game")
class Sprite():
pen = turtle.Turtle()
pen.hideturtle()
pen.speed(0)
pen.penup()
def __init__(self, x, y, shape, color):
self.x = x
self.y = y
self.shape = shape
self.color = color
self.dx = 0
self.speed = 0
def render(self):
Sprite.pen.goto(self.x, self.y)
Sprite.pen.shape(self.shape)
Sprite.pen.color(self.color)
Sprite.pen.stamp()
def move(self):
self.x += self.dx
sprites = []
#Defenders
for _ in range(10):
x = random.randint(-500, -300)
y = random.randint(-300, 300)
sprites.append(Sprite(x, y, "circle", "blue"))
# Attackers
for _ in range(10):
x = random.randint(300, 500)
y = random.randint(-300, 300)
sprites.append(Sprite(x, y, "circle", "red"))
sprites[-1].heading = 180 #Left
sprites[-1].dx = -0.2
# Weapons
for _ in range(10):
x = -1000
y = -1000
sprites.append(Sprite(x, y, "circle", "light blue"))
# Main game loop
while True:
# Move
for sprite in sprites:
sprite.move()
#Render
for sprite in sprites:
sprite.render()
# Update the screen
wn.update()
# Clear the screen
Sprite.pen.clear()
wn.mainloop()
|
7737b93b5c93234ab9a28e8a3b6d3b23f740dd76 | abhiranjan-singh/DevRepo | /calculater.py | 383 | 4.1875 | 4 | def mutiply(x, y):
return x*y
print(mutiply(int(input("enter the 1st number ")),int(input("Enter the second number "))))
#m = int(input("enter the 1stnumber "))
#n = int(input("enter the second number "))
# print(mutiply(input("enter the 1st number"),input("enter the second number")))
#print(mutiply(m, n))
#print('m' + '*' + 'n' + '=' + mutiply(m, n))print(mutiply(m, n))
|
dce0cf3caa43263a93aba2b4cd1de6e10e2efb03 | rexos/python_data_mining | /fibonacci.py | 147 | 3.9375 | 4 | def fibonacci(n):
ary = [1,1]
for i in range(2,n):
ary.append(ary[i-1]+ary[i-2])
return ary[n-1]
print fibonacci(10)
|
356f25da7e3e31a653955de095d7a12392d3b331 | marclacerna/ormuco | /question_b.py | 560 | 3.796875 | 4 | class CheckInputs:
def __init__(self, input1, input2):
try:
self.input1 = float(input1)
self.input2 = float(input2)
except ValueError:
print('Both inputs must be a number')
def compare(self):
if self.input1 > self.input2:
return '{} greater than {}'.format(self.input1, self.input2)
elif self.input1 == self.input2:
return '{} is equal {}'.format(self.input1, self.input2)
else:
return '{} less than {}'.format(self.input1, self.input2) |
67ca1707453a15e4c6ea0983a8e11ee83b7c1b97 | agvaibhav/Dynamic-Programming | /rod_cutting_to_max_profit.py | 1,646 | 3.515625 | 4 | # rod cutting
# we are given profit of each length of rod
# we have to max profit
# recursion method
'''
def maxProfit(arr, totalLen):
if totalLen == 0:
return 0
best = 0
for len in range(1, totalLen+1):
netProfit = arr[len] + maxProfit(arr, totalLen-len)
best = max(best, netProfit)
return best
if __name__=='__main__':
totalLen = int(input())
priceOfEachLen = list(map(int,input().split()))
priceOfEachLen.insert(0,0)
print(maxProfit(priceOfEachLen, totalLen))
'''
# memoization method
'''
def maxProfit(arr, totalLen):
if totalLen == 0:
return 0
if memo[totalLen] != -1:
return memo[totalLen]
best = 0
for len in range(1, totalLen+1):
netProfit = arr[len] + maxProfit(arr, totalLen-len)
best = max(best, netProfit)
memo[totalLen] = best
return best
if __name__=='__main__':
totalLen = int(input())
priceOfEachLen = list(map(int,input().split()))
priceOfEachLen.insert(0,0)
memo = [-1]*(totalLen+1)
print(maxProfit(priceOfEachLen, totalLen))
'''
# bottom up (dp) method
def maxProfit(arr, totalLen):
for len in range(1, totalLen+1):
best = 0
for cut in range(1, len+1):
best = max(best, arr[cut] + dp[len-cut])
dp[len] = best
return dp[totalLen]
if __name__=='__main__':
totalLen = int(input())
priceOfEachLen = list(map(int,input().split()))
priceOfEachLen.insert(0,0)
dp = [0]*(totalLen+1)
print(maxProfit(priceOfEachLen, totalLen))
|
ea6180b91169567ad23ba823d65587a2151c76d2 | agvaibhav/Dynamic-Programming | /fibonacci_memoized.py | 373 | 4.03125 | 4 | def fib(n,lookup):
if n==0 or n==1:
lookup[n]=n
if lookup[n] is None:
lookup[n]=fib(n-1,lookup)+fib(n-2,lookup)
return lookup[n]
def main(n):
lookup=[None]*(n+1)
print("fibonacci number is:",fib(n,lookup))
if __name__=="__main__":
n=int(input("write the number you want to calculate fibonacci for:"))
main(n)
|
817ff7a48e120dde311d2efe4ed5af3653c3a421 | nan0445/Leetcode-Python | /Recover Binary Search Tree.py | 803 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
self.pre,self.n1,self.n2 = None,None,None
def helper(root):
if not root: return
helper(root.left)
if not self.pre: self.pre = root
if root.val<self.pre.val:
if not self.n1: self.n1 = self.pre
self.n2 = root
self.pre = root
helper(root.right)
helper(root)
self.n1.val,self.n2.val = self.n2.val,self.n1.val
|
3e6d1270046132f91ba5cadc072ca19307865178 | nan0445/Leetcode-Python | /Balanced Binary Tree.py | 660 | 3.75 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
self.flag = True
def helper(root):
if not root: return 0
if not self.flag: return 0
l = helper(root.left)
r = helper(root.right)
if abs(l-r)>1:
self.flag = False
return 0
return max(l,r)+1
helper(root)
return self.flag
|
4513ff87de71790ef509b716ab2457c32241ac06 | nan0445/Leetcode-Python | /Power of Three.py | 250 | 3.8125 | 4 | class Solution:
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n<=0: return False
while n>1:
n, m = divmod(n, 3)
if m!=0: return False
return True
|
50fac474fbcefc14ff6ae95edde0ecce61f8ccd2 | nan0445/Leetcode-Python | /Binary Tree Right Side View.py | 654 | 3.609375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
def helper(root,k):
if not root: return
if k==0 or k==len(res): res.append([])
res[k].append(root.val)
helper(root.left,k+1)
helper(root.right,k+1)
helper(root,0)
ans = []
for i in range(len(res)):
ans.append(res[i][-1])
return ans
|
62edcf7046115e564e295034c50102711b71c688 | nan0445/Leetcode-Python | /Linked List Cycle II.py | 821 | 3.65625 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head: return None
slow = fast = head
stack = set()
stack.add(slow)
flag = False
while fast and fast.next:
slow=slow.next
fast=fast.next.next
stack.add(slow)
if slow==fast:
flag = True
break
if not flag: return None
if slow==head: return head
slow = slow.next
while slow not in stack:
slow = slow.next
return slow
|
cff739a27abb4061b8d01e34d056580f77981790 | nan0445/Leetcode-Python | /Self Crossing.py | 599 | 3.5625 | 4 | class Solution:
def isSelfCrossing(self, x):
"""
:type x: List[int]
:rtype: bool
"""
if len(x)<=3: return False
flag = True if x[2] > x[0] else False
for i in range(3,len(x)):
if flag == False:
if x[i]>=x[i-2]: return True
else:
if x[i]<=x[i-2]:
flag = False
if i>=4 and x[i-2]-x[i-4]<=x[i]:
x[i-1] -= x[i-3]
elif i==3 and x[i-2]<=x[i]:
x[i-1] -= x[i-3]
return False
|
35b9c6dc1b7ce2b5b4a6d9d1f2ca09d4cf119735 | nan0445/Leetcode-Python | /Different Ways to Add Parentheses.py | 651 | 3.546875 | 4 | class Solution:
def diffWaysToCompute(self, input):
"""
:type input: str
:rtype: List[int]
"""
if input.isdigit(): return [int(input)]
res = []
def helper(n1, n2, op):
if op == '+': return n1 + n2
elif op == '-': return n1 - n2
elif op == '*': return n1 * n2
for i in range(len(input)):
if input[i] in "+-*":
l = self.diffWaysToCompute(input[:i])
r = self.diffWaysToCompute(input[i+1:])
res.extend([helper(ln, rn, input[i]) for ln in l for rn in r])
return res
|
e55d1042b514fb55cff0e831b1d83872cf4c550a | nan0445/Leetcode-Python | /Search Insert Position.py | 545 | 3.71875 | 4 | class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
l,r = 0,len(nums)-1
if r==-1: return 0
while l<r:
mid = (l+r)//2
if target>nums[mid]:
l = mid + 1
elif target<nums[mid]:
r = mid
else: return mid
if nums[l]>target: return max(l,0)
elif nums[l]<target: return min(l+1,len(nums))
elif nums[l]==target: return l
|
d1b02071edd187ca634a03c63b86db4b7838b758 | nan0445/Leetcode-Python | /House Robber III.py | 488 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def helper(node):
if not node: return 0,0
l, r = helper(node.left), helper(node.right)
return max(l) + max(r), node.val + l[0] + r[0]
return max(helper(root))
|
9186c1fb4552a1b862f949cd36b35a126a90061f | nan0445/Leetcode-Python | /Remove Nth Node From End of List.py | 742 | 3.734375 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
count = 0
dummy = ListNode(0)
dummy.next = head
while head!=None:
head = head.next
count+=1
ind = count - n
res = dummy
count = 0
while dummy!=None:
if count==ind:
dummy.next = dummy.next.next
dummy = dummy.next
else:
dummy = dummy.next
count+=1
return res.next
|
753690e49ef2149ccea76603a17de27766f9e8f6 | nan0445/Leetcode-Python | /Fraction to Recurring Decimal.py | 739 | 3.5 | 4 | class Solution:
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
if numerator*denominator<0: sign = '-'
else: sign = ''
numerator, denominator = abs(numerator), abs(denominator)
n, m = divmod(numerator, denominator)
ans = [sign, str(n)]
if m==0: return ''.join(ans)
ans.append('.')
dic = {}
while m!=0:
if m in dic:
ans.insert(dic[m],'(')
ans.append(')')
break
dic[m] = len(ans)
n, m = divmod(m*10, denominator)
ans.append(str(n))
return ''.join(ans)
|
26ff62a19dc23bb66d05ac34c2f87e6c2095a87c | nan0445/Leetcode-Python | /Word Search.py | 859 | 3.578125 | 4 | class Solution:
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
m = len(board)
n = len(board[0])
def helper(p,q,t,board,word):
if p<0 or p>=len(board) or q<0 or q>=len(board[0]) or board[p][q] != word[t]: return False
board[p][q] = '#'
if t == len(word)-1: return True
a1 = helper(p-1,q,t+1,board,word) or helper(p,q-1,t+1,board,word) or helper(p+1,q,t+1,board,word) or helper(p,q+1,t+1,board,word)
board[p][q] = word[t]
return a1
for i in range(m):
for j in range(n):
if board[i][j] == word[0]:
if helper(i,j,0,board,word): return True
return False
|
363fb60fab73ad320aac80101cf924305254ca94 | nan0445/Leetcode-Python | /Palindrome Pairs.py | 654 | 3.609375 | 4 | class Solution:
def palindromePairs(self, words):
"""
:type words: List[str]
:rtype: List[List[int]]
"""
dic = {word: i for i, word in enumerate(words)}
res = []
for j, word in enumerate(words):
for i in range(len(word)+1):
if word[:i] == word[:i][::-1]:
w = word[i:][::-1]
if w != word and w in dic: res.append([dic[w],j])
if i>0 and word[-i:] == word[-i:][::-1]:
w = word[:-i][::-1]
if w != word and w in dic: res.append([j, dic[w]])
return res
|
0e0078f97b8be6d5e53b5da55670433ff1034a3b | chae-heechan/Python_Study | /3. 문자열/practice_2.py | 812 | 3.515625 | 4 | print("a" + "b")
print("a", "b")
# 방법 1
print("나는 %d살입니다." % 20) #굉장히 C스럽네
print("나는 %s를 좋아해요." % "파이썬")
print("Apple 은 %c로 시작해요." % "A")
# %s
print("나는 %s살입니다." % 20)
print("나는 %s색과 %s색을 좋아해요." % ("파란", "빨간"))
# 방법 2
print("나는 {}살입니다.".format(20))
print("나는 {}색과 {}색을 좋아해요.".format("파란", "빨간"))
print("나는 {1}색과 {0}색을 좋아해요.".format("파란", "빨간"))
# 방법 3
print("나는 {age}살이며, {color}색을 좋아해요.".format(age=20, color="빨간"))
print("나는 {age}살이며, {color}색을 좋아해요.".format(color="빨간", age=20))
# 방법 4
age = 20
color = "빨간"
print(f"나는 {age}살이며, {color}색을 좋아해요.") |
aebd7a8b4bfed4166b0c2294ab90c48acc6ce8df | chae-heechan/Python_Study | /3. 문자열/practice_1.py | 411 | 4.0625 | 4 | python = "Python is Amazing"
print(python.lower())
print(python.upper())
print(python[0].isupper())
print(len(python))
print(python.replace("Python", "Java"))
index = python.index("n")
print(index)
index = python.index("n", index + 1)
print(index)
print(python.find("Java")) # 없을 경우 return -1
# print(python.index("Java")) # 없을 경우 error 띄우고 종료
print("hi")
print(python.count("n")) |
dc24a69fde9b47505c07f6e16a95c9497be4763c | chae-heechan/Python_Study | /4. 자료구조/set.py | 662 | 3.859375 | 4 | # 집합 (set)
# 중복 안됨, 순서 없음
my_set = {1, 2, 3, 3, 3}
print(my_set)
java = {"유재석", "김태호", "양세형"}
python = set(["유재석", "박명수"])
# 교집합 (java와 python을 모두 할 수 있는 사람)
print(java & python)
print(java.intersection(python))
# 합집합 (java나 python을 할 수 있는 사람)
print(java | python)
print(java.union(python))
# 차집합 (java는 할 수 있지만 python은 할 수 없는 사람)
print(java - python)
print(java.difference(python))
# python을 할 수 있는사람이 늘어남
python.add("김태호")
print(python)
# java를 까먹음
java.remove("김태호")
print(java) |
c1423dde6c4d142d9028e4d6953e1293d1e0ae29 | Andrew4me/byte | /except/try_except.py | 273 | 3.5 | 4 | try:
text = input('Введите что-нибудь -->')
except EOFError:
print('Ну зачем вы сделали мне EOF?')
except KeyboardInterrupt:
print('вы отменили операцию')
else:
print('Вы ввели {0}' .format(text))
|
3c0a49d57c23bfcd8d38c64fefe23231efd6c5e7 | xswxm/Smart_Fan_for_Raspberry_Pi | /fan.py | 1,446 | 3.71875 | 4 | #!/usr/bin/python2
#coding:utf8
'''
Author: xswxm
Blog: xswxm.com
This script is designed to manage your Raspberry Pi's fan according to the CPU temperature changes.
'''
import RPi.GPIO as GPIO
import os, time
# Parse command line arguments
import argparse
parser = argparse.ArgumentParser(description='Manage your Raspberry Pi Fan intelligently!')
parser.add_argument('-i', '--interval', type=int,
help='The interval of each CPU temperature check (in seconds). default=5', default=5)
parser.add_argument('-p', '--pin', type=int,
help='Pin number of the Fan. default=24', default=24)
parser.add_argument('-t', '--temp_limit', type=int,
help='Fan will be turned on once the temperature is higher than this value (in celsius). default=60', default=60)
args = parser.parse_args()
interval = args.interval
pin = args.pin
temp = 0
temp_limit = args.temp_limit * 1000
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(pin, GPIO.OUT)
try:
while True:
# Acquire CPU temperature
with open('/sys/class/thermal/thermal_zone0/temp', 'r') as file:
temp = int(file.read())
# Turn on the fan if temp is larger than the limit value
if temp > temp_limit:
GPIO.output(pin, GPIO.HIGH)
# Turn off the fan if temp is smaller than the value - 2000
elif temp < temp_limit-5000:
GPIO.output(pin, GPIO.LOW)
# Sleep for few seconds
time.sleep(interval)
except KeyboardInterrupt:
GPIO.cleanup() |
1e894d45be1e1e01e00d89c35e8169d3b3ad5652 | DGEs2018/python_4_django | /functions.py | 197 | 3.546875 | 4 | import functiontobeimported
def multiplication(x, y, z):
return x*y*z
# def square(x):
# return x*x
for i in range(10):
print(f"The square of {i} is {functiontobeimported.square(i)}") |
43d6e2b5da96f94c5037c2a0d19a6330fb5febec | sebastiandifrancesco/web-scraping-challenge | /scrape_mars.py | 3,975 | 3.53125 | 4 | # --- dependencies and setup ---
from bs4 import BeautifulSoup
import pandas as pd
from splinter import Browser
import time
def init_browser():
# Set executable path & initialize Chrome browser
executable_path = {"executable_path": "./chromedriver.exe"}
return Browser("chrome", **executable_path, headless=False)
def scrape():
browser = init_browser()
# Visit NASA Mars news site
url = "https://mars.nasa.gov/news/"
browser.visit(url)
time.sleep(1)
# Parse results HTML using BeautifulSoup
html = browser.html
news_soup = BeautifulSoup(html, "html.parser")
slide_element = news_soup.select_one("ul.item_list li.slide")
slide_element.find("div", class_="content_title")
# Scrape the latest news title
title = slide_element.find("div", class_="content_title").get_text()
# Scrape the latest paragraph text
paragraph = slide_element.find("div", class_="article_teaser_body").get_text()
# Visit the NASA JPL Site
url = "https://data-class-jpl-space.s3.amazonaws.com/JPL_Space/index.html"
browser.visit(url)
# Click button with class name full_image
full_image_button = browser.find_by_xpath("/html/body/div[1]/div/a/button")
full_image_button.click()
# Parse results HTML with BeautifulSoup
html = browser.html
image_soup = BeautifulSoup(html, "html.parser")
featured_image_url = image_soup.select_one("body > div.fancybox-overlay.fancybox-overlay-fixed > div > div > div > div > img").get("src")
# Use base URL to create absolute URL
featured_image_url = f"https://www.jpl.nasa.gov{featured_image_url}"
# Visit the Mars facts site using pandas
mars_df = pd.read_html("https://space-facts.com/mars/")[0]
mars_df.columns=["Description", "Value"]
mars_df.set_index("Description", inplace=True)
html_table = mars_df.to_html(index=False, header=False, border=0, classes="table table-sm table-striped font-weight-light")
# Visit hemispheres website through splinter module
url = "https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars"
browser.visit(url)
# HTML object
html_hemispheres = browser.html
# Parse HTML with Beautiful Soup
soup = BeautifulSoup(html_hemispheres, 'html.parser')
# Retreive all items that contain Mars hemispheres information
items = soup.find_all('div', class_='item')
# Create empty list for hemisphere urls
hemisphere_image_urls = []
# Store the main_url
hemispheres_main_url = 'https://astrogeology.usgs.gov'
# Loop through the items previously stored
for i in items:
# Store title
title = i.find('h3').text
# Store link that leads to full image website
partial_img_url = i.find('a', class_='itemLink product-item')['href']
# Visit the link that contains the full image website
browser.visit(hemispheres_main_url + partial_img_url)
# HTML object of individual hemisphere information website
partial_img_html = browser.html
# Parse HTML with Beautiful Soup for every individual hemisphere information website
soup = BeautifulSoup( partial_img_html, 'html.parser')
# Retrieve full image source
img_url = hemispheres_main_url + soup.find('img', class_='wide-image')['src']
# Append the retrieved information into a list of dictionaries
hemisphere_image_urls.append({"title" : title, "img_url" : img_url})
# Store all values in dictionary
scraped_data = {
"news_title": title,
"news_para": paragraph,
"featuredimage_url": featured_image_url,
"mars_fact_table": html_table,
"hemisphere_images": hemisphere_image_urls
}
# --- Return results ---
return scraped_data |
71b154af653eadaf81bfb74ba900427383f54235 | yan-yf/pyhomework | /hanoi&fib.py | 284 | 3.9375 | 4 | def hanoi(n, A, B, C):
if n == 1:
print A, '->', B
else:
hanoi(n - 1, A, C, B)
print A, '->', B
hanoi(n - 1, C, B, A)
hanoi(5, 'A', 'B', 'C')
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n - 1) + fib (n - 2)
print fib(6) |
a203f7b2a316c3f9eaef8f3ae9ab5d2abd3454cb | leftan/D07 | /HW07_ch10_ex06.py | 928 | 4.09375 | 4 | # I want to be able to call is_sorted from main w/ various lists and get
# returned True or False.
# In your final submission:
# - Do not print anything extraneous!
# - Do not put anything but pass in main()
def is_sorted(list_of_items):
try:
new_list = sorted(list_of_items)
except:
print('The list cannot be sorted.')
return None
if list_of_items == new_list:
return True
else:
return False
def main():
list_1 = ['apple', 'bear', 'cat']
list_2 = ['apple', 'bear', 'apples']
list_3 = [1,2,3]
list_4 = [1,45,3]
list_5 = ['APPLE', 'BEAR', 'APPLES']
list_6 = ['APPLE', 'BEAR', 'CAT']
print(is_sorted(list_1)) # True
print(is_sorted(list_2)) # False
print(is_sorted(list_3)) # True
print(is_sorted(list_4)) # False
print(is_sorted(list_5)) # False
print(is_sorted(list_6)) # True
if __name__ == main():
main() |
83c83339f9279481ccb83273ae84555c316e3fc6 | HelalChow/Data-Structures | /Labs/Lab 8.py | 1,135 | 3.875 | 4 | class ArrayStack:
def __init__(self):
self.data = []
def __len__(self):
return len(self.data)
def is_empty(self):
return len(self) == 0
def push(self, item):
self.data.append(item)
def pop(self):
if self.is_empty==0:
raise Exception("Stack is empty")
return self.data.pop()
def top(self):
if self.is_empty==0:
raise Exception("Stack is empty")
return self.data[-1]
def balanced_expression(str):
lst = []
for i in str:
lst.append(i)
opening = "([{"
closing = ")]}"
stack = ArrayStack()
for i in lst:
if i in opening:
stack.push(i)
elif i in closing:
prev = stack.pop()
if prev == '(' and i != ")":
return False
elif prev == "[" and i != "]":
return False
elif prev == '{' and i != '}':
return False
if stack.is_empty():
return True
else:
return False
print(balanced_expression("{{([])}}([])("))
print(balanced_expression("{{[(])}}"))
|
6219eeb03cac0b97952fe8e2599a006421073865 | HelalChow/Data-Structures | /Classwork/10/10-17 ADT.py | 878 | 3.90625 | 4 | def Algorithm():
pass
'''
***Stack ADT***
Data Model: Collection of items where the last element in is the first to come out (Last in, first out)
Operations:
s = Stack()
len(s)
s.is_empty()
s.push() #Adds Item
s.pop() #Removes last item and returns it
s.top() #Returns last item
'''
def print_reverse(str):
letters = Stack()
for i in str:
letters.push(i)
while(letters.is_empty() == False):
print(letters.pop(),end='')
print()
'''
***Polish Notation***
Infix Postfix Prefix
5 5 5
5+2 5 2 + + 5 2
5-(3*4) 5 34 * - - 5 * 3 4
(5-3)*4 5 3 - 4 * * - 5 3 4
((5+2)*(8-3))/4 5 2 + 8 3 - * 4 / / * + 5 2 - 8 3 4
''' |
8561124801f526b472e5f3b3182b7efccb6f1a0f | HelalChow/Data-Structures | /Labs/Lab 6.py | 1,454 | 3.71875 | 4 | def find_lst_max(lst):
if len(lst)==1:
return lst[0]
else:
hold = find_lst_max(lst[1:])
return max(lst[0],hold)
print(find_lst_max( [1,2,3,4,5,100,12,2]))
def product_evens(n):
if n==2:
return n
else:
if n%2==0:
return n*product_evens(n-2)
else:
return n*product_evens(n-1)
#print(product_evens(8))
def is_palindrome(str, low, high):
if low>=high:
return False
elif high - low == 2 or high-low ==1:
if str[low]==str[high]:
return True
else:
return False
else:
hold = is_palindrome(str,low+1,high-1)
if str[low]==str[high] and hold ==True:
return True
else:
return False
#print(is_palindrome("mam",0,2))
def binary_search(lst,val,low,high):
if high==low:
if lst[low]==val:
return lst.index(val)
else:
return
else:
mid = (high +low)//2
if lst[mid]>=val:
return binary_search(lst,val,low,mid)
else:
return binary_search(lst,val,mid+1,high)
lst=[1,2,3,4,5,6,7,8,9,10]
#print(binary_search(lst,5,0,9))
def nested_sum(lst):
sum = 0
for i in lst:
if isinstance(i, list):
sum = sum+ nested_sum(i)
else:
sum += i
return sum
#print(nested_sum( [1,[2,3,4]])) |
9f6eb2c3ca0d17db7a68b94e7ddd51b1a88592c8 | HelalChow/Data-Structures | /Labs/Lab 2.py | 1,964 | 3.78125 | 4 | class Polynomial:
def __init__(self,lst=[0]):
self.lst = lst
def __repr__(self):
poly = ""
for i in range(len(self.lst)-1,0,-1):
if i == 1:
poly += str(self.lst[i])+"x^"+str(i)+"+"+str(self.lst[0])
else:
poly += str(self.lst[i]) + "x^" + str(i)+"+"
count = poly.count("-")
for i in range(count):
minus=poly.find("-")
poly = poly[:minus-1]+poly[minus:]
return poly
def evaluate(self, val):
sum = 0
for i,j in enumerate(self.lst):
sum+=j*val**i
return sum
def __add__(self, other):
new = []
count=0
if len(self.lst)>len(other.lst):
for i in range(len(other.lst)):
sum=self.lst[i]+other.lst[i]
new.append(sum)
count=i+1
for i in range(count,len(self.lst)):
new.append(self.lst[i])
else:
for i in range(len(self.lst)):
sum=self.lst[i]+other.lst[i]
new.append(sum)
count=i+1
for i in range(count,len(other.lst)):
new.append(other.lst[i])
return Polynomial(new)
def __mul__(self, other):
new = [0]*(len(self.lst)+len(other.lst)-1)
for i,j in enumerate(self.lst):
for k,l in enumerate(other.lst):
new[i+k] += j*l
return Polynomial(new)
def derive(self):
new = []
for i,j in enumerate(self.lst):
new.append(j*i)
new.pop(0)
return Polynomial(new)
def main():
test1 = Polynomial([3,7,0,-9,2])
test2 = Polynomial([1,2])
test_eval = Polynomial([3, 7, 0, -9, 2]).evaluate(2)
test_add = test1+test2
mul = test1*test2
derive = Polynomial([3,7,0,-9,2]).derive()
print(derive)
main()
|
31a03d615d586ef55b70874d973d5a68cd1d4ae1 | HelalChow/Data-Structures | /Homework/HW3/hc2324_hw3_q3.py | 307 | 3.6875 | 4 | def find_duplicates(lst):
counter = [0] * (len(lst) - 1)
res_lst = []
for i in range(len(lst)):
counter[lst[i] - 1] += 1
for i in range(len(counter)):
if (counter[i] > 1):
res_lst.append(i + 1)
return res_lst
print(find_duplicates([0,2,2])) |
68ee8286c000c5c0512432a0d808be49dc8ab6a9 | HelalChow/Data-Structures | /Homework/HW2/hc2324_hw2_q6.py | 593 | 3.671875 | 4 | def two_sum(srt_lst, target):
curr_index = 0
sum_found = False
count =0
while(sum_found==False and curr_index < len(srt_lst)-1):
if (count >= len(srt_lst)):
count = 0
curr_index += 1
elif srt_lst[curr_index] + srt_lst[count] == target and curr_index != count:
sum_found = True
else:
count+=1
if sum_found==True:
return (curr_index, count)
else:
return None
def main():
srt_lst = [-2, 7, 11, 15, 20, 21]
target = 35
print(two_sum(srt_lst, target))
|
fe0871327bdc40129abafafc866406b13995f722 | MafihlwaK/Pre-Bootcamp-coding-Challenges-python- | /Task 11.py | 206 | 3.8125 | 4 | def common_characters():
str1 = input("Enter first string: ")
str2 = input("Enter second string: ")
s1 = set(str1)
s2 = set(str2)
first = s1 & s2
print(first)
common_characters() |
4359dd4f67584016be61c50548e51c8117ee2bc7 | xpbupt/leetcode | /Medium/Complex_Number_Multiplication.py | 1,043 | 4.15625 | 4 | '''
Given two strings representing two complex numbers.
You need to return a string representing their multiplication. Note i2 = -1 according to the definition.
Example 1:
Input: "1+1i", "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.
Example 2:
Input: "1+-1i", "1+-1i"
Output: "0+-2i"
Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.
'''
class Solution(object):
def complexNumberMultiply(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
t_a = self.get_real_and_complex(a)
t_b = self.get_real_and_complex(b)
c = self.calculate(t_a, t_b)
return c[0] + '+' + c[1] +'i'
def get_real_and_complex(self, c):
a = c.split('+')[0]
b = c.split('+')[1].split('i')[0]
return (int(a), int(b))
def calculate(self, a, b):
return (str(a[0]*b[0] - a[1]*b[1]), str(a[0]*b[1] + a[1]*b[0]))
|
f5368db904d1ec8e53ba06e9c529751ed9982f67 | jeevabalanmadhu/__LearnWithMe__ | /Machine Learning/Data science/DataScienceClass/PythonBasics/StringHandling.py | 7,782 | 3.9375 | 4 | #String handling
#isupper
'''
MyString="HELLO"
MyString1="HELLO%&^%&"
MyString2="HELLO%e"
result=MyString.isupper()
result1=MyString1.isupper()
result2=MyString2.isupper()
print(result)
print(result1)
print(result2)
output:
True
True
False
---------------------
#islower
MyString="hello"
MyString1="hello%&^%&"
MyString2="hello%E"
result=MyString.islower()
result1=MyString1.islower()
result2=MyString2.islower()
print(result)
print(result1)
print(result2)
output:
True
True
False
---------------------
#isspace
MyString=""
MyString1=" "
MyString2=" e"
result=MyString.isspace()
result1=MyString1.isspace()
result2=MyString2.isspace()
print(result)
print(result1)
print(result2)
MyString3=None
result3=MyString3.isspace()
print(result3)
output:
False
True
False
Traceback (most recent call last):
File "C:/Users/HP1/AppData/Local/Programs/Python/Python37/StringHandling.py", line 65, in <module>
result3=MyString3.isspace()
AttributeError: 'NoneType' object has no attribute 'isspace'
---------------------
#isdigit
MyString="52342423"
MyString1="2343242 "
MyString2="233423468e3222"
result=MyString.isdigit()
result1=MyString1.isdigit()
result2=MyString2.isdigit()
print(result)
print(result1)
print(result2)
MyString3=""
result3=MyString3.isdigit()
print(result3)
output:
True
False
False
False
---------------------
#istitle
MyString="Hello Python Class"
MyString1="hello Python Class"
MyString2="Hello python Class"
result=MyString.istitle()
result1=MyString1.istitle()
result2=MyString2.istitle()
print(result)
print(result1)
print(result2)
output:
True
False
False
---------------------
#isidentifier
MyString="Hello"
MyString1="hello8"
MyString2="_hello"
MyString3=" hello"
MyString4="^hello"
result=MyString.isidentifier()
result1=MyString1.isidentifier()
result2=MyString2.isidentifier()
result3=MyString3.isidentifier()
result4=MyString4.isidentifier()
print(result)
print(result1)
print(result2)
print(result3)
print(result4)
output:
True
True
True
False
False
---------------------
#isalpha
MyString="Hello"
MyString1="hello8"
MyString2="_hello"
MyString3=" hello"
MyString4="^hello"
result=MyString.isalpha()
result1=MyString1.isalpha()
result2=MyString2.isalpha()
result3=MyString3.isalpha()
result4=MyString4.isalpha()
print(result)
print(result1)
print(result2)
print(result3)
print(result4)
output:
True
False
False
False
False
---------------------
#isalnum
MyString="Hello"
MyString1="hello8"
MyString2="_hello"
MyString3=" hello"
MyString4="^hello"
result=MyString.isalnum()
result1=MyString1.isalnum()
result2=MyString2.isalnum()
result3=MyString3.isalnum()
result4=MyString4.isalnum()
print(result)
print(result1)
print(result2)
print(result3)
print(result4)
output:
True
True
False
False
False
---------------------
#upper
MyString="Hello python"
MyString1="hello8 Py"
MyString2="_hello"
MyString3=" hello"
MyString4="^hello"
result=MyString.upper()
result1=MyString1.upper()
result2=MyString2.upper()
result3=MyString3.upper()
result4=MyString4.upper()
print(result)
print(result1)
print(result2)
print(result3)
print(result4)
output:
HELLO PYTHON
HELLO8 PY
_HELLO
HELLO
^HELLO
---------------------
#swapcase
MyString="Hello pYthon"
MyString1="hello8 Py"
MyString2="_hELlo"
MyString3=" hello"
MyString4="^hellO"
result=MyString.swapcase()
result1=MyString1.swapcase()
result2=MyString2.swapcase()
result3=MyString3.swapcase()
result4=MyString4.swapcase()
print(result)
print(result1)
print(result2)
print(result3)
print(result4)
output:
hELLO PyTHON
HELLO8 pY
_HelLO
HELLO
^HELLo
---------------------
#capitalize
MyString="python Class"
MyString1="hello Python Class"
MyString2="Hello python Class"
MyString3="_hello"
MyString4=" hello"
result=MyString.capitalize()
result1=MyString1.capitalize()
result2=MyString2.capitalize()
result3=MyString3.capitalize()
result4=MyString4.capitalize()
print(result)
print(result1)
print(result2)
print(result3)
print(result4)
output:
Python class
Hello python class
Hello python class
_hello
hello
---------------------
#startswith
MyString="python Class"
MyString1="hello Python Class"
MyString2="Hello python Class"
MyString3="_hello"
MyString4=" hello"
result=MyString.startswith("he")
result1=MyString1.startswith("he")
result2=MyString2.startswith("he")
result3=MyString3.startswith("he")
result4=MyString4.startswith("he")
print(result)
print(result1)
print(result2)
print(result3)
print(result4)
output:
False
True
False
False
False
---------------------
#endswith
MyString="python CLASS"
MyString1="hello Python Class"
MyString2="Hello python"
MyString3="_hello class "
MyString4=" hello"
result=MyString.endswith("ss")
result1=MyString1.endswith("ss")
result2=MyString2.endswith("ss")
result3=MyString3.endswith("ss")
result4=MyString4.endswith("ss")
print(result)
print(result1)
print(result2)
print(result3)
print(result4)
output:
False
True
False
False
False
---------------------
#split
MyString="python CLASS"
MyString1="hello Python Class"
MyString2="HeLlo python"
MyString3="_hello class "
MyString4=" heLLo"
result=MyString.split("SS")
result1=MyString1.split("o")
result2=MyString2.split("s")
result3=MyString3.split("l")
result4=MyString4.split("L")
print(result)
print(result1)
print(result2)
print(result3)
print(result4)
output:
1
2
0
3
2
---------------------
#split
MyString="python CLASS"
MyString1="hello Python Class"
MyString2="HeLlo python"
MyString3="_hello class "
MyString4=" heLLo"
result=MyString.split("CL")
result1=MyString1.split(" ")
result2=MyString2.split("on")
result3=MyString3.split("L")
result4=MyString4.split("L")
print(result)
print(result1)
print(result2)
print(result3)
print(result4)
output:
['python ', 'ASS']
['hello', 'Python', 'Class']
['HeLlo pyth', '']
['_hello class ']
[' he', '', 'o']
---------------------
#rstrip
MyString="Hello pYthon "
MyString1="hello8 Py "
MyString2="_hELlo"
MyString3=" hello"
MyString4=" ^hellO"
result=MyString.rstrip()
result1=MyString1.rstrip()
result2=MyString2.rstrip()
result3=MyString3.rstrip()
result4=MyString4.rstrip()
print(result)
print(len(MyString))
print(len(result))
print(result1)
print(len(MyString1))
print(len(result1))
print(result2)
print(len(MyString2))
print(len(result2))
print(result3)
print(len(MyString3))
print(len(result3))
print(result4)
print(len(MyString4))
print(len(result4))
output:
15
Hello pYthon
15
12
hello8 Py
10
9
_hELlo
6
6
hello
6
5
^hellO
7
6
---------------------
#lrstrip
MyString="Hello pYthon "
MyString1="hello8 Py "
MyString2="_hELlo"
MyString3=" hello"
MyString4=" ^hellO"
result=MyString.rstrip()
result1=MyString1.rstrip()
result2=MyString2.rstrip()
result3=MyString3.rstrip()
result4=MyString4.rstrip()
print(result)
print(len(MyString))
print(len(result))
print(result1)
print(len(MyString1))
print(len(result1))
print(result2)
print(len(MyString2))
print(len(result2))
print(result3)
print(len(MyString3))
print(len(result3))
print(result4)
print(len(MyString4))
print(len(result4))
output:
Hello pYthon
15
15
hello8 Py
10
10
_hELlo
6
6
hello
6
5
^hellO
7
6
---------------------
#rstrip
MyString="Hello pYthon "
MyString1="hello8 Py "
MyString2="_hELlo"
MyString3=" hello"
MyString4=" ^hellO"
result=MyString.rstrip()
result1=MyString1.rstrip()
result2=MyString2.rstrip()
result3=MyString3.rstrip()
result4=MyString4.rstrip()
print(result)
print(len(MyString))
print(len(result))
print(result1)
print(len(MyString1))
print(len(result1))
print(result2)
print(len(MyString2))
print(len(result2))
print(result3)
print(len(MyString3))
print(len(result3))
print(result4)
print(len(MyString4))
print(len(result4))
output:
Hello pYthon
15
12
hello8 Py
10
9
_hELlo
6
6
hello
6
6
^hellO
7
7
|
4f4be5077a2ec1945975bc34b0c05c20af8e6600 | jeevabalanmadhu/__LearnWithMe__ | /Machine Learning/Data science/DataScienceClass/PythonBasics/OddOrEven.py | 527 | 4.0625 | 4 | #odd or even from 1-100
'''
####method: 1
myOddList=[]
myEvenList=[]
for i in range(1,101):
if(i%2==0):
print("even = {0}".format(i))
elif(i%2==1):
print("odd = {0}".format(i))
'''
###Method 2:
myOddList=[]
myEvenList=[]
for i in range(1,101):
if(i%2==0):
myEvenList.append(i)
elif(i%2==1):
myOddList.append(i)
print("Odd number from 1 - 100 are: ",myOddList)
print()
print("Even number from 1 - 100 are: ",myEvenList)
|
1c749cd9a5612b07f817fe9ae2b5df307e896ff1 | leonardo185/Data-Structures-using-Python | /binary_search.py | 527 | 3.78125 | 4 | def binarySearach(list, value):
first = 0
last = len(list) - 1
found = False
index = None
while(first <= last and not found):
midpoint = int((first + last)/2)
if(list[midpoint] == value):
found = True
index = midpoint + 1
else:
if(value < list[midpoint]):
last = midpoint - 1
else:
first = midpoint + 1
return index
list = [1,2,3,4,5,6,7,8,9]
print(binarySearach(list, 8))
|
eae2e47d12de9e59fcf8637f16e4349e78efa153 | Mystic67/Game-Mac-Gyver | /controller/events.py | 1,860 | 3.6875 | 4 | #! /usr/bin/python3
# -*-coding: utf-8-*-
import pygame
class Events:
'''This class listen the user inputs and set the game variables '''
main = 1
home = 1
game = 1
game_level = 0
game_end = 0
# self.listen_events()
@classmethod
def listen_game_events(cls, instance_sprite=None):
cls.instance_sprite = instance_sprite
for event in pygame.event.get():
if event.type == pygame.QUIT or event.type == pygame.KEYDOWN \
and event.key == pygame.K_ESCAPE:
cls.quit_game() # Quit the game
'''If user presse space bar, quit home screen and start game'''
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
cls.go_game() # Start de game
''' Listen the directory entry key if instance
of sprite is given as parameter'''
elif instance_sprite is not None:
if event.key == pygame.K_RIGHT:
cls.instance_sprite.move("right")
elif event.key == pygame.K_LEFT:
cls.instance_sprite.move("left")
elif event.key == pygame.K_UP:
cls.instance_sprite.move("up")
elif event.key == pygame.K_DOWN:
cls.instance_sprite.move("down")
@classmethod
def quit_game(cls):
cls.home = 0
cls.game = 0
cls.main = 0
cls.game_level = 0
@classmethod
def init_game(cls):
cls.home = 1
cls.game = 1
@classmethod
def go_game(cls):
cls.home = 0
cls.game_level = 1
cls.game_end = 0
@classmethod
def end_game(cls):
cls.game = 0
cls.game_end = 1
cls.home = 1
|
9e0d6c1a5ccda5e204d5ab171e22afc74f63261b | francico4293/Sudoku-Solver-v2 | /sudoku_board.py | 21,643 | 4.125 | 4 | # Author: Colin Francis
# Description: Implementation of the sudoku board using Pygame
import pygame
import time
from settings import *
class SudokuSolver(object):
"""A class used to solve Sudoku puzzles."""
def __init__(self):
"""Creates a SudokuSolver object."""
self._board = Board()
self._running = True
pygame.font.init()
def run(self) -> None:
"""
Load a blank puzzle board, input the puzzle, and run the solver.
:return: None.
"""
while self._running:
for event in pygame.event.get():
# check if the user is trying to exit
if event.type == pygame.QUIT:
self._running = False
# check for a grid square being selected
if event.type == pygame.MOUSEBUTTONDOWN:
if (BOARD_LEFT <= pygame.mouse.get_pos()[0] <= BOARD_LEFT + BOARD_WIDTH) and \
(BOARD_TOP <= pygame.mouse.get_pos()[1] <= BOARD_TOP + BOARD_HEIGHT):
self._board.set_selected_coords(mouse_pos()[0], mouse_pos()[1])
elif (BUTTON_LEFT <= pygame.mouse.get_pos()[0] <= BUTTON_LEFT + BUTTON_WIDTH) and \
(BUTTON_TOP <= pygame.mouse.get_pos()[1] <= BUTTON_TOP + BUTTON_HEIGHT):
self._board.click()
# check for a number being entered
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1 or event.key == pygame.K_KP1:
self._board.set_number_by_selected(1)
elif event.key == pygame.K_2 or event.key == pygame.K_KP2:
self._board.set_number_by_selected(2)
elif event.key == pygame.K_3 or event.key == pygame.K_KP3:
self._board.set_number_by_selected(3)
elif event.key == pygame.K_4 or event.key == pygame.K_KP4:
self._board.set_number_by_selected(4)
elif event.key == pygame.K_5 or event.key == pygame.K_KP5:
self._board.set_number_by_selected(5)
elif event.key == pygame.K_6 or event.key == pygame.K_KP6:
self._board.set_number_by_selected(6)
elif event.key == pygame.K_7 or event.key == pygame.K_KP7:
self._board.set_number_by_selected(7)
elif event.key == pygame.K_8 or event.key == pygame.K_KP8:
self._board.set_number_by_selected(8)
elif event.key == pygame.K_9 or event.key == pygame.K_KP9:
self._board.set_number_by_selected(9)
if self._board.solve():
self._solve()
self._board.update_board(pygame.mouse.get_pos()) # update the game board
pygame.display.update() # update the display
def _solve(self):
"""
Used to solve Sudoku puzzles.
:return:
"""
self._board.lock_presets()
row_index, col_index = 0, 0
start_time = time.perf_counter()
while not self._board.solved():
if col_index > 8:
col_index = 0
row_index += 1
self._board.set_selected_coords(BOARD_LEFT + (SQUARE_HEIGHT * col_index),
BOARD_TOP + (SQUARE_WIDTH * row_index)
)
if self._board.get_number(row_index, col_index) == '.' and not \
self._board.is_preset(row_index, col_index):
for number in range(1, 10):
if not self._board.in_row(row_index, str(number)) and not \
self._board.in_col(col_index, str(number)) and not \
self._board.in_square(row_index, col_index, str(number)):
self._board.set_number_by_index(row_index, col_index, str(number))
col_index += 1
break
else:
row_index, col_index = self._back_prop(row_index, col_index - 1)
elif not self._board.is_preset(row_index, col_index):
start_number = int(self._board.get_number(row_index, col_index)) + 1
for number in range(start_number, 10):
if not self._board.in_row(row_index, str(number)) and not \
self._board.in_col(col_index, str(number)) and not \
self._board.in_square(row_index, col_index, str(number)):
self._board.set_number_by_index(row_index, col_index, str(number))
col_index += 1
break
else:
self._board.set_number_by_index(row_index, col_index, '.')
row_index, col_index = self._back_prop(row_index, col_index - 1)
else:
col_index += 1
self._board.update_board(pygame.mouse.get_pos()) # update the game board
pygame.display.update() # update the display
end_time = time.perf_counter()
print("Solution Speed: {:.2f}s".format(end_time - start_time))
# self.print_board()
def _back_prop(self, row_index: int, col_index: int) -> tuple:
"""
Recursively moves backwards through the Sudoku puzzle until a non-preset
value less than 9 is found.
:param row_index: The current row index in the puzzle.
:param col_index: The current column index in the puzzle
:return: A tuple containing the row index and column index where the
non-preset value was found.
"""
if col_index < 0:
col_index = 8
row_index -= 1
# base case
if self._board.get_number(row_index, col_index) != '9' and not self._board.is_preset(row_index, col_index):
return row_index, col_index
if self._board.get_number(row_index, col_index) == '9' and not self._board.is_preset(row_index, col_index):
self._board.set_number_by_index(row_index, col_index, '.')
return self._back_prop(row_index, col_index - 1)
elif self._board.is_preset(row_index, col_index):
return self._back_prop(row_index, col_index - 1)
class Board(object):
"""Represents a Sudoku Board."""
def __init__(self):
"""Creates a Board object."""
self._screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
self._surface = pygame.Surface((BOARD_WIDTH, BOARD_HEIGHT))
self._screen.fill(WHITE)
self._surface.fill(WHITE)
self._button = Button(self._screen)
self._selected_square = [None] * 2
self._puzzle = [[".", ".", ".", ".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", ".", ".", ".", "."],
]
self._puzzle_presets = None
pygame.display.set_caption('Sudoku Solver')
def update_board(self, mouse_position):
"""
Updates the state of the Sudoku Board.
:return: None.
"""
self._screen.blit(self._surface, (BOARD_LEFT, BOARD_TOP))
if self._selected_square != [None] * 2:
self._color_selected()
self._color_row()
self._color_col()
self._button.update(mouse_position)
self._place_numbers()
self._draw_grid()
def solve(self) -> bool:
return self._button.is_clicked()
def click(self):
self._button.click()
def get_number(self, row_index: int, col_index: int) -> str:
"""
Returns the number in the Sudoku puzzle found in the position specified by
`row_index` and `col_index`.
:param row_index: The index of the row to get the number from.
:param col_index: The index of the column to get the number from.
:return: The number corresponding to the specified row index and column
index.
"""
return self._puzzle[row_index][col_index]
def lock_presets(self):
self._puzzle_presets = self._find_presets()
def set_selected_coords(self, x_coord: int, y_coord: int) -> None:
"""
Sets the x-coordinate and y-coordinate of the selected square.
:param x_coord: The x-coordinate of the selected square.
:param y_coord: The y-coordinate of the selected square.
:return: None.
"""
self._selected_square[0], self._selected_square[1] = x_coord, y_coord
def set_number_by_selected(self, number: int) -> None:
"""
Sets the `number` in the puzzle row / col corresponding to the currently
selected square.
:param number: The number to set.
:return: None.
"""
if self._selected_square == [None] * 2:
return
row = (self._selected_square[1] - BOARD_TOP) // SQUARE_HEIGHT
col = (self._selected_square[0] - BOARD_LEFT) // SQUARE_WIDTH
self._puzzle[row][col] = str(number)
def set_number_by_index(self, row_index: int, col_index: int, number: str) -> None:
"""
Sets the square in the Sudoku puzzle corresponding to `row_index` and
`col_index`.
:param row_index: The index of the row to place the number in.
:param col_index: The index of the column to place the number in.
:param number: The number to place in the puzzle.
:return: None.
"""
self._puzzle[row_index][col_index] = number
def solved(self) -> bool:
"""
Searches each row in the Sudoku puzzle to determine if a solution has been
found.
:return: True if a solution has been found. Otherwise, False.
"""
if '.' in self._puzzle[0] or '.' in self._puzzle[1] or '.' in self._puzzle[2] or \
'.' in self._puzzle[3] or '.' in self._puzzle[4] or '.' in self._puzzle[5] or \
'.' in self._puzzle[5] or '.' in self._puzzle[7] or '.' in self._puzzle[8]:
return False
return True
def in_row(self, row_index: int, number: str) -> bool:
"""
Searches the Sudoku puzzle to see if `number` exists in the specified row index.
:param row_index: The row index in the Sudoku puzzle to search in.
:param number: The number to search for.
:return: True if the number is found in the row. Otherwise, False.
"""
if number in self._puzzle[row_index]:
return True
return False
def in_col(self, col_index: int, number: str) -> bool:
"""
Searches the Sudoku puzzle to see if 'number' exists in the specified column
index.
:param col_index: The column index in the Sudoku puzzle to search in.
:param number: The number to search for.
:return: True if the number is found in the column. Otherwise, False.
"""
for row in self._puzzle:
if row[col_index] == number:
return True
return False
def in_square(self, row_index: int, col_index: int, number: str) -> bool:
"""
Searches the Sudoku puzzle to see if the `number` exists in the square
region of the Sudoku board as indicated by the specified row index and
column index.
:param row_index: The row index of the Sudoku puzzle to search in.
:param col_index: The column index of the Sudoku puzzle to search
in.
:param number: The number to search for.
:return: True if the number is found in the square region. Otherwise,
False.
"""
squares = {1: self._puzzle[0][:3] + self._puzzle[1][:3] + self._puzzle[2][:3],
2: self._puzzle[0][3:6] + self._puzzle[1][3:6] + self._puzzle[2][3:6],
3: self._puzzle[0][6:] + self._puzzle[1][6:] + self._puzzle[2][6:],
4: self._puzzle[3][:3] + self._puzzle[4][:3] + self._puzzle[5][:3],
5: self._puzzle[3][3:6] + self._puzzle[4][3:6] + self._puzzle[5][3:6],
6: self._puzzle[3][6:] + self._puzzle[4][6:] + self._puzzle[5][6:],
7: self._puzzle[6][:3] + self._puzzle[7][:3] + self._puzzle[8][:3],
8: self._puzzle[6][3:6] + self._puzzle[7][3:6] + self._puzzle[8][3:6],
9: self._puzzle[6][6:] + self._puzzle[7][6:] + self._puzzle[8][6:]
}
if row_index == 0 or row_index == 1 or row_index == 2:
if 0 <= col_index < 3:
if number in squares[1]:
return True
return False
elif 3 <= col_index < 6:
if number in squares[2]:
return True
return False
else:
if number in squares[3]:
return True
return False
elif row_index == 3 or row_index == 4 or row_index == 5:
if 0 <= col_index < 3:
if number in squares[4]:
return True
return False
elif 3 <= col_index < 6:
if number in squares[5]:
return True
return False
else:
if number in squares[6]:
return True
return False
else:
if 0 <= col_index < 3:
if number in squares[7]:
return True
return False
elif 3 <= col_index < 6:
if number in squares[8]:
return True
return False
else:
if number in squares[9]:
return True
return False
def is_preset(self, row_index: int, col_index: int) -> bool:
"""
Determines whether a board value is a preset value or not.
:param row_index: The row corresponding to the value in the puzzle to check.
:param col_index: The column corresponding to the value in the puzzle to check.
:return: True if the value is preset. Otherwise, False.
"""
if self._puzzle_presets[row_index][col_index]:
return True
else:
return False
def _place_numbers(self) -> None:
"""
Places the numbers set in the puzzle onto the Sudoku Board.
:return: None.
"""
# TODO: Find a better way to center the number
for row_index, row in enumerate(self._puzzle):
for col_index, number in enumerate(row):
if number != ".":
font = pygame.font.SysFont('Arial', 30)
number_surface = font.render(number, True, BLACK)
self._screen.blit(number_surface,
(BOARD_LEFT + (SQUARE_WIDTH * col_index) + (SQUARE_WIDTH / 2) - 5,
BOARD_TOP + (SQUARE_HEIGHT * row_index) + (SQUARE_HEIGHT / 4) - 5
)
)
def _draw_grid(self) -> None:
"""
Draws the grid used in Sudoku on the Board.
:return: None.
"""
pygame.draw.rect(self._screen,
BLACK,
pygame.Rect(BOARD_LEFT, BOARD_TOP, BOARD_WIDTH, BOARD_HEIGHT),
width=3
)
self._draw_vert_grid_lines()
self._draw_horz_grid_lines()
def _draw_vert_grid_lines(self) -> None:
"""
Draws vertical grid lines on the Board.
:return: None.
"""
grid_count = 1
for x_coord in range(BOARD_LEFT + SQUARE_WIDTH, BOARD_WIDTH + BOARD_LEFT + SQUARE_WIDTH, SQUARE_WIDTH):
width = 1 if grid_count % 3 != 0 else 3
pygame.draw.line(self._screen,
BLACK,
(x_coord, BOARD_TOP),
(x_coord, BOARD_HEIGHT + BOARD_TOP),
width=width
)
grid_count += 1
def _draw_horz_grid_lines(self) -> None:
"""
Draws horizontal grid lines on the Board.
:return: None.
"""
grid_count = 1
for y_coord in range(BOARD_TOP + SQUARE_HEIGHT, BOARD_HEIGHT + BOARD_TOP + SQUARE_HEIGHT, SQUARE_HEIGHT):
width = 1 if grid_count % 3 != 0 else 3
pygame.draw.line(self._screen,
BLACK,
(BOARD_LEFT, y_coord),
(BOARD_LEFT + BOARD_WIDTH, y_coord),
width=width
)
grid_count += 1
def _color_selected(self) -> None:
"""
Colors the selected square.
:return: None.
"""
pygame.draw.rect(self._screen,
SQUARE_BLUE,
pygame.Rect(self._selected_square[0],
self._selected_square[1],
SQUARE_WIDTH,
SQUARE_HEIGHT)
)
def _color_row(self) -> None:
"""
Colors the row corresponding to the selected square.
:return: None.
"""
row_surface = pygame.Surface((BOARD_WIDTH, SQUARE_HEIGHT))
row_surface.set_alpha(100)
row_surface.fill(SQUARE_BLUE)
self._screen.blit(row_surface, (BOARD_LEFT, self._selected_square[1]))
def _color_col(self) -> None:
"""
Colors the column corresponding to the selected square.
:return: None.
"""
col_surface = pygame.Surface((SQUARE_WIDTH, BOARD_HEIGHT))
col_surface.set_alpha(100)
col_surface.fill(SQUARE_BLUE)
self._screen.blit(col_surface, (self._selected_square[0], BOARD_TOP))
def _find_presets(self) -> list:
"""
Iterates through the initial Sudoku puzzle and determines which values are preset and
which values are variable.
:return: A matrix (list-of-lists) containing boolean values - True for preset, False
for variable.
"""
preset_values = []
for row_index, row in enumerate(self._puzzle):
preset_row = []
for col_index, col_value in enumerate(row):
if col_value == '.':
preset_row.append(False)
else:
preset_row.append(True)
preset_values.append(list(preset_row))
preset_row.clear()
return preset_values
class Button(object):
""""""
def __init__(self, board):
""""""
self._clicked = False
self._board = board
def update(self, mouse_position: tuple) -> None:
"""
Updates the states of the Button.
:param mouse_position: The current position of the user's mouse.
:return: None.
"""
if (BUTTON_LEFT <= mouse_position[0] <= BUTTON_LEFT + BUTTON_WIDTH) and \
(BUTTON_TOP <= mouse_position[1] <= BUTTON_TOP + BUTTON_HEIGHT):
color = DARK_GREY
else:
color = LIGHT_GREY
self._draw_button(color)
self._button_text()
def is_clicked(self):
return self._clicked
def click(self):
self._clicked = True
def _draw_button(self, color: tuple) -> None:
"""
Draws the button on the screen.
:param color: The color of the button.
:return: None.
"""
pygame.draw.rect(self._board,
color,
pygame.Rect(BUTTON_LEFT,
BUTTON_TOP,
BUTTON_WIDTH,
BUTTON_HEIGHT)
)
def _button_text(self) -> None:
"""
Displays the text "Solve Puzzle" inside of the Button.
:return: None.
"""
font = pygame.font.SysFont('Arial', 20)
text_surface = font.render('Solve Puzzle', True, BLACK)
self._board.blit(text_surface, (BUTTON_LEFT + 15, BUTTON_TOP + 2))
if __name__ == "__main__":
sudoku_puzzle = [["5", "3", ".", ".", "7", ".", ".", ".", "."],
["6", ".", ".", "1", "9", "5", ".", ".", "."],
[".", "9", "8", ".", ".", ".", ".", "6", "."],
["8", ".", ".", ".", "6", ".", ".", ".", "3"],
["4", ".", ".", "8", ".", "3", ".", ".", "1"],
["7", ".", ".", ".", "2", ".", ".", ".", "6"],
[".", "6", ".", ".", ".", ".", "2", "8", "."],
[".", ".", ".", "4", "1", "9", ".", ".", "5"],
[".", ".", ".", ".", "8", ".", ".", "7", "9"]]
solve = SudokuSolver()
solve.run()
|
b716e509279d0f192f5128489d752690a4d303ed | subham09/Comp9021 | /Quizes/quiz 4.py | 3,442 | 3.625 | 4 | # Randomly fills a grid of size height and width whose values are input by the user,
# with nonnegative integers randomly generated up to an upper bound N also input the user,
# and computes, for each n <= N, the number of paths consisting of all integers from 1 up to n
# that cannot be extended to n+1.
# Outputs the number of such paths, when at least one exists.
#
# Written by Subham Anand for COMP9021
from random import seed, randint
import sys
from collections import defaultdict
def display_grid():
for i in range(len(grid)):
print(' ', ' '.join(str(grid[i][j]) for j in range(len(grid[0]))))
def get_paths():
global grid1
grid1 = list(grid)
zero = []
for i in range(height):
grid1[i].append(0)
grid1[i].reverse()
grid1[i].append(0)
grid1[i].reverse()
for i in range(width+2):
zero.append(0)
grid1.append(zero)
grid1.reverse()
grid1.append(zero)
grid1.reverse()
areas = {}
b = 0
global max_length
path = {}
counter = 0
for i in range(1,height+1):
for j in range(1,width+1):
if grid1[i][j] == 1:
if grid1[i][j+1] != 2 and grid1[i][j-1] != 2 and grid1[i+1][j] != 2 and grid1[i-1][j] != 2 :
counter += 1
areas[1] = counter
while max_length > 1:
for i in range(1,height+1):
for j in range(1,width+1):
if grid1[i][j] == max_length:
if grid1[i][j+1] != max_length + 1 and grid1[i][j-1] != max_length + 1 and grid1[i-1][j] != max_length + 1 and grid1[i+1][j] != max_length + 1 :
b = areas_of_region(max_length,i,j)
if max_length in areas:
areas[max_length] = areas[max_length] + b
else:
areas[max_length] = b
max_length -= 1
return areas
# Replace pass above with your code
# Insert your code for other functions
def areas_of_region(n,i,j,counter = 0, a = 0):
if grid1[i][j+1] == n-1 and n > 1:
if n-1 == 1 and n > 1:
a+=1
a += areas_of_region(n-1,i,j+1)
if grid1[i][j-1] == n-1 and n > 1:
if n-1 == 1 and n > 1:
a+=1
a += areas_of_region(n-1,i,j-1)
if grid1[i+1][j] == n-1 and n > 1:
if n-1 == 1 and n > 1:
a+=1
a += areas_of_region(n-1,i+1,j)
if grid1[i-1][j] == n-1 and n > 1:
if n-1 == 1 and n > 1:
a+=1
a += areas_of_region(n-1,i-1,j)
return a
try:
for_seed, max_length, height, width = [int(i) for i in
input('Enter four nonnegative integers: ').split()
]
if for_seed < 0 or max_length < 0 or height < 0 or width < 0:
raise ValueError
except ValueError:
print('Incorrect input, giving up.')
sys.exit()
seed(for_seed)
grid = [[randint(0, max_length) for _ in range(width)] for _ in range(height)]
print('Here is the grid that has been generated:')
display_grid()
#convert_grid()
paths = get_paths()
if paths:
for length in sorted(paths):
print(f'The number of paths from 1 to {length} is: {paths[length]}')
|
7000f0861768fb5c3cccb7e6dc7bc017190d456b | AlexseySukhanov/HomeWork3 | /Task_add_1.py | 360 | 3.734375 | 4 | flat=int(input("Введите номер квартиры "))
if flat<=144 and flat>0:
ent=int(flat/36-0.01)+1
floor=int(flat/4-0.01)+1-(ent-1)*9
print(f"Квартира находится в {ent} подъезде, на {floor} этаже")
else:
print("Квартиры с таким номером не существует в доме")
|
1def0b375d6b7f6d8ec10e58f8aefc784c923486 | Egan-eagle/python-exercises | /week1&2.py | 3,145 | 4.3125 | 4 | # Egan Mthembu
# A program that displays Fibonacci numbers using people's names.
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
name = "Mthembu"
first = name[0]
last = name[-1]
firstno = ord(first)
lastno = ord(last)
x = firstno + lastno
ans = fib(x)
print("My surname is", name)
print("The first letter", first, "is number", firstno)
print("The last letter", last, "is number", lastno)
print("Fibonacci number", x, "is", ans)
#COMMENT
Re: Week 2 task
by EGAN MTHEMBU - Saturday, 3 February 2018, 6:47 PM
C:\Users\egan\Desktop\fib.py\WEEK2>python test.py
My surname is Mthembu
The first letter M is number 77
The last letter u is number 117
Fibonacci number 194 is 15635695580168194910579363790217849593217
ord(c)
Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example,ord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr().
i.e
firstno = ord(first) M = 77
lastno = ord(last) U = 117
x = firstno + lastno = 194
Fibonacci number 194 is 15635695580168194910579363790217849593217
WEEK1 EXERCISE
# Egan Mthembu 24.01.2018
# A program that displays Fibonacci numbers.
def fib(n):
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
x = 19
ans = fib(x)
print("Fibonacci number", x, "is", ans)
Re: Fibonacci exercise responses
by EGAN MTHEMBU - Wednesday, 24 January 2018, 11:12 PM
Egan : E + N = 19, Fibonacci Number = 4181
C:\Users\ppc\Desktop\Fibonacci>python fib3.py
Fibonacci number 19 is 4181# Egan Mthembu
# A program that displays Fibonacci numbers using people's names.
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
name = "Mthembu"
first = name[0]
last = name[-1]
firstno = ord(first)
lastno = ord(last)
x = firstno + lastno
ans = fib(x)
print("My surname is", name)
print("The first letter", first, "is number", firstno)
print("The last letter", last, "is number", lastno)
print("Fibonacci number", x, "is", ans)
#COMMENT
#Re: Week 2 task
#EGAN MTHEMBU - Saturday, 3 February 2018, 6:47 PM
#My surname is Mthembu
The first letter M is number 77
The last letter u is number 117
Fibonacci number 194 is 15635695580168194910579363790217849593217
ord(c)
Given a string repord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr().
i.e
firstno = ord(first) M = 77
lastno = ord(last) U = 117
x = firstno + lastno = 194
Fibonacci number 194 is 15635695580168194910579363790217849593217
##WEEK1 EXERCISE
# Egan Mthembu 24.01.2018
# A program that displays Fibonacci numbers.
def fib(n):
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
x = 19
ans = fib(x)
print("Fibonacci number", x, "is", ans)
Re: Fibonacci exercise responses
by EGAN MTHEMBU - Wednesday, 24 January 2018, 11:12 PM
Egan : E + N = 19, Fibonacci Number = 4181
Fibonacci number 19 is 4181
|
8fdad961a6692877342af74576cda9610090de77 | yuvraajsj18/CS50 | /intro/week6/tuple.py | 115 | 3.609375 | 4 | tuple = [
(1, 'a'),
(2, 'b'),
(3, 'c')
]
for num, alpha in tuple:
print(f"{alpha} - {num}") |
312c19e4e77b383d412b06a7ca482e7930e94b8a | yuvraajsj18/CS50 | /intro/week6/swap.py | 174 | 3.5625 | 4 | from cs50 import get_int
x = get_int("x = ")
y = get_int("y = ")
print(f"Before Swap: x = {x} & y = {y}")
x, y = y, x
print(f"After Swap: x = {x} & y = {y}")
|
29df6be4c64bd613e10323d60edf59d28f8b1386 | yuvraajsj18/CS50 | /intro/week6/hello1.py | 133 | 3.515625 | 4 | from cs50 import get_string
name = get_string("Name: ")
print("Hello,",name)
print(f"{name}, Hello!!!") # formated string output |
f27f0ec182b9da2d7ffac680b2c6cbab78494f9a | Sir-Benj/Python-First-Game | /enemy.py | 1,621 | 3.765625 | 4 | # Enemy Class
# Creating as a module.
# Creating the Enemy Class.
class Enemy:
"""For Each Enemy in the game"""
def __init__(self, name, hp, maxhp, attack, heal_count, heal, magic_count, magic_attack):
self.name=name
self.hp=hp
self.maxhp=maxhp
self.attack=attack
self.heal_count=heal_count
self.heal=heal
self.magic_count=magic_count
self.magic_attack=magic_attack
def __str__(self):
return "\t{}\n***********\nHP:{}\nMaxHP:{}\nAttack:{}\nHeal Count:{}\nHeal:{}\nMagic Count:{}\nMagic Attack:{}".format(self.name, self.hp, self.maxhp, self.attack, self.heal_count, self.heal, self.magic_count, self.magic_attack)
def is_alive(self):
return self.hp > 0
####################################################################################################################
# Function to unpack the enemy text file and create Enemy class objects to append to a list.
def enemy_unpack(file):
"""Creating all enemies from a text file"""
with open(file, "r") as f:
enemies = []
for line in f:
line = line.strip()
line = line.replace("/", "\n")
line = line.split("*")
name = line[0]
hp = int(line[1])
maxhp = int(line[2])
attack = int(line[3])
heal_count = int(line[4])
heal = int(line[5])
magic_count = int(line[6])
magic_attack = int(line[7])
enemy = Enemy(name, hp, maxhp, attack, heal_count, heal, magic_count, magic_attack)
enemies.append(enemy)
return enemies |
c5db71efe8b6a60f65ae9b00bb6b5258f468cf0c | ShamiliS/Java_Backup | /practice/funct2.py | 232 | 3.609375 | 4 | '''
Created on 4 Apr 2018
@author: SHSRINIV
'''
import function1
result = function1.calcuator_add(4, 5)
print("Addition:", result)
listofvalues = [3, 6, 7, 8, 2]
listresult = function1.listCheck(listofvalues)
print(listresult)
|
e25be21c2647af9c32be52f2891770f2b5177ece | ShamiliS/Java_Backup | /SimplePython/pException.py | 478 | 3.53125 | 4 | '''
Created on 9 Apr 2018
@author: SHSRINIV
'''
def KelvinToFahrenheit(temp):
result = 0
try:
assert(temp > 0), "Colder than absolute zero!"
except AssertionError:
print("AssertionError: Error in the input", temp)
except TypeError:
print(TypeError)
else:
result = ((temp - 273) * 1.8) + 32
print("")
return result
print(KelvinToFahrenheit(0))
print(KelvinToFahrenheit("test"))
print(KelvinToFahrenheit(273))
|
2f69991dd752fee0a0fe55ca276bc3b9db4ca8df | JacobRoyster/GroupMe | /GroupMeFunctions/RemoveFromGroup.py | 1,971 | 3.609375 | 4 | import requests
import json
import sys
"""
userToken should be a valid GroupMe user token. (string)
groupID should be a valid group that you have access to. (string)
userID should be a valid ID for the user you want to remove. If this userID is yours, you leave the group. (string)
purpose of this function is to remove someone (including yourself) from a group.
"""
def RemoveFromGroup(userToken, groupID, userID):
# Standard start for the request string for the GroupMe API
standardBeginning = "https://api.groupme.com/v3/groups"
# Assembling the request
response = requests.post( (standardBeginning + "/" + groupID + "/members/" + userID +"/remove?token=" +userToken ) )
# Printing response code. Response code key available at https://dev.groupme.com/docs/responses
# Additional info will be availabe if you print out the entire translated json package
print(response)
# It is possible to result in non bmp characters (such as emojiis)
# Non bmp characters will be mapped to � (oxfffd)
non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode +1), 0xfffd)
jsonInterpretedResponse = json.loads(response.text.translate(non_bmp_map))
# Printing out entire json resonse package
if (jsonInterpretedResponse['meta']['code'] < 400):
# We have a least sent a validly formatted packet and recieved a response
return()
else:
print(jsonInterpretedResponse)
raise ValueError("We have a packet with a meta code != 200")
def TestRemoveFromGroup():
# Load in my token, then use that token to view the groups
with open("C://Users//Public//Documents//groupmetoken.txt") as f:
userToken = f.read()
with open("C://Users//Public//Documents//groupmegroupid.txt") as f:
groupID = f.read()
with open("C://Users//Public//Documents//groupmetestdummyid.txt") as f:
testdummyid = f.read()
RemoveFromGroup(str(userToken),str(groupID),str(testdummyid))
|
70499b8516182a300a1a47dd14bb226fbaa7a696 | yzzyq/Machine-learning | /贝叶斯/病例预测/naiveBayes.py | 5,349 | 4.03125 | 4 | #贝叶斯算法
import csv
import random
import math
import copy
#整个流程:
##1.处理数据:从CSV文件载入数据,分为训练集和测试集
## 1.将文件中字符串类型加载进来转化为我们使用的数字
## 2.数据集随机分为包含67%的训练集和33%的测试集
##
##2.提取数据特征:提取训练数据集的属性特征,以便我们计算概率并作出预测
## 1.按照类别划分数据
## 2.写出均值函数
## 3.写出标准差函数
## 4.计算每个类中每个属性的均值和标准差(因为这里是连续型变量,也可以使用区间)
## 5.写个函数将上面过程写入其中
##
##3.预测
## 1.根据上述计算出的均值和方差,写出函数是计算高斯概率密度函数
## 2.计算值对每个类别的高斯概率分布
##
##3.单一预测:使用数据集的特征生成单个预测
## 1.比较那个类别的概率更大,就输出哪个
##
##4.评估精度:评估对于测试数据集的预测精度作为预测正确率
## 1.多重预测:基于给定测试数据集和一个已提取特征的训练数据集生成预测,就是生成了很多预测.
## 2.计算精度,看正确率
#加载数据
# 1. Number of times pregnant
# 2. Plasma glucose concentration a 2 hours in an oral glucose tolerance test
# 3. Diastolic blood pressure (mm Hg)
# 4. Triceps skin fold thickness (mm)
# 5. 2-Hour serum insulin (mu U/ml)
# 6. Body mass index (weight in kg/(height in m)^2)
# 7. Diabetes pedigree function
# 8. Age (years)
# 9. Class variable (0 or 1)
#加载数据
def loadData(fileName):
dataSet = []
with open(fileName) as file:
File = csv.reader(file,delimiter=',')
dataSet = list(File)
for i in range(len(dataSet)):
#将字符串转化为浮点数,数据量有点大
dataSet[i] = [float(x) for x in dataSet[i]]
return dataSet
#将数据集分为训练集和测试集
def splitDataSet(dataSet,splitRatio):
trainSetSize = int(len(dataSet)*splitRatio)
trainSet = []
#测试集
exeSet = dataSet
while len(trainSet) < trainSetSize:
index = random.randrange(len(exeSet))
data = copy.deepcopy(dataSet[index])
trainSet.append(data)
del exeSet[index]
return trainSet,exeSet
#按照类别划分数据,这里就是0和1
def splitDataSetByClass(dataSet):
dataClass = {}
for data in dataSet:
key = data[-1]
if key not in dataClass.keys():
dataClass[key] = []
del data[-1]
dataClass[key].append(data)
return dataClass
#因为数据中的数值都是连续型的
#计算均值
def averageData(dataSet):
return sum(dataSet)/len(dataSet)
#计算方差
def varianceData(dataSet):
aver = averageData(dataSet)
temp = 0.0
dataSetTemp = dataSet
for data in dataSet:
temp += math.pow(data - aver,2)+1
return math.sqrt(temp/(len(dataSet)+2))
#计算每个属性的均值和方差
def attributesNormal(dataSet):
dataClass = splitDataSetByClass(dataSet)
dataNormal = {}
#每个类别进行循环
for dataAttri in dataClass.keys():
data = dataClass[dataAttri]
dataNormal[dataAttri] = []
#每列元素组合在一起
dataAttribute = zip(*data)
#计算每列的均值和方差
for dataCol in dataAttribute:
attri = []
aver = averageData(dataCol)
variance = varianceData(dataCol)
attri.append(aver)
attri.append(variance)
dataNormal[dataAttri].append(attri)
print('dataNormal:',dataNormal)
return dataNormal
#计算每个属性高斯密度函数
def normalFunction(value,data):
aver = value[0]
variance = value[1]
temp = math.exp(-(float)(math.pow(data-aver,2))/(2*math.pow(variance,2)))
return (1/math.sqrt(2*(math.pi)*variance))*temp
#计算每个类别的每个属性密度函数值
def Normal(dataNormal,exeData):
bestLabel = None
bestScoer = 0.0
#比较俩个类别,谁大就是谁
for key in dataNormal.keys():
values = dataNormal[key]
normalClass = 1
for i in range(len(values)):
normalClass *= normalFunction(values[i],exeData[i])
if normalClass > bestScoer:
bestScoer = normalClass
bestLabel = key
return bestLabel
#模型的准确率
def accuracy(results,exeSet):
correctDecision = []
for data in exeSet:
print(data)
correctDecision.append(data[-1])
sumExeDataSet = len(exeSet)
correctNum = 0
#print(len(correctDecision))
#print(len(results))
for i in range(sumExeDataSet):
if correctDecision[i] == results[i]:
correctNum += 1
return correctNum/sumExeDataSet
#加载数据
dataSet = loadData('pima-indians-diabetes.csv')
#70%是训练集,30%是测试集
trainSet,exeSet = splitDataSet(dataSet,0.7)
#得出所有的属性的均值和方差
dataNormal = attributesNormal(trainSet)
#对每个数据计算结果
results = []
for exe in exeSet:
result = Normal(dataNormal,exe)
results.append(result)
#测试准确度
num = accuracy(results,exeSet)
print(num)
|
7da84a0ef5b3fad6a422adf7242707c31f07bbe7 | seales/EulerSolutions | /Solutions/Solution30.py | 1,152 | 3.859375 | 4 |
def get_nth_digit(number, n):
if n < 0:
return 0
else:
return get_0th_digit(number / 10**n)
def get_0th_digit(number):
return int(round(10 * ((number/10.0)-(number/10))))
def digit_count(number):
return len(str(number))
def nth_digit_sum_upper_bound(n):
i = 0
while digit_count(i)*9**n >= i:
i += 10
return i
def sum_digits_equals_nth_power(number, n):
if number < 2:
return False
summation = 0
for i in range(digit_count(number)):
summation += get_nth_digit(number, i) ** n
if summation > number:
return False
return summation == number
assert sum_digits_equals_nth_power(1634, 4)
assert sum_digits_equals_nth_power(8208, 4)
assert sum_digits_equals_nth_power(9474, 4)
assert not sum_digits_equals_nth_power(9574, 4)
def sum_of_numbers_with_nth_digit_sum_equality(n):
i = 0
bound = nth_digit_sum_upper_bound(n)
summation = 0
while i <= bound:
if sum_digits_equals_nth_power(i, n):
summation += i
i += 1
return summation
print sum_of_numbers_with_nth_digit_sum_equality(5)
|
8b7e67918be7f322b2243df81fec613e61815cbb | seales/EulerSolutions | /Solutions/Solution47.py | 2,021 | 3.71875 | 4 |
import math
def find_factors(n, factors):
if n == 1:
return factors
divisor = math.floor(math.sqrt(n))
# loop until integer divisor found
while (n/divisor) != int(n/(divisor*1.0)):
divisor -= 1
if int(divisor) == 1:
break
a = int(n/(divisor*1.0))
b = int(divisor)
a_is_prime = is_prime(int(n/(divisor*1.0)))
b_is_prime = is_prime(b)
if a_is_prime and a not in factors:
factors.append(a)
if b_is_prime and b not in factors:
factors.append(b)
if not a_is_prime and not b_is_prime:
return find_factors(a, find_factors(b, factors))
elif not a_is_prime and b_is_prime:
return find_factors(a, factors)
elif a_is_prime and not b_is_prime:
return find_factors(b, factors)
else:
return factors
def is_prime(n):
divisor = math.floor(math.sqrt(n))
while (n/(divisor)) != int(n/(divisor*1.0)):
divisor -= 1
if int(divisor) == 1:
return True
return divisor == 1
def first_of_consecutive_prime_factors(n):
index = 2
current_prime_factors = []
consecutive_prime_factor_count = 0
while True:
previous_number = index
current_prime_factors = find_factors(index, [])
if len(current_prime_factors) == n:
consecutive_prime_factor_count += 1
else:
consecutive_prime_factor_count = 0
if consecutive_prime_factor_count == n:
return index - n + 1
index += 1
### TEST IS PRIME METHOD ###
assert not is_prime(10)
assert is_prime(2)
assert is_prime(1)
assert is_prime(13)
assert not is_prime(15)
### TEST FIND FACTORS METHOD ###
factors_found = find_factors(4, [])
assert len(factors_found) == 1
assert 2 in factors_found
factors_found = find_factors(646,[])
assert len(factors_found) == 3
assert 19 in factors_found
assert 17 in factors_found
assert 2 in factors_found
print first_of_consecutive_prime_factors(4) |
bf16f46f94cad68da94c323d0d506b450e0cefc0 | patiregina89/Exercicios-Logistica_Algoritimos | /Questionario.py | 1,945 | 4.0625 | 4 | print("*"*12,"FACULDADE CESUSC","*"*12)
print("CURSO: ANÁLISE E DESENV. DE SISTEMAS")
print("Discipl.: Lógica Computacional e Algorítimos")
print("Turma: ADS11")
print("Nome: Patricia Regina Rodrigues")
print("Exercício:Questionário")
print(("*"*42))
'''
3) Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa
cadastrada, o programa perguntar se o usuário quer ou não continuar. No final
mostre:
a. a) Quantas pessoas tem mais de 18 anos.
b. b) Quantos homens foram cadastrados.
c. c) Quantas mulheres tem menos de 20 anos.
'''
qtd_pessoa_18 = 0
qtd_homem = 0
qtd_mulher = 0
while True:
idade = int(input("Informe a idade: "))
sexo = ' '
while sexo not in 'MF':
sexo = str(input("Informe o sexo [M/F]: "))
if idade >= 18:
qtd_pessoa_18 += 1
if sexo == 'M':
qtd_homem += 1
if sexo == 'F' and idade < 20:
qtd_mulher += 1
resp = ' '
while resp not in 'SN':
resp = str(input("Quer continuar [S/N]? "))
if resp == 'N':
break
print("Finalizado!")
print("A quantidade de pessoas, maior de 18 anos, cadastradas é: %d"%qtd_pessoa_18)
print("A quantidde de homens cadatsrados é: %d"%qtd_homem)
print("A quantidade de mulheres com menos de 20 anos cadastrdas é: %d"%qtd_mulher)
'''
Criei 3 variávei atribuidas o valor de 0 pois utilizamos para cacular as quantidades, conforme as perguntas.
Criei também a variável resp para saber se o usuário quer continuar respondendo ou finalizar o programa 'break'.
Usei o while true, pois quero que ele repita a perguntas várias vezes até que o usuáro decida parar com o comando 'N'
Pedi que informassem a idade; Pedi que informassem o sexo, porém fiz uma condição para que aceitem apenas M ou F, caso contrário, ele repete a pergunta.
Feito isso, utilizei o if para responder as perguntas e utilizei a formula para somar à variável existente+1.
''' |
e7fcefbf8508b463718639ae1098f2933eff8c24 | patiregina89/Exercicios-Logistica_Algoritimos | /Funcao_calculos.py | 771 | 3.921875 | 4 | import sys
'''ARQUIVOS NÃO EXECUTAVEIS. sao apenas funções pré-determinadas.'''
def somar():
x = float(input('Digite o primeiro número: '))
y = float(input('Digite o segundo número: '))
print('Somar: ', x + y)
def subtrair():
x = float(input('Digite o primeiro número: '))
y = float(input('Digite o segundo número: '))
print('Subtrair: ', x - y)
def multiplicar():
x = float(input('Digite o priemiro número: '))
y = float(input('Digite o segundo número: '))
print('Multiplicar: ', x * y)
def dividir():
x = float(input('Digite o primeiro número: '))
y = float(input('Digite o segundo número: '))
print('Dividir: ', x / y)
def sair():
print('Saindo do sistema!')
sys.exit(0) |
509db82ab08a4667d0642c5f952301717c291fb9 | patiregina89/Exercicios-Logistica_Algoritimos | /Condicao_Parada999.py | 1,444 | 4.21875 | 4 | print("*"*12,"FACULDADE CESUSC","*"*12)
print("CURSO: ANÁLISE E DESENV. DE SISTEMAS")
print("Discipl.: Lógica Computacional e Algorítimos")
print("Turma: ADS11")
print("Nome: Patricia Regina Rodrigues")
print("Exercício:Condição parada 999")
print(("*"*42))
'''
Crie um programa que leia vários números inteiros pelo teclado. O programa só vai
parar quando o usuário digitar o valor de 999 (flag), que é a condição de parada. No
final mostre quantos números foram digitados e qual foi a soma entre eles
(desconsiderando o flag - 999)
'''
soma = 0
num_digitado = 0
while True:
num = int(input("Digite um número ou 999 para sair: "))
if num == 999:
break
soma = soma + num
num_digitado = num_digitado + 1
print("A soma dos números digitados é: ",soma)
print("A quantidade de números digitados é: ", num_digitado)
'''
Criei uma variável soma atribuida o valor de 0, pois pedem a soma dos valores digitados.
Também criei a variável num_digitado com valor atribuido de 0 pois, o exercicio quer saber quantos números foram digitados.
Usei o while true pois significa que enquanto a condição for verdadeira, o sistema irá se repetir. Então:
enquanto o número digitado for diferente de 999, ele vai repetir o pedido de digitar novo número.
Assim que o usuário digitar 999, o programa se encerra e ele informa a soma dos números digitados e a quantidade de números digitados.
''' |
ec39f6b56f562c88fb97f60df1037443664419f4 | patiregina89/Exercicios-Logistica_Algoritimos | /repeticao_aninhada.py | 260 | 3.984375 | 4 | tabuada = 1
while tabuada<=10:
numero = 1
while numero <= 10:
print("%d x %d = %d"%(tabuada, numero, tabuada*numero))
numero = numero + 1
#numero += 1 ---> mesma coisa da sequencia acima
print("="*14)
tabuada+=1 |
7bb23b547c4e1c5993093195c726b8b54f42a820 | patiregina89/Exercicios-Logistica_Algoritimos | /Dic_comparando_paises.py | 1,543 | 3.984375 | 4 |
print()
#Criar dicionário
dic_Paises = {'Brasil': 211049519,
'França': 65129731,
'Portugal': 10226178,
'México': 10226178,
'Uruguai': 3461731}
#utilizar os métodos do dicionário
print('********************** 1 - Método **********************')
print(dic_Paises)
print(dic_Paises.keys())
print(dic_Paises.values())
print('A população extimada do Brasil é: ', dic_Paises.get('Brasil'))
print()
print()
#percorrer todos os elementos do meu dicionário
print('***** 2 - Percorrer todos os elemnetos do dicionário *****')
for k, v in dic_Paises.items():
print(k, '-->', v)
print()
print()
#usando outras funções
print('******************** 3 - Outras Funções ********************')
print('----- 3.1 - Len (contar número de chaves do dicionário -----')
print('Total de chaves: ', len(dic_Paises))
print()
print('---------- 3.2 - Min e Max (maior e menor chave) ----------')
print('Menor chaves: ', min(dic_Paises), '(ordem alfabética)')
print('Maior chaves: ', max(dic_Paises), '(ordem alfabética)')
print()
print()
#combinar dicionários
dic_Novos_Paises = {'Belize': 390351,
'Tanzânia': 58005461}
print('**************** 4 - Atualizando dicionários ****************')
dic_Paises.update(dic_Novos_Paises)
print('Dicionário Atualizado', dic_Paises)
print()
print()
#limpeza do dicionário
print('**************** 5 - Destruindo dicionário ****************')
dic_Paises.clear()
print(dic_Paises) |
dcf778368e954f93a6ae7e05677ad4b1f37384c8 | patiregina89/Exercicios-Logistica_Algoritimos | /Exercicio3_Notas.py | 695 | 4 | 4 | print("*"*12,"FACULDADE CESUSC","*"*12)
print("CURSO: ANÁLISE E DESENV. DE SISTEMAS")
print("Discipl.: Lógica Computacional e Algorítimos")
print("Turma: ADS11")
print("Nome: Patricia Regina Rodrigues")
print("Exercício 3 - Média notas")
print(("*"*42))
#3. Faça um Programa que leia 4 notas, mostre as notas e a média na tela.
nota1 = float(input('Informe a primeira nota: '))
nota2 = float(input('Informe a segunda nota:' ))
nota3 = float(input('Informe a terceira nota: '))
nota4 = float(input('Informe a quarta nota: '))
media = (nota1 + nota2 + nota3 + nota4) / 4
lista = [nota1, nota2, nota3, nota4]
print('A suas notas foram:{}, e a sua média final é {:.2f}'.format(lista, media)) |
9c2c799fbfd1d11762fcf1c25a2a413ae2087b91 | patiregina89/Exercicios-Logistica_Algoritimos | /Lista_Soma_Notas2.py | 229 | 3.765625 | 4 | notas = [0.0, 0.0, 0.0]
notas[0] = float(input("Informe a nota 1: "))
notas[1] = float(input("Informe a nota 2: "))
notas[2] = float(input("Informe a nota 3: "))
print("A somas das notas é: ", notas[0]+notas[1]+notas[2]) |
0b6d65ee7e88de9c04723eba487b5e807571cd2f | CoCode2018/Refresher | /Python/笨办法学Python3/Exercise 1.py | 1,216 | 3.5 | 4 | """
slightly
adv.轻微地,轻轻地;细长地,苗条地;〈罕〉轻蔑地;粗
exactly
adv.恰恰;确切地;精确地;完全地,全然
SyntaxError
语法错误
Usually
adv.通常,经常,平常,惯常地;一直,向来;动不动,一般;素
cryptic
adj.神秘的;隐藏的;有隐含意义的;使用密码的
Drills
n.钻头;操练( drill的名词复数 );军事训练;(应对紧急情况的)演习
v.训练;操练;钻(孔)( drill的第三人称单数 );打(眼)
explain
vt.& vi.讲解,解释
vt.说明…的原因,辩解
vi.说明,解释,辩解
#
An "octothorpe" is also called a "pound", "hash", "mesh", or any number of names.
Pick the one that makes you chill out.
common
adj.普通的;通俗的;[数学]公共的;共有的
n.普通;[法律](对土地、水域的)共有权;公共用地;平民
Common Student Questions
学生常见问题
"""
# ex1.py
print("Hello World!")
print("Hello Again")
print("I like typing this.")
print("This is fun.")
print('Yay! Printing.')
print("I'd much rather you 'not'.")
print('I "said" do not touch this.')
# Study Drills
print("学习演练")
# 注释
print("# 起注释作用")
|
a83d4a66c989c107a57dadf4dcfb8e597e14a107 | CoCode2018/Refresher | /Python/笨办法学Python3/Exercise 18.py | 1,416 | 4.71875 | 5 | """
Exercise 18: Names, Variables, Code, Functions
1.Every programmer will go on and on about functions
introduce
vt.介绍;引进;提出;作为…的
about to
即将,正要,刚要;欲
explanation
n.解释;说明;辩解;(消除误会后)和解
tiny
adj.极小的,微小的
n.小孩子;[医]癣
related
adj.有关系的;叙述的
vt.叙述(relate过去式和过去分词)
break down
失败;划分(以便分析);损坏;衰弱下来
except that
n.除了…之外,只可惜
asterisk
n.星号,星状物
vt.加星号于
parameter
n.[数]参数;<物><数>参量;限制因素;决定因素
indenting
n.成穴的
v.切割…使呈锯齿状( indent的现在分词 );缩进排版
colon
n.冒号;<解>结肠;科郎(哥斯达黎加货币单位
right away
就;立刻,马上;当时
"""
# this one if like your scripts with argv
def print_two(*args):
arg1, arg2, arg3 = args
print(F"arg1: {arg1}\narg2: {arg2}\narg3: {arg3}\nargs: {args}")
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print(F"arg1: {arg1}\narg2: {arg2}")
# this just takes one argument
def print_one(arg1):
print(F"arg1: {arg1}")
# this one takes no arguments
def print_none():
print("I got nothin'.")
print_two("Zed", "Shaw", "ZhouGua")
print_two_again("Zed", "Shaw")
print_one("First!")
print_none() |
c0c7eb4b9ada3385e0f96acca76bcf758080851e | AlphaBitClub/alphabit-coding-challenge | /alphabit-coding-challenge-01/03_zeros/solutions/zeros.py | 432 | 3.625 | 4 | # count the multiplicity of the factor y in x
def multiplicity(x, y):
count = 0
while x % y == 0:
x //= y
count += 1
return count
n = int(input())
two = 0
five = 0
for _ in range(n):
x = int(input())
if x % 2 == 0:
two += multiplicity(x, 2)
if x % 5 == 0:
five += multiplicity(x, 5)
# the min is the number of pairs of (2, 5)
zeros = min(two, five)
# OUTPUT
print(zeros) |
a71c8a60aafc290dab24730570a42709f24d5627 | luislama/algoritmos_y_estructuras_de_datos | /algoritmos/17_suma_de_primos/suma_de_primos.py | 1,570 | 3.59375 | 4 | '''
Encuentre la suma de los numeros primos menores a 2 millones
'''
'''
Analisis
Anteriormente, el numero primo mayor a calcular fue el 10001, el algoritmo de buscar los numeros primos no era eficiente,
pero no representaba un problema
En este caso, el tope es de 2000000 y necesita otro enfoque
Se utiliza un arreglo para ir almacenando los numeros primos, sin embargo no es suficiente
Investigando, se encuentra un metodo que evita el tener que verificar si cada numero es primo dentro de la serie
Se utiliza un arreglo para marcar los numeros no primos dentro de la serie, y al avanzar por el arreglo, aquellos que
no estan marcados, son primos
0 1 2 3 4 5 6 7 8 9 10
1 1 0 0 1 0 1 0 1 1 1
0 no es primo
1 no es primo
2 si es primo, encuentro sus multiplos dentro de la serie
2 4 6 8 10
0 1 2 3 4 5 6 7 8 9 10
1 1 0 0 1 0 1 0 1 0 1
3 no esta marcado, es primo, encuentro sus multiplos
3 9
0 1 2 3 4 5 6 7 8 9 10
1 1 0 0 1 0 1 0 1 1 1
de esta manera, tachando los multiplos que son faciles de calcular, se pueden sumar los primos sin necesidad de hacer la verificacion
se necesita el arreglo de 2000001 elementos
'''
MAX = 2000000
numeros = [0]*(MAX + 1)
numeros[0] = 1
numeros[1] = 1
suma_de_primos = 0
for i in range(MAX + 1):
if numeros[i] == 0:
suma_de_primos += i
for mult in range(i, int(MAX/i) + 1):
numeros[i * mult] = 1
print("".join(["La suma de los numeros primos menores a ", str(MAX), " es: ", str(suma_de_primos)]))
|
55ba0cf476b6e3bb1b11adfee422b27374244d74 | sukritsangvong/Hearts | /main.py | 4,422 | 4 | 4 | #Final project for CS 111 with DLN
#PJ Sangvong and Ben Aoki-Sherwood
#Hearts
from heartCard import *
from playable import *
from turnFunction import *
from calculateScore import *
from roundFunction import *
from takeCardFromBoard import *
from botswap import *
from heartsBoard import *
def main():
'''Runs the card game Hearts, displayed in a graphics window (with some
information also in the terminal window).'''
input("Welcome to Hearts! Press ENTER to start.")
#Create the players and the starting deck
deck, players = createDeck(), generatePlayers()
#Deal the cards
for player in players:
assignHand(player,deck, 13)
makeSortedHand(player)
window = setup()
player0Hand = players[0].getHand()
clickZone = slotForCardOnHand(window, player0Hand)
Tie = False
roundCount = 1
#The game continues as long as no one reaches a score of 20. If a player
#reaches 20 points but there is a tie for the lowest score, play continues
while (players[0].getScore() < 20 and players[1].getScore() < 20 \
and players[2].getScore() < 20 and players[3].getScore() < 20) or Tie:
print("You: ", players[0].getHand())
print("-----------")
print("Bot 1: ", players[1].getHand())
print("-----------")
print("Bot 2: ", players[2].getHand())
print("-----------")
print("Bot 3: ", players[3].getHand())
print("-----------")
#Initializing variables at the beginning of each round
roundCount = roundCount % 4
displayTextChooseCard(window, roundCount, False)
cardSwap(players,roundCount, clickZone, window)
giveSwaps(players,roundCount)
displayTextChooseCard(window, roundCount, True)
player0Hand = players[0].getHand()
clickZone = slotForCardOnHand(window, player0Hand)
index2ofClubs = find2OfClubs(players)
#Updates the players and determines who will lead the next trick,
#as well as whether hearts have been broken yet or not
players, indexOfNextPlayer, isHeartPlayed, clickZone = \
turn(players, index2ofClubs, True, \
False, window, clickZone)
if index2ofClubs == 0:
player0Hand = players[0].getHand()
clickZone = slotForCardOnHand(window, player0Hand)
print("-x-x-x-x-x-x-x-x-x-x-x-x-x-x--x Turn Ended -x-x-x-x-x-x-x-x-x-x-x-x-x-x--x")
while players[0].getHand() != [[],[],[],[]]:
players, indexOfNextPlayer, isHeartPlayed, clickZone = \
turn(players, indexOfNextPlayer, False, \
isHeartPlayed, window, clickZone)
updateScore(players[indexOfNextPlayer])
players[indexOfNextPlayer].clearGraveyard()
playerScore = players[indexOfNextPlayer].getScore()
score(window, playerScore, indexOfNextPlayer, False)
print("-x-x-x-x-x-x-x-x-x-x-x-x-x-x--x Turn Ended -x-x-x-x-x-x-x-x-x-x-x-x-x-x--x")
scores = []
for player in players:
scores.append(player.getScore())
#generate new deck
deck = createDeck()
players = generatePlayers()
#give new hands
for player in players:
assignHand(player,deck, 13)
makeSortedHand(player)
player.setScore(scores[players.index(player)])
#new round
roundCount += 1
#determining if there is a tie at end of round
winningPlayerIndex = 0
lowestScore = 20
for player in players:
if player.getScore() < lowestScore:
lowestScore = player.getScore()
lowestScoreCount = 0
for player in players:
if player.getScore() == lowestScore:
lowestScoreCount += 1
winningPlayerIndex = players.index(player)
if lowestScoreCount > 1:
Tie = True
else:
Tie = False
player0Hand = players[0].getHand()
clickZone = slotForCardOnHand(window, player0Hand)
winner = ''
if winningPlayerIndex == 0:
winner = "You win!"
else:
winner = "Bot " + str(winningPlayerIndex) + " wins!"
print("Game Over!", winner)
if __name__ == "__main__":
main()
|
d5ae00e795446869e908aeec451a5dd8012dd487 | Darkman94/autoencoder | /encode_tf.py | 2,742 | 3.8125 | 4 | from tensorflow.examples.tutorials.mnist import input_data
#not sure this is working the way I think it is
#if it is it's a really poor model
#don't think I need one_hot, since I'm training an autoencoder
#not attempting to learn the classification
mnist = input_data.read_data_sets("MNIST_data/", one_hot = True)
import tensorflow as tf
#Turn denoising on/off
corrupt = True
#the corruption function for the denoising
def corruption(x):
'''adds a corruption to the input variables uniformly distributed in [-1,1]
params:
x -> the (Tensorflow) value to be corrupted
'''
global corrupt
if corrupt:
return tf.multiply(x,tf.random_uniform(shape=tf.shape(x), minval = -1, maxval = 1, dtype = tf.float32))
else:
return x
#a placeholder is used to store values that won't change
#we'll load this with the MNIST data
#None indicates we'll take arbitrarily many entries in that dimension, na d784 is the size of an individual MNIST image
x = tf.placeholder(tf.float32, [None, 784])
#build our neural network
W_1 = tf.Variable(tf.zeros([784,512]))
b_1 = tf.Variable(tf.zeros([512]))
W_2 = tf.Variable(tf.zeros([512,256]))
b_2 = tf.Variable(tf.zeros([256]))
W_3 = tf.Variable(tf.zeros([256,128]))
b_3 = tf.Variable(tf.zeros([128]))
W_4 = tf.Variable(tf.zeros([128,64]))
b_4 = tf.Variable(tf.zeros([64]))
W_5 = tf.Variable(tf.zeros([64,128]))
b_5 = tf.Variable(tf.zeros([128]))
W_6 = tf.Variable(tf.zeros([128,256]))
b_6 = tf.Variable(tf.zeros([256]))
W_7 = tf.Variable(tf.zeros([256,512]))
b_7 = tf.Variable(tf.zeros([512]))
W_8 = tf.Variable(tf.zeros([512,784]))
b_8 = tf.Variable(tf.zeros([784]))
y_1 = tf.nn.sigmoid(tf.matmul(corruption(x), W_1) + b_1)
y_2 = tf.nn.sigmoid(tf.matmul(y_1, W_2) + b_2)
y_3 = tf.nn.sigmoid(tf.matmul(y_2, W_3) + b_3)
y_4 = tf.nn.sigmoid(tf.matmul(y_3, W_4) + b_4)
y_5 = tf.nn.sigmoid(tf.matmul(y_4, W_5) + b_5)
y_6 = tf.nn.sigmoid(tf.matmul(y_5, W_6) + b_6)
y_7 = tf.nn.sigmoid(tf.matmul(y_6, W_7) + b_7)
y = tf.nn.sigmoid(tf.matmul(y_7, W_8) + b_8)
#Get the function to minimize
loss = tf.nn.l2_loss(y - x)
#create a training step for (batch) gradient descent
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
l2diff = tf.sqrt( tf.reduce_sum(tf.square(tf.subtract(x, y)), reduction_indices=1))
loss_mean = tf.reduce_mean(l2diff)
with tf.Session() as sess:
#initialize our Variables
sess.run(tf.global_variables_initializer())
for _ in range(10000):
#load the next 50 values from MNIST (hre is where the batch comes in)
batch_x, batch_y = mnist.train.next_batch(50)
#run our training step (each Placeholder needs a value in the dictionary)
train_step.run(feed_dict={x: batch_x})
#get the accuracy
print(sess.run(loss_mean, feed_dict={x: mnist.test.images})) |
01d4eeafaf9ddbb6966fe3c9a3a29755942931be | pankajgupta119/Python | /piggy.py | 779 | 4.0625 | 4 | #A Piggybank contains 10 Rs coin, 5 Rs coin , 2 Rs coin and 1 Rs coin then calculate total amount.
print("\tPIGGY BANK")
num1=int(input("Enter the number of 10rs coin\n "))
result1=num1*10
print("The total amount of 10rs coin is",result1)
print("\n")
num2=int(input("Enter the number of 5rs coin\n "))
result2=num2*5
print("The total amount of 5rs coin is",result2)
print("\n")
num3=int(input("Enter the number of 2rs coin\n "))
result3=num3*2
print("The total amount of 2rs coin is",result3)
print("\n")
num4=int(input("Enter the number of 1rs coin\n "))
result4=num4*1
print("The total amount of 1rs coin is",result4)
print("\n")
print("THE TOTAL AMOUNT OF ALL THE COINS IS\n")
total=result1+result2+result3+result4
print(total)
|
008a644d92b235fb12c932f9d8d32785aa557c8b | pankajgupta119/Python | /swap.py | 176 | 3.984375 | 4 | num1=int(input("ENTER NUMBER1"))
num2=int(input("ENTER NUMBER2"))
print("nuber1=",num1)
print("nu2mber=",num2)
num1,num2=num2,num1
print("num1=",num1)
print("num2=",num2) |
7e64a3f0004ba7103ae527be9e661e18a548eef8 | Romko97/Python | /Codawars/1.py | 743 | 3.515625 | 4 | # boolean_list= [True, True, False, True, True, False, False, True]
# print(f"The origion list is{boolean_list}")
# res_true, res_false = [],[]
# for i, item in enumerate(boolean_list):
# temp = res_true if item else res_false
# temp.append(i)
# print(f"True indexes: {res_true}" )
# print(f"False indexes: {res_false}" )
# class Perens:
# def __init__(self, param):
# self.v1= param
# class Chaild(Perens):
# def __init__(self, param):
# self.v2= param
# op = Chaild(11)
# print(op.v1 +' '+ op.v2)
# print(r'\ndfs')
# one = chr(104)
# two = chr(105)
# print(one+two)
# dic = {}
# dic[(1,2,4)] = 8
# dic[(4,2,1)] = 10
# dic[(1,2)] = 12
# sum=0
# for k in dic:
# sum += dic[k]
# print(len(dic)+sum) |
a6ca59324734f9e4fcf75d443b17070b2b14138b | Romko97/Python | /Softserve/HOME_WORK_03.py | 2,926 | 3.625 | 4 | Zen = '''The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!'''
# Знайти кількість слів у стрічці
substring = ["better", "never", "is"]
for i in range(len(substring)):
count = Zen.count(substring[i])
print(count)
print('\n............................\n')
# Вивести весь текст у верхньому регістрі.
# upperString = Zen.upper()
# print(upperString)
print(Zen.upper())
print('\n............................\n')
# Замінити всі літери "і" на "&"
# replaced_i_to_ampersand = Zen.replace('i', '&')
# print(replaced_i_to_ampersand)
print(Zen.replace('i', '&'))
print('\n............................\n')
# Задано чотирицифрове натуральне число.
# first way of solution
# Знайти добуток цифр цього числа.
number = int(input("Please enter nnumber :"))
changed_type = str(number)
product = 1
for i in range(len(changed_type)):
product *= int(changed_type[i])
print("product is :", product)
print('\n............................\n')
# Записати число в реверсному порядку.
# the first way of solution
print('\n.first way of solution \n')
changed_type = str(number)
print(list(reversed(changed_type)))
# the second way of solution.
print('\n.second way of solution \n')
originNumber = number
Reverse = 0
while (number > 0):
Reminder = number % 10
Reverse = (Reverse * 10) + Reminder
number //= 10
print(f"Revers of {originNumber} is {Reverse}")
print('\n............................\n')
print("the third way of solution\n")
number = input("enter number again:")
print(number[::-1])
# Посортувати цифри, що входять в дане число
print(sorted(number))
print('\n............................\n')
# Поміняти між собою значення двох змінних, не використовуючи третьої змінної.
a = input("first var: ")
b = input("second var: ")
# print(f"first var:{a} \nsecond var: {b}")
a, b = b, a
print(f"first var:{a} \nsecond var: {b}")
|
62e85e9955191e8612ad7252c04c248315e3030e | Romko97/Python | /Codawars/06.02.20/Reversing_Words_in_a_String.py | 219 | 4.03125 | 4 | def reverse(st):
st = st.split()
st = st[::-1]
st = ' '.join(st)
return st
def reverse(st):
print(' '.join(st.split()[::-1]))
def reverse(st):
return " ".join(reversed(st.split())).strip()
|
c1cc2522e99d5022a7d680103e1a7c1431aafdf3 | steeju/Free-python-class-with-friends | /DAY 3.py | 1,144 | 3.984375 | 4 | #leap year program
name = int(input("year : "))
if (name%4==0 and name%100!=0) or (name%400==0):
print( name, "is a leap year")
else:
print( name, "not a leap year")
# leap year แต่ไม่ทัน
start = int(input())
end = int(input())
count = 0
for year in range (start, end+1):
if(year%4==0 and year%100!=0) or (year%400==0)
print (year)
count = count + 1 # <- count +1 ไปใส่ใน count
print("total number of leap year = ", count)
#natural number
sum 1 --> input
x = int(input("to which number? "))
sum = 0
for i in range (1, x+1):
#sum = sum + i วิธีล่างเร็วกว่า
sum += i
print (sum)
#sum 1^5 --> input^5
x = int(input("to which number? "))
sum = 0
for i in range (1, x+1):
#sum = sum + i วิธีล่างเร็วกว่า
sum += i**5
print (sum)
#factorial
x = int(input("to which number? "))
product = 1
for i in range (1, x+1):
product *= i
print (product)
#sum 1^n --> input^n
x = int(input("x: "))
n = int(input("n: ))
sum = 0
for i in range (1, x+1)
# sum = sum + i
sum += i**n
print (sum)
#loop
n = 0
while n < 10:
print(n)
|
ce715c678ac816847a3939e61700f50637ef1210 | samcoh/FinalProject206 | /finalproj.py | 39,723 | 3.578125 | 4 | import requests
import json
from bs4 import BeautifulSoup
import sys
import sqlite3
import plotly.plotly as py
import plotly.graph_objs as go
#QUESTIONS:
#1. How to write test cases
#2. Check to see if table okay (list parts)
#3. Joing the table and the data processing for plotly (is okay that i use some part classes)
#4. Does my project add up to enough points
#5. IMDB sometime does not let me do anymore scraping what should i do when this happens? I am afraid to delete my cache because i think if i do the website wont let me collect anymore data
#6. Plotly charts how do i add a title
#------------------LIST OF THINGS TO DO:
#1. Assign theater objects Ids in the class (do this by when inserting theters have own counter )
#2. Instead of grabbing data from movies using name grab it using IDs
num = 0
DBNAME = 'Imdb.sql'
#cache just the html for the sites
CACHE_FNAME = 'cache_theaters.json'
try:
cache_file = open(CACHE_FNAME, 'r')
cache_contents = cache_file.read()
CACHE_DICTION = json.loads(cache_contents)
cache_file.close()
except:
CACHE_DICTION = {}
CACHE = 'cache_movies.json'
try:
cache = open(CACHE, 'r')
contents = cache.read()
CACHE_DICTION_MOVIES = json.loads(contents)
cache.close()
except:
CACHE_DICTION_MOVIES = {}
def params_unique_combination(baseurl):
return baseurl
def cache_theaters(baseurl):
unique_ident = params_unique_combination(baseurl)
if unique_ident in CACHE_DICTION:
return CACHE_DICTION[unique_ident]
else:
resp = requests.get(baseurl)
CACHE_DICTION[unique_ident] = resp.text
dumped_json_cache = json.dumps(CACHE_DICTION)
fw = open(CACHE_FNAME,"w")
fw.write(dumped_json_cache)
fw.close()
return CACHE_DICTION[unique_ident]
def cache_movies(baseurl):
unique_ident = params_unique_combination(baseurl)
if unique_ident in CACHE_DICTION_MOVIES:
return CACHE_DICTION_MOVIES[unique_ident]
else:
resp = requests.get(baseurl)
CACHE_DICTION_MOVIES[unique_ident] = resp.text
dumped_json_cache = json.dumps(CACHE_DICTION_MOVIES)
fw = open(CACHE,"w")
fw.write(dumped_json_cache)
fw.close()
return CACHE_DICTION_MOVIES[unique_ident]
#defined classes
class Theater():
def __init__(self, name, url,street_address,city,state,zip,list_movies):
self.theater_name = name
self.theater_url = url
self.list_movies = list_movies
self.street_address = street_address
self.city = city
self.state = state
self.zip = zip
def __str__(self):
return "{}: {}, {} {}, {}".format(self.theater_name,self.street_address,self.city,self.state,self.zip)
class Movie():
def __init__(self, name, year, time, url, rating, genre, descrip, directors, num_directors, stars, num_stars, more_details_url, gross = "No Gross", weekend="No Opening Weekend Usa", budget="No Budget", cumulative = "No Cumulative Worldwide Gross"):
self.movie_name = name
self.movie_year = year
self.movie_time = time
self.movie_url = url
self.movie_rating = rating
self.movie_genre = str(genre)
self.movie_descrip = descrip
self.movie_directors = str(directors)
self.movie_number_of_directors = num_directors
self.movie_stars = str(stars)
self.movie_number_of_stars = num_stars
self.movie_more_details_url = more_details_url
self.movie_gross_usa = gross
self.movie_opening_weekend_usa = weekend
self.movie_budget = budget
self.movie_worldwide_gross = cumulative
def __str__(self):
return '''{}({})\n\tRating: {} \n\tMinutes: {} \n\tGenre: {} \n\tDirected by: {} \n\tStars: {}\n\tDescription:\n\t\t {}\n\tMONEY:\n\t\t Budget: {}\n\t\t Gross Profit in the USA: {}\n\t\t Opening Weekend in the USA: {}\n\t\t Cumulative Worldwide Gross: {}'''.format(self.movie_name,self.movie_year,self.movie_rating,self.movie_time,self.movie_genre,self.movie_directors,self.movie_stars,self.movie_descrip,self.movie_budget,self.movie_gross_usa,self.movie_opening_weekend_usa, self.movie_worldwide_gross)
#QUESTIONS:
#1. list_movietheaters: ask about not cachining the list of movies because they update everyday
#caching
#can cache list_movietheaters
#movie theaters within 5,10,20,and 30 miles away
def list_movietheaters(zip_code):
zip_code = zip_code
baseurl = "http://www.imdb.com"
url = "http://www.imdb.com/showtimes/location/US/{}".format(zip_code)
#page_text = requests.get(url).text
page_text= cache_theaters(url)
page_soup = BeautifulSoup(page_text, 'html.parser')
content = page_soup.find_all("span", itemprop = "name")
#print(content)
#content = page_soup.find_all("h5", class_ = "li_group")
list_theaters = []
num = 0
for x in content:
theater_name = x.text
theater_link = x.find("a")['href']
full_url = baseurl + theater_link
#uncomment and comment page_text for most recent movie list
# page_text= requests.get(full_url).text
page_text = cache_theaters(full_url)
page_soup = BeautifulSoup(page_text, 'html.parser')
content = page_soup.find_all("div", class_= "info")
movies = []
for y in content:
mov = y.find('h3').text.strip()
list_mov= mov.split("(")
movie_name = list_mov[0]
movies.append(movie_name)
#content = page_soup.find_all(class_= "article listo st")
#content = page_soup.find_all("div", itemtype= "http://schema.org/PostalAddress")
street_address= page_soup.find("span",itemprop="streetAddress").text
city = page_soup.find(itemprop="addressLocality").text
state = page_soup.find(itemprop="addressRegion").text
zip = page_soup.find(itemprop="postalCode").text
class_theaters = Theater(name = theater_name,url =full_url,street_address = street_address,city= city,state= state,zip=zip,list_movies = movies)
list_theaters.append(class_theaters)
# for x in list_theaters:
# movie_information(x)
insert_Theaters(list_theaters,zip_code)
return list_theaters
# content = page_soup.find_all("div", class_= "info")
# for y in content:
# movie_name = y.find('h3').text.strip()
# print(movie_name)
# movies.append(movie_name)
#this function takes in a theater class object
def movie_information(theater_class_object):
baseurl = "http://www.imdb.com"
url = theater_class_object.theater_url
#page_text = requests.get(url).text
page_text = cache_theaters(url)
page_soup = BeautifulSoup(page_text, 'html.parser')
#content= page_soup.find_all("div",class_="description")
#print(content)
content = page_soup.find_all("div", class_= "info")
#content = page_soup.find_all("div",class_="list_item even",itemtype="http://schema.org/Movie")
movies =[]
for y in content:
#movie_name = y.find("span",itemprop= "name").text.strip()
mov = y.find('h3').text.strip()
list_mov= mov.split("(")
movie_name = list_mov[0]
try:
movie_year = list_mov[1][:-1]
except:
movie_year = "No Movie Year"
try:
time = y.find("time",itemprop = "duration").text.strip().split()[0]
except:
time = "No Time"
try:
rating_info = y.find("span", itemprop = "contentRating")
rating = rating_info.find("img")["title"].strip()
except:
rating = "No Rating"
movie_url = y.find('a')['href']
full_url = baseurl + movie_url
page_text = cache_movies(full_url)
page_soup = BeautifulSoup(page_text, 'html.parser')
c = page_soup.find_all("td", class_= "overview-top")
for x in c:
g = x.find_all("span", itemprop = "genre")
genre = []
for s in g:
genre.append(s.text.strip())
descrip = x.find("div", class_="outline", itemprop = "description").text.strip()
d = x.find_all("span", itemprop= "director")
director = []
for f in d:
dir = f.find("a").text.strip()
director.append(dir)
number_of_directors = len(director)
a = x.find_all("span", itemprop = "actors")
stars= []
for actor in a:
act = actor.find("a").text
stars.append(act)
number_of_stars = len(stars)
link = x.find_all("h4",itemprop ="name")
#print(link)
for l in link:
link = l.find("a")['href']
movie_url = baseurl + link
page_text = cache_movies(movie_url)
page_soup = BeautifulSoup(page_text, 'html.parser')
# info = page_soup.find_all("div",class_="article",id="titleDetails")
# for z in info:
detail_info = page_soup.find_all("div",class_= "txt-block")
#print(detail_info)
gross = "No Gross"
weekend = "No Opening Weekend Usa"
budget = "No Budget"
cumulative = "No Cumulative Worldwide Gross"
for detail in detail_info:
try:
d = detail.find("h4",class_= "inline").text.strip()
if d == "Gross USA:":
gross = detail.text.strip()
gross = gross.split()[:3]
#print(gross)
gross= " ".join(gross)[:-1].split()[-1][1:]
#print(gross)
# else:
# gross = "No Gross USA"
#print(gross)
if d == "Opening Weekend USA:":
weekend = detail.text.strip()
weekend = weekend.split()[:4]
weekend =" ".join(weekend)[:-1].split()[-1][1:]
#print(weekend)
# else:
# weekend = "No Opening Weekend USA"
#print(weekend)
if d == "Budget:":
budget = detail.text.strip()
budget = budget.split(":")[1].split("(")[0][1:]
#print(budget)
# else:
# budget = "No Budget"
#print(budget)
if d == "Cumulative Worldwide Gross:":
cumulative = detail.text.strip()
cumulative= cumulative.split()[:4]
cumulative=" ".join(cumulative)[:-1].split()[-1][1:]
except:
#print("except")
continue
mov_object = Movie(name = movie_name, year = movie_year, time = time ,url = full_url, rating = rating, genre = genre, descrip = descrip, directors = director, num_directors = number_of_directors, stars = stars, num_stars = number_of_stars, more_details_url= movie_url, gross = gross, weekend= weekend, budget = budget, cumulative = cumulative)
movies.append(mov_object)
# print(movie_name)
# print(movie_year)
# print(time)
# print(full_url)
# print(descrip)
# print(director)
# print(number_of_directors)
# print(stars)
# print(number_of_stars)
# print(movie_url)
# print(gross)
# print(weekend)
# print(budget)
# print(movies)
insert_Movies(movies,theater_class_object)
return movies
# movies = list_movietheaters("48104")
# mov = movie_information(movies[0])
# for x in mov:
# print(x.movie_budget,x.movie_gross_usa,x.movie_opening_weekend_usa)
# for x in mov:
# print(x.movie_name)
#making the database:
def init_db(db_name):
conn = sqlite3.connect(db_name)
cur = conn.cursor()
statement = '''
DROP TABLE IF EXISTS 'Movies';
'''
cur.execute(statement)
statement = '''
DROP TABLE IF EXISTS 'Theaters';
'''
cur.execute(statement)
conn.commit()
#left out these three from the table:
#self.movie_url = url
#self.movie_descrip = descrip
#self.movie_more_details_url = more_details_url
statement = '''
CREATE TABLE 'Movies' (
'Id' INTEGER PRIMARY KEY AUTOINCREMENT,
'Name' TEXT NOT NULL,
'ReleaseYear' INTEGER,
'Minutes' INTEGER,
'Rating' TEXT,
'Genre' TEXT NOT NULL,
'Directors' TEXT NOT NULL,
'NumberOfDirectors' INTEGER NOT NULL,
'Stars' TEXT NOT NULL,
'NumberOfStars' INTEGER NOT NULL,
'Budget' INTEGER,
'GrossProfitUSA' INTEGER,
'OpeningWeekendUSA' INTEGER,
'CumulativeWorldwideGross' INTEGER
);
'''
cur.execute(statement)
conn.commit()
#self.theater_url = url
statement = '''
CREATE TABLE 'Theaters' (
'Id' INTEGER PRIMARY KEY AUTOINCREMENT,
'EnteredZipCode' TEXT NOT NULL,
'Name' TEXT NOT NULL,
'StreetAddress' TEXT,
'City' TEXT,
'State' TEXT,
'ZipCode' TEXT,
'MoviesPlaying' TEXT
);
'''
cur.execute(statement)
conn.commit()
conn.close()
def insert_Theaters(List_Theater_Objects,zip):
conn = sqlite3.connect(DBNAME)
cur = conn.cursor()
for x in List_Theater_Objects:
Name = x.theater_name
EnteredZipCode = zip
StreetAddress = x.street_address
City = x.city
State = x.state
ZipCode= x.zip
MoviesPlaying = None
insert = (None, EnteredZipCode, Name, StreetAddress,City, State,ZipCode,MoviesPlaying)
statement = 'INSERT INTO Theaters VALUES (?,?,?,?,?,?,?,?)'
cur.execute(statement, insert)
conn.commit()
conn.close()
#update_movies_playing(List_Theater_Objects)
def insert_Movies(List_Movie_Objects,theater_class_object):
conn = sqlite3.connect(DBNAME)
cur = conn.cursor()
movies_in_sql = []
for x in List_Movie_Objects:
Name = x.movie_name
if Name in movies_in_sql:
continue
else:
movies_in_sql.append(Name)
ReleaseYear = x.movie_year
if ReleaseYear == "No Movie Year":
ReleaseYear = None
Minutes = x.movie_time
if Minutes == "No Time":
Minutes = None
Rating = x.movie_rating
if Rating == "No Rating":
Rating = None
Genre = x.movie_genre
Directors = x.movie_directors
NumberOfDirectors = x.movie_number_of_directors
Stars = x.movie_stars
NumberOfStars = x.movie_number_of_stars
Budget = x.movie_budget
if Budget == "No Budget":
Budget = None
GrossProfitUSA = x.movie_gross_usa
if GrossProfitUSA == "No Gross":
GrossProfitUSA = None
OpeningWeekendUSA = x.movie_opening_weekend_usa
if OpeningWeekendUSA == "No Opening Weekend Usa":
OpeningWeekendUSA = None
CumulativeWorldwideGross = x.movie_worldwide_gross
if CumulativeWorldwideGross == "No Cumulative Worldwide Gross":
CumulativeWorldwideGross = None
insert = (None,Name,ReleaseYear,Minutes,Rating,Genre,Directors,NumberOfDirectors,Stars,NumberOfStars,Budget,GrossProfitUSA,OpeningWeekendUSA,CumulativeWorldwideGross)
statement = 'INSERT INTO Movies '
statement += 'VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)'
cur.execute(statement, insert)
conn.commit()
conn.close()
update_movies_playing(theater_class_object)
#get the list of movies from theaters
def update_movies_playing(theater_object):
conn = sqlite3.connect(DBNAME)
cur = conn.cursor()
MoviesPlaying= ""
M = []
MoviesShowing = theater_object.list_movies
theater_name = theater_object.theater_name
for x in MoviesShowing:
statement = '''
SELECT Movies.Id
FROM Movies
WHERE Movies.Name = "{}"
'''.format(x)
cur.execute(statement)
for y in cur:
id_ = str(y[0]) + ','
MoviesPlaying = MoviesPlaying + id_
#MoviesPlaying = MoviesPlaying + str(id_) + ","
#MoviesPlaying.append(str(id_))
M.append(MoviesPlaying[:-1])
update = (M)
statement = '''
UPDATE Theaters
SET MoviesPlaying=?
WHERE Name = '{}'
'''.format(theater_name)
cur.execute(statement,update)
conn.commit()
conn.close()
#init_db(DBNAME)
# movies = list_movietheaters("48104")
# mov = movie_information(movies[0])
#plotly graphs:
#Type: Grouped Bar Chart
#Shows:movie budget compared to cumulative worldwide gross for movies playing at a selected theater
def budget_and_cumulativegross(theater_object):
conn = sqlite3.connect(DBNAME)
cur = conn.cursor()
try:
theater_streetaddress = theater_object.street_address
theater_name = theater_object.theater_name
title = 'Movie Budget Compared to Cumulative Worldwide Gross for Movies Playing at {}'.format(theater_name)
budget = []
worldwide_gross = []
MoviesShowing = []
statement = '''
SELECT MoviesPlaying
FROM Theaters
WHERE Name = "{}" AND StreetAddress = "{}"
LIMIT 1
'''.format(theater_name,theater_streetaddress)
cur.execute(statement)
for x in cur:
movie_ids=x[0]
movie_ids=movie_ids.split(',')
print(movie_ids)
for x in movie_ids:
statement = '''
SELECT Budget,CumulativeWorldwideGross,Name
FROM Movies
WHERE Id = {}
'''.format(x)
cur.execute(statement)
for y in cur:
if y[0] == None and y[1]== None:
continue
elif y[0] == None or y[1]== None:
continue
else:
budget.append(y[0])
worldwide_gross.append(y[1])
MoviesShowing.append(y[2])
trace1 = go.Bar(
x = MoviesShowing,
y = budget,
name = 'Budget'
)
trace2 = go.Bar(
x = MoviesShowing,
y = worldwide_gross,
name = 'Cumulative Worldwide Gross'
)
data = [trace1,trace2]
layout = go.Layout(
title = title,
barmode = 'group',
yaxis=dict(title='Dollars'),
xaxis=dict(title='Movies Playing')
)
fig = go.Figure(data = data, layout= layout)
py.plot(fig, filename = 'Movie Budget Compared to Cumulative Worldwide Gross for Movies Playing')
except:
print("Data not available to make this chart")
# movies = list_movietheaters("48104")
# mov = movie_information(movies[0])
# here =budget_and_cumulativegross(movies[0])
#Type: Bar Chart
#Shows: movie length in minutes for movies playing
def minutes_of_movies(theater_object):
conn = sqlite3.connect(DBNAME)
cur = conn.cursor()
try:
theater_streetaddress = theater_object.street_address
theater_name = theater_object.theater_name
title = 'Movie Length (in Minutes) for Movies Playing at {}'.format(theater_name)
MoviesShowing = []
minutes = []
statement = '''
SELECT MoviesPlaying
FROM Theaters
WHERE Name = "{}" AND StreetAddress = "{}"
LIMIT 1
'''.format(theater_name,theater_streetaddress)
cur.execute(statement)
for x in cur:
movie_ids=x[0]
movie_ids=movie_ids.split(',')
for x in movie_ids:
statement = '''
SELECT Minutes,Name
FROM Movies
WHERE Id = {}
'''.format(x)
cur.execute(statement)
for y in cur:
if y[0] == None:
continue
else:
minutes.append(y[0])
MoviesShowing.append(y[1])
data = [go.Bar(x=MoviesShowing,y= minutes)]
layout = go.Layout(
title = title,
yaxis=dict(title='Length of Movie (Minutes)'),
xaxis = dict(title = "Movies Playing")
)
fig = go.Figure(data = data, layout= layout)
py.plot(fig, filename='Movie Time (Minutes)')
except:
print("Data not avaliable to make this chart")
# movies = list_movietheaters("48104")
# mov = movie_information(movies[0])
# here =minutes_of_movies(movies[0])
#Type: Pie Chart
#Shows: a selected movies' percentage revenue that came from the U.S compared to the percentage that came from the rest of ther world.
def gross_usa_vs_cumulativegross(movie_object):
conn = sqlite3.connect(DBNAME)
cur = conn.cursor()
try:
movie = movie_object.movie_name
title = "{}Movie: Revenue From U.S Compared to Revenue From the Rest of the World".format(movie)
statement = '''
SELECT GrossProfitUSA,CumulativeWorldwideGross
FROM Movies
WHERE Name = "{}"
'''.format(movie)
cur.execute(statement)
for y in cur:
if y[0] == None and y[1]== None:
continue
elif y[0] == None or y[1]== None:
continue
else:
#percent_us = y[1].split(',')/int(y[0].split(',').join()) #U.S percentage
world = y[1].split(',')
usa = y[0].split(',')
percent_us= int("".join(usa))/int("".join(world))
percent_world = 1 - percent_us
fig = {
'data': [{'labels': ["% Revenue From the United States", "% Revenue From the Rest of the World"],
'values': [percent_us, percent_world],
'type': 'pie'}],
'layout': {'title': title}
}
py.plot(fig)
except:
print("Data not avaliable to make this chart")
# init_db(DBNAME)
# movies = list_movietheaters("48104")
# mov = movie_information(movies[0])
# here =gross_usa_vs_cumulativegross(mov[3])
#Type: Scatter Plot
#Shows: movie length (in minutes) compared to movie budget for movies playing
def time_budget(theater_object):
conn = sqlite3.connect(DBNAME)
cur = conn.cursor()
try:
theater_streetaddress = theater_object.street_address
theater_name = theater_object.theater_name
title = 'Length of Movie (minutes) Compared to Movie Budget for Movies Playing at {}'.format(theater_name)
budget = []
minutes = []
MoviesShowing = []
statement = '''
SELECT MoviesPlaying
FROM Theaters
WHERE Name = "{}" AND StreetAddress = "{}"
LIMIT 1
'''.format(theater_name,theater_streetaddress)
cur.execute(statement)
for x in cur:
movie_ids=x[0]
movie_ids=movie_ids.split(',')
for x in movie_ids:
statement = '''
SELECT Budget,Minutes,Name
FROM Movies
WHERE Id = {}
'''.format(x)
cur.execute(statement)
for y in cur:
if y[0] == None and y[1]== None:
continue
elif y[0] == None or y[1]== None:
continue
else:
budget.append(y[0])
minutes.append(y[1])
MoviesShowing.append(y[2])
trace1 = go.Scatter(
x = MoviesShowing,
y = budget,
name = 'Budget'
)
trace2 = go.Scatter(
x = MoviesShowing,
y = minutes,
name = 'Time (minutes)',
yaxis='y2'
)
data = [trace1,trace2]
layout = go.Layout(
title = title,
yaxis=dict(
title='Dollars'
),
yaxis2=dict(
title='Length of Movie (Minutes)',
titlefont=dict(color='rgb(148, 103, 189)'),
tickfont=dict(color='rgb(148, 103, 189)'),
overlaying='y',
side='right'
),
xaxis=dict(title='Movies Playing')
)
fig = go.Figure(data = data, layout= layout)
py.plot(fig, filename = 'Length of Movie Compared to Movie Budget')
except:
print("Data not avaliable to make this chart")
# init_db(DBNAME)
# movies = list_movietheaters("48104")
# mov = movie_information(movies[0])
# here =time_budget(movies[0])
#Type: Grouped Bar Chart
#Shows: Gross Profit Compared to Gross Profit During Opening Weekend in the USA for Movies Playing
def OpeningWeekendUSA_compared_GrossUSA(theater_object):
conn = sqlite3.connect(DBNAME)
cur = conn.cursor()
try:
theater_streetaddress = theater_object.street_address
theater_name = theater_object.theater_name
title = 'Gross Profit Compared to Gross Profit During Opening Weekend in the USA for Movies Playing at {}'.format(theater_name)
openingweekend = []
gross = []
MoviesShowing = []
statement = '''
SELECT MoviesPlaying
FROM Theaters
WHERE Name = "{}" AND StreetAddress = "{}"
LIMIT 1
'''.format(theater_name,theater_streetaddress)
cur.execute(statement)
for x in cur:
movie_ids=x[0]
movie_ids=movie_ids.split(',')
for x in movie_ids:
statement = '''
SELECT GrossProfitUSA,OpeningWeekendUSA,Name
FROM Movies
WHERE Id = {}
'''.format(x)
cur.execute(statement)
for y in cur:
if y[0] == None and y[1]== None:
continue
elif y[0] == None or y[1]== None:
continue
else:
gross.append(y[0])
openingweekend.append(y[1])
MoviesShowing.append(y[2])
trace1 = go.Bar(
x = MoviesShowing,
y = openingweekend,
name = 'Opening Weekend USA'
)
trace2 = go.Bar(
x = MoviesShowing,
y = gross,
name = 'Gross Profit USA'
)
data = [trace1,trace2]
layout = go.Layout(
title = title,
barmode = 'group',
yaxis=dict(title='Dollars'),
xaxis=dict(title='Movies Playing')
)
fig = go.Figure(data = data, layout= layout)
py.plot(fig, filename = 'Gross Profit USA Compared to Opening Weekend USA')
except:
print("Data not avaliable to make this chart")
# init_db(DBNAME)
# movies = list_movietheaters("48104")
# mov = movie_information(movies[0])
# here =OpeningWeekendUSA_compared_GrossUSA(movies[0])
# r=list_movietheaters("60022")
# i=movie_information(r[0])
# gross_usa_vs_cumulativegross(i[2])
#zip #
# theater #
# movie info #
#interactive part
def interactive():
print('Enter "help" at any point to see a list of valid commands')
response = input('Please type in the zipcode command (or "exit" to quit): ')
while response != 'exit':
split_response = response.split()
if split_response[0]== "zip" and len(split_response[1]) == 5:
try:
int(split_response[1])
result = list_movietheaters(split_response[1])
if len(result) == 0:
print("No theaters near the zip code entered.")
response = input('Please type in a valid command (or "help" for more options): ')
if response == "exit":
print("Goodbye!")
continue
print("List of Theaters near {}: ".format(split_response[1]))
num = 0
dic_theaters = {}
length = len(result)
for t in result:
num += 1
string = t.__str__()
dic_theaters[num] = t
if length > 10:
if num == 11:
more_theaters = input("Would you like to see more theater options (type: 'yes' or 'no')?: ")
if more_theaters.lower() == 'yes':
print("{}. {}".format(num,string))
continue
else:
break
print("{}. {}".format(num,string))
except:
response = input('Please type in a valid command (or "help" for more options): ')
if response == "exit":
print("Goodbye!")
continue
elif split_response[0] == "theater":
try:
if int(split_response[1]) not in dic_theaters.keys():
response = input('Please type in a valid command (or "help" for more options): ')
if response == "exit":
print("Goodbye!")
continue
else:
for x in dic_theaters:
if int(split_response[1]) == x:
obj = dic_theaters[x]
results = movie_information(obj)
if len(results) == 0:
print("No movies showing for the theater you selected.")
response = input('Please type in a valid command (or "help" for more options): ')
if response == "exit":
print("Goodbye!")
continue
dic_movies_playing = {}
num = 0
print("List of Movies Playing at {}: ".format(obj.theater_name))
for x in results:
num += 1
string = x.movie_name
dic_movies_playing[num]= x
print("{}. {}".format(num, string))
graph = input('Would you like to see a graph of movie budget compared to cumulative worldwide gross ("yes or "no")?: ')
graph2 = input('Would you like to see a graph of movie time ("yes or "no")?: ')
graph3 = input('Would you like to see a graph of movie budget compared to movie length ("yes or "no")?:')
graph5 = input('Would you like to see a graph of Gross Profit USA compared Opening Weekend USA ("yes or "no")?:')
if graph.lower() == "yes":
budget_and_cumulativegross(obj)
if graph2.lower() == "yes":
minutes_of_movies(obj)
if graph3.lower() == "yes":
time_budget(obj)
if graph5.lower() == "yes":
OpeningWeekendUSA_compared_GrossUSA(obj)
except:
response = input('Please type in a valid command (or "help" for more options): ')
if response == "exit":
print("Goodbye!")
continue
#graph = input('Would you like to see a graph of movie budget compared to cumulative worldwide gross("yes or "no" )?: ')
elif split_response[0] == "movie" and split_response[1] == "info":
try:
if int(split_response[2]) not in dic_movies_playing.keys():
response = input('Please type in a valid command (or "help" for more options): ')
if response == "exit":
print("Goodbye!")
continue
for x in dic_movies_playing:
if x == int(split_response[2]):
movie_obj = dic_movies_playing[x]
print(movie_obj)
graph4 = input('Would you like to see a graph that compares revenue from the U.S versus the rest of the world ("yes" or "no")?: ')
if graph4.lower() == "yes":
gross_usa_vs_cumulativegross(movie_obj)
except:
response = input('Please type in a valid command (or "help" for more options): ')
if response == "exit":
print("Goodbye!")
continue
elif "help" == response:
print("\tzip <zipcode>")
print("\t\t available anytime")
print("\t\tlists all theaters between 5 and 30 miles away from the zipcode entered")
print("\t\tvalid inputs: a 5 digit zip code")
print("\ttheater <result_number>")
print("\t\tavailable only if there is an active result set (a list of theaters near a zipcode specified)")
print("\t\tlists all movies showing at the theater selected")
print("\t\tvalid inputs: an integer 1-len (result_set_size)")
print("\tmovie info <result_number>")
print("\t\tavailable only if there is an active result set (a list of movies showing at a specified theater)")
print("\t\tshows further information about the movie selected")
print("\t\tvalid inputs: an integer 1-len (result_set_size)")
print("\texit")
print("\t\texits the program")
print("\thelp")
print("\t\tlists available commands (these instructions)")
else:
response = input('Please type in a valid command (or "help" for more options): ')
if response == "exit":
print("Goodbye!")
continue
response = input('Please type in a command (or "exit" to quit): ')
if response == "exit":
print("Goodbye!")
continue
# try:
# if response != "help":
# response = int(response)
# except:
# response = input('Please type in a valid command (or "help" for more options): ')
# if response == "exit":
# print("Goodbye!")
# continue
# if len(str(response)) == 5:
# result = list_movietheaters(response)
# print("List of Theaters near {}: ".format(response))
# num = 0
# dic_theaters = {}
# length = len(result)
# for t in result:
# num += 1
# string = t.__str__()
# dic_theaters[num] = t
# if length > 10:
# if num == 11:
# more_theaters = input("Would you like to see more theater options (type: 'yes' or 'no')?: ")
# if more_theaters.lower() == 'yes':
# print("{}. {}".format(num,string))
# continue
# else:
# break
# print("{}. {}".format(num,string))
# elif len(str(response)) < 5:
# if response not in dic_theaters.keys():
# response = input('Please type in a valid command (or "help" for more options): ')
# if response == "exit":
# print("Goodbye!")
# continue
# else:
# for x in dic_theaters:
# if response == x:
# obj = dic_theaters[x]
# results = movie_information(obj)
# dic_movies_playing = {}
# num = 0
# print("List of Movies Playing at {}: ".format(obj.theater_name))
# for x in results:
# num += 1
# string = x.movie_name
# dic_movies_playing[num]= x
# print("{}. {}".format(num, string))
# if int(response) not in dic_movies_playing.keys():
# response = input('Please type in a valid command (or "help" for more options): ')
# if response == "exit":
# print("Goodbye!")
# continue
# for x in dic_movies_playing:
# if x == int(response):
# movie_obj = dic_movies_playing[x]
# print(movie_obj)
# response = input('Type in a number to see more information about a movie (or help for more options): ')
# try:
# int(response)
# except:
# if response == "exit":
# print("Goodbye!")
# continue
# else:
# response = input('Please type in a valid command (or "help" for more options): ')
# if response == "exit":
# print("Goodbye!")
# continue
#response = input('Please type in a zipcode (or exit to escape): ')
#commands:
#zip <type zip code>
#theater <type number>
#movie <type number>
# if response == "exit":
# print("Goodbye!")
# continue
# elif response == "help":
# continue
# elif len(str(response)) == 5:
# continue
# elif type(response) == type(""):
# try:
# response = int(response)
# except:
# response input('Please enter a valid command (or "help" for more options): ')
# continue
# try:
# response = int(response)
# except:
# response = input('Please enter a valid zipcode (or exit to escape): ')
# if response == "exit":
# print("Goodbye!")
# continue
# if response == 'help':
# response = input('Enter a command: ')
# continue
# pass
# if
#table 1: theaters
#table 2: movies
#theaters column movies contain a string ('1,2,3,4,5,6,7,')
#theaters playing this list of movies
#str.split(',') get movie info for all those
#movies tables do need any information on what movies are playing
#movies can delete everytime it runs keep the theater cache
#print theaters near zipcode
#then they pick a theater number and tells the movies
#they can pick a movie number and it tells the movies
#pie chart showing the ratings for the movie
#release month (how long specific movies are in theaters) --> time line graph (or you can do gross sales ---> distribution of gross sales per movie per theater)
#-------------------------------------------------------
#table 1:movies
#join on movie titles or movie directors
#table 2: theaters and zip codes column for list of movies
#theaters table: id, zip code, address, movies list
#just keep adding them to the database
#can just use the cache data
#tables all the movie information
#join on the movies playing at that theater
#movie theaters id
#table 1: theaters, autoincriment unique id
#cant multiple theaters show the same movie
#movies: column with theater id
#movie id as a foreign key in the theater table
#beautiful soup documentation
#interactive part
if __name__ == '__main__':
# movies = list_movietheaters("48104")
# mov = movie_information(movies[0])
init_db(DBNAME)
interactive()
#result=list_movietheaters("60022")
#b = budget_and_cumulativegross(result[0])
#print(b)
# user = input("Enter a zipcode in the United States: ")
# while user != "exit":
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.