blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
802e62944bf143d5d26859802dcb3d425d989795 | theredferny/CodeCademy_Learn_Python_3 | /Unit_10-Classes/10_02_06-Polymorphism.py | 416 | 3.9375 | 4 | """
we want to implement forms that are familiar in our programs so that usage is expected.
Polymorphism is the term used to describe the same syntax (like the + operator here, but it could be a method name)
doing different actions depending on the type of data.
"""
a_list = [1, 18, 32, 12]
a_dict = {'value': True}
a_string = "Polymorphism is cool!"
print(len(a_list))
print(len(a_dict))
print(len(a_string))
|
1eb12471bed3eba77285802e1241a7e7a01c8a05 | visweswar299/_291862_python | /Dictionary.py | 7,072 | 4.53125 | 5 | '''
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and does not allow duplicates.
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.
Dictionaries are written with curly brackets, and have keys and values.
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.
'''
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
print(thisdict["brand"])
#Dictionaries cannot have two items with the same key:
#Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
print(len(thisdict))
#String, int, boolean, and list data types:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
print(type(thisdict))
#You can access the items of a dictionary by referring to its key name, inside square brackets
#Get the value of the "model" key:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
x = thisdict.get("model")
print(x)
#The keys() method will return a list of all the keys in the dictionary.
x = thisdict.keys()
print(x)
#The list of the keys is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the keys list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
#The values() method will return a list of all the values in the dictionary.
x = thisdict.values()
print(x)
#The list of the values is a view of the dictionary, meaning that any changes done to the dictionary will be reflected in the values list.
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
#The items() method will return each item in a dictionary, as tuples in a list.
x = thisdict.items()
print(x)
#Check if Key Exists
#To determine if a specified key is present in a dictionary use the in keyword:
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
#change values
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
print(thisdict)
#Update the "year" of the car by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
print(thisdict)
#Adding items
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
'''
The update() method will update the dictionary with the items from a given argument. If the item does not exist, the item will be added.
The argument must be a dictionary, or an iterable object with key:value pairs.
'''
#Add a color item to the dictionary by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})
print(thisdict)
#remove items
#There are several methods to remove items from a dictionary:
#The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
#The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
#The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
#The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
#print(thisdict) #this will cause an error because "thisdict" no longer exists.
#The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
#loop
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
#Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
#Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
#You can also use the values() method to return values of a dictionary:
for x in thisdict.values():
print(x)
#You can use the keys() method to return the keys of a dictionary:
for x in thisdict.keys():
print(x)
#Loop through both keys and values, by using the items() method:
for x, y in thisdict.items():
print(x, y)
'''
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
'''
#Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
#Make a copy of a dictionary with the dict() function:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
#Nested Dictionaries
#A dictionary can contain dictionaries, this is called nested dictionaries.
#Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
#another way
#Create three dictionaries, then create one dictionary that will contain the other three dictionaries:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
print(myfamily)
'''
Dictionary Methods:
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
''' |
00ee46a4e7dfccb24d37bf47392fa1ab5c36ff89 | wangyongk/scrapy_toturial | /Pythonproject/matplotlib/4_柱状图.py | 344 | 3.546875 | 4 | import matplotlib.pyplot as plt
num_list = [1.5, 0.6, 7.8, 6]
num_list = [1.5,0.6,7.8,6]
num_list = [1.5,0.6,7.8,6]
#plt.bar(range(len(num_list)), num_list,fc='r')
#设置颜色 fc='r'
name_list = ['Monday', 'Tuesday', 'Friday', 'Sunday']
plt.bar(range(len(num_list)), num_list,color='rgbr')
#设置颜色 color='rgbr'
plt.show() |
9f9fe3a7db69cf56e7e0133b1c53338b1e5a412b | CodecoolKRK20173/erp-mvc-hania-szymon | /model/common.py | 1,540 | 3.671875 | 4 | """ Common functions for models
implement commonly used functions here
"""
import datetime
import random
def generate_random(table):
"""
Generates random and unique string. Used for id/key generation:
- at least 2 special characters (except: ';'), 2 number, 2 lower and 2 upper case letter
- it must be unique in the table (first value in every row is the id)
Args:
table (list): Data table to work on. First columns containing the keys.
Returns:
string: Random and unique string
"""
generated = ''
list_of_keys = []
id_part1, id_part_2, id_part3, id_part4 = '', '' , '', ''
letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
special_characters = '!@#$%^&*()?'
numbers = '1234567890'
for i in range(len(table)):
list_of_keys.append(table[i][0])
#print(list_of_keys)
id_part1 = id_part1 + random.choice(letters) + random.choice(letters)
id_part_2 = id_part_2 + random.choice(special_characters) + random.choice(special_characters)
id_part3 = id_part3 + random.choice(numbers) + random.choice(numbers)
id_part4 = id_part4 + random.choice(letters) + random.choice(letters)
generated = generated + id_part1 + id_part3 + id_part4 + id_part_2
while generated in list_of_keys:
generated = generated + id_part1 + id_part3 + id_part1 + id_part_2
# your code
return generated
def convert_to_date (year,month, day):
date = datetime.date(year, month, day)
return date |
0fa55a495df5fb44466fa0bce59468570226cd93 | CodingGearsCourses/PythonProgrammingFundamentals | /Module-05-Conditional-Statements-Loops/02-while-statement-02.py | 155 | 3.9375 | 4 | # while statement basics
x = 0
while x <= 12:
print('I am inside the while loop : ' + str(x))
if x == 5:
print("Hey! Found 5!")
x += 1 |
c5b02b97c630fd03df6feac8d39cf5ce5c8b2d88 | ototlvg/python-study | /python_sandbox_starter/strings.py | 2,549 | 4.46875 | 4 | # Strings in python are surrounded by either single or double quotation marks. Let's look at string formatting and some string methods
name = 'Jason'
age = 37
# Concatenate
# print('Hello my name is ' + name) -- Se concatena igual que en Js
# print('Hello my name is' + name + 'and I am' + age) # -- Esto retorna un error, ya que solo se pueden concatenar strings, no tiene autocast al parecer
print('1. Hello my name is ' + name + ' and I am ' + str(age)) # Debemos de hacer el cast de forma manual, y ahi si funcionara
# String Formatting
# Arugments by position
'''
Esta forma es como en C, se ponen 'placeholders' dentro del string
y por fuera usando la funcion 'format()' se especifican las
variables de los placeholders ({name},{age})
'''
print('2. My name is {name} and I am {age}'.format(name=name,age=age))
# F-Strings (Python V3.6+)
'''
Es como en JS, solo que en vez de poner `` (comillas inversas, 'backtips')
se pone una f al principio y no se usa el simbolo de dolar $
'''
print(f'3. Hello 2, my name is {name} and I am {age}')
# String Methods
s = 'hello world'
# Capitalize string
print(s.capitalize()) # Solo la primera letra es afectada NO todo el string
# Make all uppercase
print(s.upper())
# Make all lower
print(s.lower())
# Swap case - Las mayusculas las pasa a minusculas y las mayusculas a minusculas
sc= 'HeLLo WoRlD'
print('Swap case: ' + sc.swapcase())
# Get length
'''
This length is a function can be used on string, list, vectors,
basic any data type and is gonna get the lenght
'''
print(len(s))
# Replace
'''
Reempleza todas las palabras del primer argumento, por la palabra
del segundo argumento
'''
print(s.replace('world', 'everyone'))
# Count
'''
Retorna cuantas letras hay en el string especificado en el
argumento
'''
# print('Count:')
sub = 'h'
print(s.count(sub))
# Starts with
'''
Pregunta si el string empieza con lo que se pone en el argumento
'''
print(s.startswith('hello'))
# Ends with
'''
Pregunta si el string termina con lo que se pone en el argumento
'''
print(s.endswith('d'))
# Split into a list
'''
Al parecer una lista es un array, separa las letras en un array
'''
print(s.split())
# Find position
'''
Encuentra la posicion de un caracter (el primero que encuentre)
'''
print(s.find('r'))
# Is all alphanumeric -- return boolean, retorna false por el espacio -- FALTA INVESTIGAR MAS
print(s.isalnum())
# Is all alphabetic -- return boolean, retorna false por el espacio -- FALTA INVESTIGAR MAS
print(s.isalpha())
# Is all numeric -- return boolean
print(s.isnumeric()) |
9d46e1a4351ce97763c732d71d5c2fef7b22d4a7 | johnemurphy1/PythonProjects | /SpiralRosettes.py | 1,248 | 4.3125 | 4 | import turtle
t = turtle.Pen()
t.penup()
turtle.bgcolor("black")
# Ask the user for the number of sides, default to 4, min 2, max 6
sides = int(turtle.numinput("Number of sides", "How many sides in your spiral of spirals? (2-6)", 4,2,6))
colors = ['red', 'yellow', 'blue', 'green', 'purple', 'orange']
number_of_circles = int(turtle.numinput("Number of circles", "How many circles in your rosette?",6))
# Our outer spiral loop
for m in range(100):
t.forward(m*4)
position = t.position()#Remember this corner of the spiral
heading = t.heading()#Remember the direction we are heading
#print(position, heading)
#Our "inner" spiral loop
#Draws a little spiral at each corner of the big spiral
for x in range(sides):
t.pendown()
t.pencolor(colors[x%sides])
t.forward(x*4)
t.circle(m/5)
t.right(360/sides-2)
t.width(m/20)
t.penup()
t.setx(position[0]) #Go back to the big spiral's x location
t.sety(position[1]) #Go back to the big spiral's y location
t.setheading(heading) #Point in the big spiral's heading
t.left(360/sides + 2) #Aim at the next point of the big spiral
|
a68b2a4fb729494e884993d6430cecf3c7592216 | piyushjha7/Files | /even_odd_count.py | 309 | 4.0625 | 4 | n = int(input("Enter your number:"))
even_count = 0
odd_count = 0
for i in range(1,n+1):
if i % 2 == 0:
even_count= even_count+1
print(i)
else:
odd_count= odd_count+1
print(i)
print("Even numbers:{}". format (even_count))
print("Odd numbers:{}". format (odd_count))
|
c905be982b8675d07e2b9e37f6e1bf0023f19ef8 | pfuntner/fun | /resub | 610 | 3.609375 | 4 | #! /usr/bin/env python2
import re
import argparse
parser = argparse.ArgumentParser()
# parser.add_argument('pattern', help='A regular expression pattern')
parser.add_argument('replacement', help='Replacement string')
parser.add_argument('haystack', metavar='string', help='Original string to search')
args = parser.parse_args()
pattern = 'PASSW(?:OR)?D[\'"]?[ :\t=]*(?:(?:u?[\'"])?)([-a-zA-Z0-9!@#$%^&*()_+=[\]\\|;:,./<>?]+)'
match = re.search(pattern, args.haystack, flags=re.IGNORECASE)
print match.groups() if match else None
print re.sub(pattern, args.replacement, args.haystack, flags=re.IGNORECASE)
|
37ab284640a8e4903f8b2792c1f8db7983e7ddaf | zhoushuaiandrew981112/cpe_202_pset5 | /pset5.py | 7,775 | 3.640625 | 4 | # Name: Zhoushuai (Andrew) Wu
# Course: CPE 202
# Instructor: Daniel Kauffman
# Assignment: Pset 5: Binary Search Tree
# Term: Summer 2018
class TreeNode:
def __init__(self, key, val = None, parent = None, \
l_child = None, r_child = None):
self.key = key
self.val = val
self.parent = parent
self.l_child = l_child
self.r_child = r_child
def is_leaf(self):
return self.l_child == None and self.r_child == None
def has_parent(self):
return self.parent != None
def has_l_child(self):
return self.l_child != None
def has_r_child(self):
return self.r_child != None
def has_one_child(self):
if self.has_l_child() and self.has_r_child():
return False
elif not self.has_l_child() and not self.has_r_child():
return False
return True
def is_l_child(self):
if self.parent == None:
return False
return self == self.parent.l_child
def is_r_child(self):
if self.parent == None:
return False
return self == self.parent.r_child
def replace_node_data(self, key, val, l_child, r_child):
self.key = key
self.val = val
self.l_child = l_child
self.r_child = r_child
if self.has_l_child():
self.l_child.parent = self
if self.has_r_child():
self.r_child.parent = self
class BinarySearchTree:
def __init__(self, key = None, val = None):
if key == None:
self.root = None
else:
self.root = TreeNode(key, val)
def insert_helper(self, key, val, current):
if key <= current.key:
if current.has_l_child():
self.insert_helper(key, val, current.l_child)
else:
current.l_child = TreeNode(key, val, current)
elif key > current.key:
if current.has_r_child():
self.insert_helper(key, val, current.r_child)
else:
current.r_child = TreeNode(key, val, current)
def insert(self, key, val):
if self.root == None:
self.root = TreeNode(key, val)
else:
self.insert_helper(key, val, self.root)
def get(self, current, key):
if current == None:
return None
elif current.key == key:
return current
elif current.key < key:
return self.get(current.r_child, key)
elif current.key > key:
return self.get(current.l_child, key)
def find_succ(self, t_node):
succ = None
if t_node.has_r_child():
succ = t_node.r_child
while succ.has_l_child():
succ = succ.l_child
else:
if t_node.parent != None:
if t_node.is_l_child():
succ = t_node.parent
else:
t_node.parent.r_child = None
succ = self.find_succ(t_node.parent)
t_node.parent.r_child = t_node
return succ
def splice_out(self, succ):
if succ.is_leaf():
if succ.is_l_child():
succ.parent.l_child = None
else:
succ.parent.r_child = None
elif succ.l_child != None or succ.r_child != None:
if self.has_l_child():
if succ.is_l_child():
succ.parent.l_child = succ.l_child
else:
succ.parent.r_child = succ.l_child
succ.l_child.parent = succ.parent
else:
if succ.is_l_child():
succ.parent.l_child = succ.r_child
else:
succ.parent.r_child = self.r_child
succ.r_child.parent = succ.parent
def remove_if_is_leaf(self, t_node):
if t_node.is_l_child():
t_node.parent.l_child = None
else:
t_node.parent.r_child = None
def remove_has_l_child(self, t_node):
if t_node.is_l_child():
t_node.l_child.parent = t_node.parent
t_node.parent.l_child = t_node.l_child
elif t_node.is_r_child():
t_node.l_child.parent = t_node.parent
t_node.parent.r_child = t_node.l_child
else:
t_node.replace_node_data(t_node.l_child.key, t_node.l_child.val, \
t_node.l_child.l_child, t_node.l_child.r_child)
def remove_has_r_child(self, t_node):
if t_node.is_l_child():
t_node.r_child.parent = t_node.parent
t_node.parent.l_child = t_node.r_child
elif t_node.is_r_child():
t_node.r_child.parent = t_node.parent
t_node.parent.r_child = t_node.r_child
else:
t_node.replace_node_data(t_node.r_child.key, t_node.r_child.val, \
t_node.r_child.l_child, t_node.r_child.r_child)
def remove_has_one_child(self, t_node):
if t_node.has_l_child():
self.remove_has_l_child(t_node)
elif t_node.has_r_child():
self.remove_has_r_child(t_node)
def remove_has_both_children(self, t_node):
succ = self.find_succ(t_node)
self.splice_out(succ)
t_node.key = succ.key
t_node.val = succ.val
def remove(self, t_node):
if t_node.is_leaf():
self.remove_if_is_leaf(t_node)
elif t_node.has_one_child():
self.remove_has_one_child(t_node)
else:
self.remove_has_both_children(t_node)
def delete(self, key):
if self.root.l_child == None and self.root.r_child == None:
self.root = None
elif self.root != None:
t_node = self.get(self.root, key)
if t_node != None:
self.remove(t_node)
def contains_helper(self, node, key):
if node == None:
return False
elif node.key == key:
return True
elif node.key < key:
return self.contains_helper(node.r_child, key)
elif node.key > key:
return self.contains_helper(node.l_child, key)
def contains(self, key):
node = self.root
return self.contains_helper(node, key)
def find_min(self):
current = self.root
while current.has_l_child():
current = current.l_child
return current
def find_max(self):
current = self.root
while current.has_r_child():
current = current.r_child
return current
def inorder_list(self):
def inorder_helper(node):
if node == None:
return []
lst_left = inorder_helper(node.l_child)
lst_mid = [node.key]
lst_right = inorder_helper(node.r_child)
return lst_left + lst_mid + lst_right
return inorder_helper(self.root)
def preorder_list(self):
def preorder_helper(node):
if node == None:
return []
lst_left = preorder_helper(node.l_child)
lst_mid = [node.key]
lst_right = preorder_helper(node.r_child)
return lst_mid + lst_left + lst_right
return preorder_helper(self.root)
def postorder_list(self):
def postorder_helper(node):
if node == None:
return []
lst_left = postorder_helper(node.l_child)
lst_mid = [node.key]
lst_right = postorder_helper(node.r_child)
return lst_left + lst_right + lst_mid
return postorder_helper(self.root)
|
daad5cd55a600875d77b054c4e9f96b305a1022b | moragbl/checkio | /threewords.py | 653 | 4.1875 | 4 | #!/usr/bin/python
def checkio(words):
#split words on whitespace
ThreeWords = False
word_list = words.split()
count = 0
for word in word_list:
if any(i.isdigit() for i in word):
count = 0
else:
count +=1
if count >= 3:
ThreeWords = True
return ThreeWords
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio("Hello World hello") == True, "Hello"
assert checkio("He is 123 man") == False, "123 man"
assert checkio("1 2 3 4") == False, "Digits"
assert checkio("bla bla bla bla") == True, "Bla Bla"
assert checkio("Hi") == False, "Hi"
|
d47963f801cd6f0488018bd21b64f9fb8d7bdd0e | Wehzie/Bachelor-Thesis-Data-Democracy | /src/gov_rep.py | 4,454 | 3.875 | 4 |
class Gov_rep(object):
'''
This government models a representative democracy with a party system.
Each month all households are income taxed with a single tax rate.
Each month all households receive a universal basic income.
Each month all money that is collected from taxes is spent on ubi.
Each term the government's parliamentary composition changes.
'''
def __init__(self, sim: object):
self.sim = sim # link government to the simulation
self.money = 0 # money available to government for redistribution
self.tax_rate = 0 # taxes are collected each month based on income and taxrate
self.ubi = 0 # ubi paid to each hh monthly
self.parties = [0] * self.sim.g_param['rep_num_parties'] # holds parliamentary composition in percentages per party
# the left most party in the list represents the poorest households
######## ######## ######## METHODS ######## ######## ########
# each term a new government is elected in the form of a parliamentary composition
def assemble_parliament(self):
hh_i_sort = sorted(self.sim.hh_list, key=lambda hh: hh.income) # sort households by income
num_p = self.sim.g_param['rep_num_parties']
# integrate over households income
integral = [0]
for hh in hh_i_sort:
integral.append(hh.income + integral[-1])
norm = [i / integral[-1] for i in integral] # normalize integral
x = list(range(0, len(norm))) # list with number of points in integral
x = [i /(len(x)-1) for i in x] # normalize list
# Given (x, norm) income_dist(0.2) returns the % of income is received by the poorest 20% of households
# Given (norm, x) income_dist(0.2) returns the % of households receiving the leftmost 20% of income
income_dist = interp1d(norm, x, kind='linear') # interpolate income distribution for integrated incomes
self.parties = []
step = 1 / num_p
for i in range(1, num_p+1):
self.parties.append(round(float(income_dist(step * i) - income_dist(step * (i-1))), 2))
# households vote for a party based on income
# party size follows income distribution
# for example, when the left most 20% of income is received by the poorest 60% of households their party has 60% weight
# poor party votes for highest taxes, the rich party for the lowest taxes
def vote_tax(self):
taf = self.sim.g_param['tax_adj_freq'] # tax adjustment frequency
# only tax households once enough data is available
if len(self.sim.stat.hh_stat['metric']['gini_i']) < taf:
self.tax_rate = 0
return
# only vote for a new tax rate when it's the first month of a year
if self.sim.current_month % taf != 0:
return
# first government established after one year has passed
# only elect a new government once a term has passed
if (self.sim.current_month - taf) % self.sim.g_param['rep_term_length'] == 0:
self.assemble_parliament()
# mean gini index of the past tax_adj_freq months
g_list = self.sim.stat.hh_stat['metric']['gini_i'][-taf:]
m_gini = sum(g_list) / len(g_list)
# calculate tax
self.tax_rate = 0
gamma = self.sim.g_param['tax_gamma'] # maximum gamma value
gamma_step = gamma / (self.sim.g_param['rep_num_parties']-1) # stepwise decrease of gamma per party
for p in self.parties:
self.tax_rate += (1 - (1 + m_gini)**-gamma) * p
gamma -= gamma_step
# collect taxes from all households each month
def collect_tax(self):
for hh in self.sim.hh_list:
self.money += hh.pay_tax(self.tax_rate)
# ubi is equal for all hhs each month
def calc_ubi(self):
self.ubi = self.money / self.sim.hh_param['num_hh']
# pay equal ubi to all households each month
def pay_ubi(self):
for hh in self.sim.hh_list:
hh.receive_ubi(self.ubi)
self.money = 0
######## ######## ######## IMPORTS ######## ######## ########
from simulation import Simulation
import random
from scipy.interpolate import interp1d
|
e9bda99dc0dafcd01600f8b29948da4c426da2d4 | brasqo/pythoncrashcourse | /users.py | 1,217 | 4.28125 | 4 | # users
# user0 = {
# 'username': 'efermi',
# 'first': 'enrico',
# 'last': 'fermi',
# }
# for key, value in user0.items():
# print("\nKey: " + key)
# print("Value: " + value)
#---
favelanguage = {
'jen':'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
#----
# for name, language in favelanguage.items():
# print(name.title()+ "'s favorite launguage is " +
# language.title() + ".")
# for name1 in favelanguage.keys():
# print(name1.title())
#---
friends = ['phil', 'sarah']
for name2 in favelanguage.keys():
print(name2.title())
if name2 in friends:
print(" Hi " + name2.title() +
", I see your favorite launguage is " +
favelanguage[name2].title() + "!")
if 'erin' not in favelanguage.keys():
print("Erin, please take our poll!")
#-- looping thru dictionarys keys in order.
for name3 in sorted(favelanguage.keys()):
print(name3.title() + ", thank you for taking the poll.")
#-- looping thru all values in a dictionary
print("The following languages have been mentioned:")
#-- prints in a set (no duplicate values)
for language1 in set(favelanguage.values()):
# doesnt print as set)
# for language1 in favelanguage.values():
print(language1.title())
|
b6cfc6848a510e47c0cf92fd347b1145d0606aac | skunz42/CS480K-Final-Project | /src/config/fetchstores.py | 6,732 | 3.546875 | 4 | import googlemaps
import json
import urllib
import sys
import csv
from pymongo import MongoClient
'''***********************************************
findPlace
purpose:
gets json data from google search
params:
lat - represents latitude
lng - represents longitude
radius - represents search radius
kw - represents search word (ie grocery)
key - API authentication key
return:
jSonData - returns search in json format
***********************************************'''
def findPlace(lat, lng, radius, kw, key):
#making the url
AUTH_KEY = key #authentication key
LOCATION = str(lat) + "," + str(lng) #location for url
RADIUS = radius
KEYWORD = kw #search word
MyUrl = ('https://maps.googleapis.com/maps/api/place/nearbysearch/json'
'?location=%s'
'&radius=%s'
'&keyword=%s'
'&sensor=false&key=%s') % (LOCATION, RADIUS, KEYWORD, AUTH_KEY) #url for search term
#grabbing the JSON result
response = urllib.request.urlopen(MyUrl)
jsonRaw = response.read()
jsonData = json.loads(jsonRaw)
return jsonData
'''***********************************************
IterJson
purpose:
returns array of data parsed from search
request
params:
place - jSonData retreived from search
return:
array of parsed data
***********************************************'''
def IterJson(place):
x = {
"Name": place['name'],
"ID": place['reference'],
"Latitude": place['geometry']['location']['lat'],
"Longitude": place['geometry']['location']['lng'],
"Address": place['vicinity'],
"Rating": place['rating'],
"Num Ratings": place['user_ratings_total']
}
return x
'''***********************************************
calcCoords
purpose:
calculates the coordinates to use when
searching. Updates an array of tuples
storing coordinates
params:
key - API authentication key
coords - array of coordinates
city - city being searched
return:
None
***********************************************'''
def calcCoords(key, coords, city):
gmaps = googlemaps.Client(key=key) #authentication
geocode_result = gmaps.geocode(city) #gets results for city
nelat = geocode_result[0]['geometry']['bounds']['northeast']['lat'] #northeast latitude
nelng = geocode_result[0]['geometry']['bounds']['northeast']['lng'] #northeast longitude
swlat = geocode_result[0]['geometry']['bounds']['southwest']['lat'] #southwest latitude
swlng = geocode_result[0]['geometry']['bounds']['southwest']['lng'] #southwest longitude
km = 0.015
templat = swlat #latitude and longitude used for calculation purposes
templng = swlng
while (templat <= nelat): #north/south calc
while (templng <= nelng): #east/west calc
coords.append((templat, templng))
templng += km # ~ 1 km
templng = swlng
templat += km # ~ 1 km
'''***********************************************
writeCSV
purpose:
write data to csv
params:
places - list of grocery store dictionaries
fn - filename
city - city name
return:
None
***********************************************'''
def writeCSV(places, fn, city):
minRatings = 30
with open(fn, mode = 'w', newline = '') as csv_test:
csv_writer = csv.writer(csv_test, delimiter = ',', quotechar = '"', quoting = csv.QUOTE_MINIMAL)
for p in places: # parse extraneous stores and spam entries and dollar stores
if city in p['Address'] and int(p['Num Ratings']) > minRatings and "Dollar" not in p['Name']:
csv_writer.writerow([p['ID'], p['Name'], p['Latitude'], p['Longitude'], p['Address'], p['Rating'], p['Num Ratings']])
'''***********************************************
writeDB
purpose:
write data to DB
params:
places - dict of grocery stores
citystate - name of city that is being analyzed
return:
None
***********************************************'''
def writeDB(places, citystate):
client = MongoClient(port=27017)
db = client.CS432FP
city = citystate[:len(citystate)-4] # gets city name
state = citystate[len(citystate)-2:] #gets state abbreviation
minRatings = 30
for p in places:
if city in p['Address'] and int(p['Num Ratings']) > minRatings and "Dollar" not in p['Name']:
store = {
'ID': p['ID'],
'Name' : p['Name'],
'City' : city,
'State' : state,
'Latitude': p['Latitude'],
'Longitude' : p['Longitude'],
'Address' : p['Address'],
'Rating' : p['Rating'],
'Num_Ratings' : p['Num Ratings'],
'File Location' : "../" + city + "" + state
}
db.storeinfo.update({'_id':p['ID']}, store, upsert=True)
print("Inserted documents")
print(db.storeinfo.count())
'''***********************************************
scrapeData
purpose:
creates set of data
parameters:
fn - filename
citystate - city + state for scraping
city - city name for csv writing
return:
None
***********************************************'''
def scrapeData(fn, citystate, city):
credsfile = open("../../Geo-Credentials/creds.txt", "r")
keyval = credsfile.read()
coords = []
calcCoords(keyval, coords, citystate)
gplaces = []
for c in coords:
gsearch = findPlace(c[0], c[1], 1000, 'grocery', keyval)
if gsearch['status'] == 'OK':
for place in gsearch['results']:
storeInfo = IterJson(place)
gplaces.append(storeInfo)
writeCSV(list({v['ID']:v for v in gplaces}.values()), fn, city) # insert unique elements into dictionary and make it a list
# include call to writeDB
writeDB(list({v['ID']:v for v in gplaces}.values()), citystate)
'''***********************************************
Main
***********************************************'''
def main():
numArgs = 4
if (len(sys.argv) != numArgs):
print("Please input in the following format: python fetchstores.py <file> <city> <state abbrev>")
return 1
fn = "../DataFiles/" + str(sys.argv[1]) + ".csv"
city = str(sys.argv[2])
state = str(sys.argv[3])
citystate = city + ", " + state
scrapeData(fn, citystate, city)
main()
|
b50f7522bd35bf4f5d6ebc3f055a3d5233d7749c | ecotyper/quant_econ_with_python | /0. quant_econ_with_py_codes/0. Basic Knowledge of Economic with Python/Chapter3_Codes/Ch3_Code.py | 1,410 | 3.75 | 4 | import numpy as np
import matplotlib.pyplot as plt
def func_one():
x = np.random.randn(100)
plt.plot(x)
plt.show()
def func_two():
ts_length=100
c_values=[]
for i in range(ts_length):
e=np.random.randn()
c_values.append(e)
plt.plot(c_values)
plt.show()
def func_three():
ts_length=100
c_values=[]
j = 0
while j < ts_length:
e = np.random.randn()
c_values.append(e)
j = j + 1
plt.plot(c_values)
plt.show()
def generate_data(n,generator_type):
c_values=[]
for i in range(n):
if generator_type=="U":
e= np.random.uniform(0,1)
else:
e=np.random.randn()
c_values.append(e)
return c_values
a = input("Which one function would you choose?")
print("You choose function:" + a)
if a == "1":
func_one()
elif a == "2":
func_two()
elif a == "3":
func_three()
elif a == "4":
b = input("Would you want to choose Uniform(0,1)?[y/n]")
if b == "y":
data = generate_data(100,"U")
plt.plot(data)
plt.show()
elif b == "n":
data = generate_data(100,"N")
plt.plot(data)
plt.show()
else:
print("WTF you want to plot?")
else:
def generate_date(n,typer):
c_values = [typer() for i in range(n)]
data = generate_data(100,np.random.uniform)
plt.plot(data)
plt.show()
|
10adb8612b8e0e1054a1506370e624632ccb27c3 | tiqwab/atcoder | /abc217/b/main.py | 240 | 3.5625 | 4 | def main():
d = {"ABC", "ARC", "AGC", "AHC"}
S1 = input().strip()
d.remove(S1)
S2 = input().strip()
d.remove(S2)
S3 = input().strip()
d.remove(S3)
return d.pop()
if __name__ == '__main__':
print(main())
|
1696d0a6837f8abcab9d47c31de2b98c956ab4c6 | at3103/Leetcode | /tree_mod.py | 818 | 3.6875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import Counter,deque,defaultdict
class Solution(object):
def findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
tree =defaultdict()
temp = root
mod = -1
mod_list =[]
to_traverse = deque()
while temp:
val = temp.val
if not tree.get(val):
tree[val]=1
else:
tree[val]+=1
if tree[val] > mod:
mod = tree[val]
mod_list =[val]
elif tree[val] == mod:
mod_list.append(val)
if temp.left:
to_traverse.append(temp.left)
if temp.right:
to_traverse.append(temp.right)
temp = to_traverse.pop()
return mod_list
#count_dict = Counter( |
2bd7ddf5f96ed7c3b2470a260914ccabb3b2c0ac | smeenai/llvm-project | /llvm/test/tools/llvm-reduce/Inputs/sleep-and-check-stores.py | 547 | 3.515625 | 4 | #!/bin/python
import time
import sys
sleep_seconds = int(sys.argv[1])
num_stores = int(sys.argv[2])
file_input = sys.argv[3]
try:
input = open(file_input, "r")
except Exception as err:
print(err, file=sys.stderr)
sys.exit(1)
InterestingStores = 0
for line in input:
if "store" in line:
InterestingStores += 1
print("Interesting stores ", InterestingStores, " sleeping ", sleep_seconds)
time.sleep(sleep_seconds)
if InterestingStores > num_stores:
sys.exit(0) # interesting!
sys.exit(1) # IR isn't interesting
|
5d742d177f909ae0f703a068ce1768f610cfbf4d | foxbox-r/CODING-TEST | /구현/12_7.py | 262 | 3.5 | 4 | import sys
input = sys.stdin.readline
string = input()
first,second = 0,0
for i in range(len(string)-1):
if(i < (len(string)-1)/2):
first += int(string[i])
else:
second += int(string[i])
print("LUCKY" if first == second else "READY") |
a11a952b2b3e0dde3ff77e0bb6aac6d9a94a0b43 | hughian/OJ | /LeetCode/Python/E374_GuessNumberHigherorLower.py | 1,004 | 3.875 | 4 | # The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num):
NUM_TO_GUESS = 0
N = 0
def guess(num):
global N,NUM_TO_GUESS
if NUM_TO_GUESS>=0 and NUM_TO_GUESS<=N:
if num==NUM_TO_GUESS:return 0
elif num>NUM_TO_GUESS:return -1
else :return 1
else:
raise(ValueError)
def set(n,k):
global N,NUM_TO_GUESS
N = n
NUM_TO_GUESS = k
class Solution(object):
def guessNumber(self, n):
"""
:type n: int
:rtype: int
"""
left, right = 0,n
while left<=right:
mid = (left + right) // 2
r = guess(mid)
if r==0:
return mid
elif r==-1:
right=mid-1
else:
left=mid+1
def main():
n,k=10,6
set(n,k)
s = Solution().guessNumber(n)
print(s)
if __name__=='__main__':
main() |
90f0fcc031d2752b1d7c3d51e4cb39fd2f7efb7d | YLyeliang/now_leet_code_practice | /Dynamic_program/fibonacci.py | 675 | 3.8125 | 4 | # 经典的斐波那契问题(爬阶梯):n个阶梯,一次可上一层或两层,有多少种上法。
# 分解之后:可以得知,n个台阶的上法为F(N)种,其结果F(N)=F(N-1)+F(N-2)。因为上n个阶梯之前,只有两种情况,一种是还有一层可以上,一种是还有两层阶梯可以上。
# 逐次分解,得到F(3)=F(2)+F(1),其中F(1)=1,F(2)=2为初始化的解,通过这几个初始解,可以推广到情况为n时的结果。
class Solution:
def fibonacci(self,n):
a,b=1,1
for i in range(n):
a,b=b,a+b # 这个写法是两个计算并行处理 与 a=b b=a+b结果不同。
return a
|
d38e76a7dec4147ae221b4447756f95ea06d7d92 | cruepprich/python | /adventure.py | 1,972 | 4.21875 | 4 | #!/usr/bin/python
## revised mysterious house, using nested conditionals.
import os
os.system('clear')
print "Welcome to Mysterious House!\n\n"
name = raw_input("What is your name? ").strip().title()
print '''You are in the *foyer*. There is a mirror on the wall. In the mirror,
it says in blood (or possibly ketchup, if you're squeamish\n\n''' + \
name[::-1].upper() + '''
creepy. Very creepy. And MYSTERIOUS!
Spooky scary skeletons...
There is a door'''
ans = raw_input('go (through the door) or stay? ')
if ans == 'go':
print '''you are in a dark hallway. It's creepy, but there is \
a delicious smell from down the hall. You go towards it.
The lit room at the end of the hall is a kitchen. You're ravenous.
There is a cake on the table.
'''
ans = raw_input("eat the cake (yes or no)? ")
if ans == "eat" or ans == "yes":
print "mmmm.... delicious cake"
ans = raw_input( '''You feel guilty. Choose a reason:
a. it's rude to eat someone else's cake
b. you ate earlier, and were still pretty full
c. you're allergic to cake\n\n''')
if ans=='a':
print "You're right, it is rude"
elif ans=='b':
print "Well, it's not like there is tupperware around to take it for later"
else:
ans = raw_input( "Oh no! What kind of allergy? [gluten or anaphalectic]? " )
if ans[0] == 'g':
print '''THE ORACLE PREDICTS.... soon you will need to find a Mysterious...........
bathroom.
'''
else: # no cake
print '''No cake? REALLY! Instead you poop, pass out, and \
are eaten by a grue'''
else: # no door
ans = raw_input('yes or no? ')
if ans == 'yes':
print '''I see you are a person of action! Too bad you're hanging about in \
a foyer!'''
else:
print '''I sometimes get that way in the winter too'''
print "\n\nThank you for playing,", name |
450566170eae6dc39dcd94394e8ea97e574b7dde | andreinaoliveira/Exercicios-Python | /Exercicios/083 - Validando expressões matemáticas.py | 444 | 4.21875 | 4 | # Exercício Python 083 - Validando expressões matemáticas
# Crie um programa onde o usuário digite uma expressão qualquer que use parênteses.
# Seu aplicativo deverá analisar se a expressão passada está com os parênteses abertos e fechados na ordem correta.
exp = str(input('Dgite a expressão: '))
if exp.count('(') == exp.count(')'):
print("Sua expressão está válida!")
else:
print("Sua expressão está errada!")
|
c1cde7f695e0ded93c28cb9e764bebcf4828792d | anubeig/python-material | /MyTraining_latest/MyTraining/17.Data_structures/LinkedList/Detect_and_remove_loop.py | 2,388 | 3.984375 | 4 | # Python program to detect and remove loop
"""
. After detecting the loop,
if we start slow pointer from head and move both slow and fast pointers at same speed until fast don’t meet,
they would meet at the beginning of linked list.
So if we start moving both pointers again at same speed such that one pointer (say slow) begins from head node of linked list and
other pointer (say fast) begins from meeting point.
When slow pointer reaches beginning of linked list (has made m steps).
Fast pointer would have made also moved m steps as they are now moving same pace. Since m+k is a multiple of n and fast starts from k,
they would meet at the beginning.
Can they meet before also? No because slow pointer enters the cycle first time after m steps.
"""
# Node class
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def detectAndRemoveLoop(self):
slow = self.head
fast = self.head.next
# Search for loop using slow and fast pointers
while (fast is not None):
if fast.next is None:
break
if slow == fast:
break
slow = slow.next
fast = fast.next.next
# if loop exists
if slow == fast:
slow = self.head
while (slow != fast.next):
slow = slow.next
fast = fast.next
# Sinc fast.next is the looping point
fast.next = None # Remove loop
# Utility function to print the linked LinkedList
def printList(self):
temp = self.head
while (temp):
print temp.data,
temp = temp.next
# Driver program
llist = LinkedList()
llist.head = Node(50)
llist.head.next = Node(20)
llist.head.next.next = Node(15)
llist.head.next.next.next = Node(4)
llist.head.next.next.next.next = Node(10)
# Create a loop for testing
llist.head.next.next.next.next.next = llist.head.next.next
llist.detectAndRemoveLoop()
print "Linked List after removing looop"
llist.printList() |
7a3f9d4be20f1abb565a1491fe934b17cb06de5c | bcwood/adventofcode2020 | /2/part2.py | 335 | 3.578125 | 4 | count = 0
for line in open("2/input.txt", "r"):
parts = line.split(" ")
positions = parts[0]
pos1 = int(positions.split("-")[0]) - 1
pos2 = int(positions.split("-")[1]) - 1
letter = parts[1][0]
text = parts[2]
if (bool(text[pos1] == letter) ^ bool(text[pos2] == letter)):
count += 1
print(count)
|
e2717abea00cb496e391e34311c85b63ad507737 | Shaigift/Python-Practice-1 | /Chapt 5: If Statements/magic_number.py | 834 | 4.125 | 4 | ##Numerical Comparisons
answer = 17
if answer != 42:
print("That is not the correct answer. Please try again!")
age = 19
age < 21
True
Age <= 21
True
age > 21
False
age >= 21
False
##Checking Multiple Conditions
#More than one condition can be checked, keywords and and or can help
##using and to Check Multiple Conditions
age_0 = 22
age_1 = 18
age_0 >= 21 and age_1 >= 21
False
age_1 = 22
age_0 >= 21 and age_1 >= 21
True
#Parenthesis can also be used to improve readability
(age_0 >= 21) and (age_1 >= 21)
##Using or tp Check Multiple Conditions
age_0 = 22
age_1 = 18
age_0 >= 21 or age_1 >= 21
True
age_0
age_0 >= 21 or age_1 >= 21
False
##Checking Whether a Value Is in a List
requested_toppings = ['mushrooms', 'onions', 'pineapple']
'mushrooms' in requested_toppings
True
'pepperoni' in requested_toppings
False
|
3d2a23cbffaa40eca0693ce78051a16d84afb794 | mohitsaroha03/The-Py-Algorithms | /src/3.1Array/delete-an-element-from-array-using-two-traversals-and-one-traversal.py | 1,049 | 4.4375 | 4 | # Link: https://www.geeksforgeeks.org/delete-an-element-from-array-using-two-traversals-and-one-traversal/
# https://practice.geeksforgeeks.org/problems/rotate-and-delete/0
# https://www.geeksforgeeks.org/array-rotation/
# python program to remove a given element from an array
# This function removes an element x from arr[] and
# returns new size after removal.
# Returned size is n-1 when element is present.
# Otherwise 0 is returned to indicate failure.
def deleteElement(arr,n,x):
# If x is last element, nothing to do
if arr[n-1]==x:
return n-1
# Start from rightmost element and keep moving
# elements one position ahead.
prev = arr[n-1]
for i in range(n-2,1,-1):
if arr[i]!=x:
curr = arr[i]
arr[i] = prev
prev = curr
# If element was not found
if i<0:
return 0
# Else move the next element in place of x
arr[i] = prev
return n-1
# Driver code
arr = [11,15,6,8,9,10]
n = len(arr)
x = 6
n = deleteElement(arr,n,x)
print("Modified array is")
for i in range(n):
print(arr[i],end=" ")
|
bae3c2453eb1fb93da53b262774ee2a9041ccb1f | panderson1988/Python-Files | /function_split_bill.py | 1,719 | 4.40625 | 4 | '''
Three people ate dinner at a restaurant and want to split the bill.
The total is $35.27, and they want to leave a 15% tip.
How much should each person pay?
'''
total = 35.27
totalPlusTip = 35.27 * 1.15
amtPerPerson = totalPlusTip / 3
print( 'amount per person =', amtPerPerson )
# use a function to compute the amount each person pays
def split_bill( bill, tip, num_ppl ):
'''
Add tip to bill to calculate total bill including tip.
Split total between num_ppl and return that value
rounded to two digits
'''
tip_pct = tip / 100
# total_bill can also be written as bill + ( bill * tip percentage )
total_bill = bill * ( 1 + tip_pct )
amt = total_bill / num_ppl
return round( amt, 2 )
''' Algorithm
-split_bill() function requires three parameters that are specified in the def
-prompt user for bill_amt and assign value to variable bill_amt
-prompt user for tip_amt and assign that value to tip_amt
-prompt user for number of people and assign that value to folks
-call split_bill passing in three values bill_amt, tip_amt, folks
and assign return value to variable amt_per_person
-print amt_per_person
'''
'''
>>> ================================ RESTART ================================
>>>
>>> bill_amt = eval( input( 'enter bill amount: ' ) )
enter bill amount: 35.27
>>> tip_amt = eval( input( 'enter tip amount between 10 and 20: ' ) )
enter tip amount between 10 and 20
>>> folks = eval( input( 'enter number of people: ' ) )
enter number of people: 3
>>> amt_per_person = split_bill( bill_amt, tip_amt, folks )
>>> print( 'Amount per person = $', amt_per_person )
Amount per person = $ 13.52
'''
|
66cb7cd0b96a1c17f3de439a4a596aeb77185192 | kpanic666/CS50-2019 | /pset6/crack/crack.py | 2,292 | 3.671875 | 4 | from sys import argv
from crypt import crypt
import string
# Newbie code, there are huge space for optimisation
def main():
error = False
ihash = ""
if len(argv) == 2:
# Check that input Hash consist only from [a-zA-Z0-9./]
# and it is 13-character in lenght
ihash = str(argv[1])
for c in ihash:
if len(ihash) != 13 or (c.isalnum() == False and
c != '.' and c != '/'):
error = True
break
# If hash is fine. Try to crack the password
if error == False:
result, findPwd = bruteforce(ihash, "A")
if result == True:
print(findPwd)
else:
exit("Failed. Cant crack the hash")
else:
error = True
if error == True:
exit("Usage: python crack.py hash")
# Increment password from "A" to "ZZZZZ"
def inc_pwd(inPwd):
pwdInd = 0
switchNextLetter = True
pwd_list = [[] for i in range(5)]
# Because strings in Python is immutable i find a newbie way to resolve this
for i in range(len(inPwd)):
pwd_list[i] = inPwd[i]
# Iterate over all letters in password string. From left to right
while switchNextLetter == True and pwdInd < 5:
switchNextLetter = False
if pwd_list[pwdInd] < 'Z':
pwd_list[pwdInd] = chr(ord(pwd_list[pwdInd]) + 1)
elif pwd_list[pwdInd] < 'a':
pwd_list[pwdInd] = 'a'
elif pwd_list[pwdInd] < 'z':
pwd_list[pwdInd] = chr(ord(pwd_list[pwdInd]) + 1)
else:
pwd_list[pwdInd] = 'A'
switchNextLetter = True
pwdInd += 1
if pwd_list[pwdInd] == []:
pwd_list[pwdInd] = 'A'
break
inPwd = ""
for c in pwd_list:
if c != []:
inPwd = inPwd + c
return inPwd
# Calc the hash, take new pass if it fails
def bruteforce(inHash, spwd):
end_pwd = "zzzzz"
while True:
outHash = crypt(spwd, inHash[:2])
# print(spwd)
if outHash == inHash:
return True, spwd
elif spwd != end_pwd:
spwd = inc_pwd(spwd)
else:
return False
if __name__ == "__main__":
main() |
1be57b58ba0d65c343cd5bb8dd505e17ed1858ac | pranavkaul/Hackerrank_Python | /Python Solutions/The_Minion_Game.py | 560 | 3.640625 | 4 | def minion_game(string):
vowel = ['A','E','I','O','U']
stuart_score = 0
kevin_score = 0
l = len(string)
for i in range(l):
if string[i] in vowel:
kevin_score = kevin_score + (l - i)
else:
stuart_score = stuart_score + (l - i)
if kevin_score > stuart_score:
print('Kevin {}'.format(kevin_score))
elif stuart_score > kevin_score:
print('Stuart {}'.format(stuart_score))
else:
print('Draw')
if __name__ == '__main__':
s = input()
minion_game(s)
|
ee5455a00b125ffef80a25566570d85a2b4f4d0b | Georgenko/TFG | /test.py | 1,842 | 3.59375 | 4 | #encoding:utf-8
import threading
import logging
logging.basicConfig(level=logging.DEBUG)
logger=logging.getLogger()
def funcion(a):
print(f"estoy en una hebra aparte: {a}")
x=threading.Thread(target=funcion,args=(1,))
x.start()
print("estoy en la hebra principal")
"""class Hebra(threading.Thread):
def __init__(self,argumento):
threading.Thread.__init__(self)
self.argumento=argumento
def run(self):
print(self.argumento)
h=Hebra("test")
h.start()"""
"""COUNTER=0
def increment(n):
global COUNTER
for _ in range(n):
COUNTER+=1
threads=[threading.Thread(target=increment,args=(1000000,)) for _ in range(3)]
[t.start() for t in threads];
[t.join() for t in threads];
print(COUNTER)"""
"""lock=threading.Lock()
COUNTER=0
def increment(n,lock):
global COUNTER
for _ in range(n):
lock.acquire()
COUNTER+=1
lock.release()
threads=[threading.Thread(target=increment,args=(1000000,lock)) for _ in range(3)]
[t.start() for t in threads];
[t.join() for t in threads];
print(COUNTER)"""
"""lock=threading.Lock()
COUNTER=0
def increment(n,lock):
global COUNTER
for _ in range(n):
lock.acquire()
print(lock.locked())
try:
raise Exception("excepción")
COUNTER+=1
finally:
lock.release()
threads=[threading.Thread(target=increment,args=(1000000,lock)) for _ in range(3)]
[t.start() for t in threads];
[t.join() for t in threads];
print(COUNTER)
print(lock.locked())"""
"""lock=threading.Lock()
COUNTER=0
def increment(n,lock):
global COUNTER
for _ in range(n):
with lock:
COUNTER+=1
threads=[threading.Thread(target=increment,args=(1000000,lock)) for _ in range(3)]
[t.start() for t in threads];
[t.join() for t in threads];
print(COUNTER)"""
|
33bddfa0bfa6e1e600ca316d6c324555771308e9 | wangyan228/auto-mosaic | /download-image.py | 3,030 | 3.53125 | 4 | # 定义函数,将网址转化为html内容
# 使用requests模块,教程参见:http://www.python-requests.org/en/master/
import requests
import re
def url2html_requests(url,encoding='utf-8'):
# 输入:网址
# 输出:网页内容
# 检查网址是否以http://开头,少数网站是以https://开头的
if not url.startswith('https://'):
url = 'https://' + url
try:
# 获取网页内容
r = requests.get(url,timeout=120)
except requests.exceptions.ConnectTimeout:
#120s没有反应就报错
print('输入的网址有误,请检查')
else:
if r.status_code == 200:
# 默认编码格式为utf-8
# 查看网页编码格式方法:Chrome浏览器Ctrl+U,搜索关键字charset,如果有,那么后面接着的就是编码格式
# 不是所有网页都有charset关键字,可以试一下utf-8或者gbk
r.encoding = encoding
content = r.text
# 返回网页内容
return content
# 关于python正则表达式,可以参考:http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html
def html2imgurl(html_content):
# detect image url in html content
# return img url list
pattern = re.compile('(https?)?//([\w\/\-\.]+)(jpg|png)') # re.S for . representate any characters
list_raw = re.findall(pattern,html_content) # raw list is made up of 2 parts
list_img_url = ['http://'+''.join(i) for i in list_raw]
return list_img_url
def html2pageurl(html_content):
# /search/flip?tn=baiduimage&ie=utf-8&word=%E8%BD%A6%E7%89%8C&pn=160&gsm=c8&ct=&ic=0&lm=-1&width=0&height=0
pattern = re.compile('\/search\/flip\?[\d\w\=\&\-\%]+')
list_raw = re.findall(pattern, html_content)
list_page_url = ['https://image.baidu.com' + ''.join(i) for i in list_raw]
return list_page_url
def saveimg_requests(imgurl,filename=''):
#http://stackoverflow.com/questions/13137817/how-to-download-image-using-requests
try:
r = requests.get(imgurl)
except requests.exception.ConnectTimeout:
print('Img NOT found')
else:
r.encoding = 'UFT-8'
if filename =='':
filename = imgurl.split('/').pop()#imgurl.split("/").pop()
print(filename)
filename = './images/' + filename;
if r.status_code == 200:
with open(filename, 'wb') as f:
for chunk in r:
f.write(chunk)
content = url2html_requests('https://image.baidu.com/search/flip?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1521007558581_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&ctd=1521007558582%5E00_844X826&word=%E8%BD%A6%E7%89%8C')
pages = html2pageurl(content)
print(pages)
for page in pages:
content = url2html_requests(page)
images = html2imgurl(content)
for image in images:
try:
saveimg_requests(image)
except:
pass
print('finish!')
#print(images)
|
145b919c3b4cea483e67ff4a1a955e42fc387c28 | leoniescape/Python-Workshop-in-Jinan | /if_example.py | 470 | 3.890625 | 4 | #Please guess the output before run the code;)
condition_A = True
condition_B = True
condition_C = True
condition_D = True
condition_E = True
condition_F = True
if condition_A:
if condition_B:
print( "1" )
else:
print( "2" )
if condition_C:
print( "3" )
elif condition_D:
print( "4" )
if condition_E:
print( "5" )
else:
print( "6" )
else:
print( "7" )
print( "8" )
|
f1aef5d062dc174b6d57c46ddeaf875095b79a9d | BatBapt/password-manager | /apps/database/database.py | 4,779 | 3.84375 | 4 | import sqlite3
import bcrypt
from datetime import datetime
class Database:
def __init__(self, database_name):
self.database_name = database_name
try:
self.conn = sqlite3.connect(self.database_name)
self.cur = self.conn.cursor()
except sqlite3.Error as error:
print("Erreur lors de la connection à la base de donnée: {}".format(error))
self.init_table_password()
def init_table_password(self):
"""
:return:
"""
self.cur.execute(
"""
CREATE TABLE IF NOT EXISTS users(
id INTEGER PRIMARY KEY,
username VARCHAR(100) NOT NULL,
password VARCHAR(255) NOT NULL,
signup_date DATETIME NOT NULL
)
"""
)
self.cur.execute(
"""
CREATE TABLE IF NOT EXISTS password(
id INTEGER PRIMARY KEY,
username VARCHAR(100) NOT NULL,
app VARCHAR(255) NOT NULL,
pseudo VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
FOREIGN KEY (username) REFERENCES users(username)
)
"""
)
def add_user(self, values):
salt = bcrypt.gensalt()
values[1] = bcrypt.hashpw(bytes(values[1], encoding='ascii'), salt)
values.append(datetime.now())
sql = "INSERT INTO users(username, password, signup_date) VALUES(?, ?, ?)"
self.cur.execute(sql, values)
self.conn.commit()
def add_row(self, values):
"""
:param values: list of values to add in the db:
values[0] => username logged
values[1] => app name
values[2] => pseudo for the app
values[3] => password for the app
values[4] => datetime // Added in this function
:return: the id of the row added
"""
sql = "INSERT INTO password(username, app, pseudo, password) VALUES(?, ?, ?, ?)"
self.cur.execute(sql, values)
self.conn.commit() # store and save the row in the database
return self.cur.lastrowid
def connection_user(self, username, pwd):
sql = "SELECT * FROM users WHERE username=?"
self.cur.execute(sql, (username, ))
row = self.cur.fetchone()
if row is not None:
password = row[2]
if bcrypt.checkpw(bytes(pwd, encoding='ascii'), password):
return True
else:
return False
else:
return False
def print_by_user(self, user):
sql = "SELECT * FROM users WHERE username=?"
self.cur.execute(sql, (user, ))
row = self.cur.fetchone()
if row is not None:
return row
else:
return False
def print_row(self, username):
sql = "SELECT * FROM password WHERE username=?"
self.cur.execute(sql, (username, ))
rows = self.cur.fetchall()
if rows is not None:
return rows
else:
return False
def search_by_app(self, app):
sql = "SELECT * FROM password WHERE app LIKE '%'||?||'%'"
self.cur.execute(sql, (app, ))
rows = self.cur.fetchall()
return rows
def search_by_pseudo(self, pseudo):
sql = "SELECT * FROM password WHERE pseudo LIKE '%'||?||'%'"
self.cur.execute(sql, (pseudo, ))
rows = self.cur.fetchall()
return rows
def print_row_by_id(self, ids):
sql = "SELECT * FROM password WHERE id=?"
self.cur.execute(sql, (ids, ))
row = self.cur.fetchone()
return row
def update_row(self, ids, pseudo="", password=""):
"""
:param ids: if of the row to update
:param pseudo: pseudo to update
:param password: password to update
:return:
"""
if len(pseudo) == 0 and len(password) > 0:
sql = "UPDATE password set password=? WHERE id=?"
self.cur.execute(sql, (password, ids, ))
elif len(pseudo) > 0 and len(password) == 0:
sql = "UPDATE password set pseudo=? WHERE id=?"
self.cur.execute(sql, (pseudo, ids,))
elif len(pseudo) > 0 and len(password) > 0:
sql = "UPDATE password set pseudo=? AND password=? WHERE id=?"
self.cur.execute(sql, (pseudo, password, ids,))
self.conn.commit()
print("Ligne modifiée correctement.")
def delete_row(self, ids):
"""
:param ids: id to delete
:return:
"""
sql = "DELETE FROM password WHERE id=?"
self.cur.execute(sql, (ids,))
self.conn.commit()
print("Lignée supprimée correctement")
|
6bdb63748c916acc34dff03130127502921b4518 | Kantslerr/laba1-python- | /lab5.py | 319 | 3.796875 | 4 | a = str(input("Введите строку: "))
def f(a):
b = 0
for s in a:
letter = s.lower()
if letter == "a" or letter == "e" or\
letter == "i" or letter == "o" or\
letter == "u" or letter == "y":
b += 1
print("Гласных =",b)
return b
f(a)
|
4fdc74152fd4c307fb9c3673f056f2a56e334ab7 | GitGAS/Education | /Lesson_6/Task_2_ls_6.py | 373 | 3.640625 | 4 | # Task_2
class Road():
weight = 25
def __init__(self,length,width):
self._length = int(length)
self._width = int(width)
def mas(self, height = 5):
result = self._length * self._width * self.weight * height / 1000
return result
out = Road(5000, 20)
print(f"Масса асфальта составит: {out.mas():0.0f} т.") |
accf2f1750145a9bd1c3ad7d998da93da827cbe7 | cooolcai/py-0901 | /zodiac/zodiac_v3.py | 1,375 | 3.5 | 4 | zodiac_name = (u'摩羯座',u'水瓶座',u'双鱼座',u'白羊座',u'金牛座',u'双子座',u'巨蟹座',u'狮子座',u'处女座',u'天秤座',u'天蝎座',u'射手座')
# #此处内容没有单引号,所以外侧可用单引号。
zodiac_days = ((1,20),(2,19),(3,21),(4,21),(5,21),(6,22),(7,23),(8,23),(9,23),(10,23),(11,23),(12,23))
# #元组可以使用嵌套功能。
chinese_zodiac = "猴鸡狗猪鼠牛虎兔龙蛇马羊"
cz_num = {}
for i in chinese_zodiac:
cz_num[i] = 0
z_num ={}
for i in zodiac_name:
z_num[i] = 0
while True:
#用户输入月份和日期
int_year = int(input('请输入年份'))
int_month = int(input('请输入月份:'))
int_day = int(input('请输入日期:'))
for zd_num in range(len(zodiac_days)):
if zodiac_days[zd_num] >= (int_month,int_day):
print(zodiac_name[zd_num])
break
elif int_month == 12 and int_day > 23:
print(zodiac_name[0])
break
print('%s 年的生肖是 %s' % (int_year, chinese_zodiac[int_year % 12]))
cz_num[chinese_zodiac[int_year % 12]] += 1
z_num[zodiac_name[zd_num]] += 1
#输出统计信息
for each_key in cz_num.keys():
print('生肖 %s 有 %d 个' %(each_key,cz_num[each_key]))
for each_key in z_num.keys():
print('星座 %s 有 %d 个' %(each_key,z_num[each_key]))
|
091e8667555901afa54a29fa78c8406182a3a756 | dPfla0130/codingtest_Python | /codingtest/202102/CyclicRotation.py | 476 | 3.65625 | 4 | # you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A, K):
# write your code in Python 3.6
if len(A)==0:
return []
else:
K = K%len(A)
answer = [0]*len(A)
for i in range(len(A)):
if i+K < len(A):
answer[i+K] = A[i]
else:
answer[0:K] = A[i:]
break
return answer
if __name__ == "__main__":
print(solution([1, 1, 2, 3, 5], 42)) |
b71a711167a0e4078c1d4f4570b9bbc428709306 | rigratz/rigratz-linkedin | /Portfolio/Blackjack/main/Main.py | 2,067 | 3.609375 | 4 | import math
import random
from main.Cards import Deck
from main.Players import Player
deckOfCards = Deck()
def getFibNum(num):
if num == 1 or num == 0:
return 1
else:
return getFibNum(num - 2) + getFibNum(num - 1)
def isPrime(num):
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
def main():
#print ("Random dice roll:", random.randrange(1, 7))
#print ("Fibonacci number 10:", getFibNum(10))
#print ("17 is a Prime Number:", isPrime(17))
deckOfCards.shuffle()
player = Player()
dealer = Player()
players = [dealer, player]
dealCards(players, deckOfCards)
players[0].showHand("DealerH")
looper = True
bust = False
while players[1].getTotal() < 21 and looper:
players[1].showHand("Player")
looper = movePrompt(players[1])
players[1].showHand("Player")
if (players[1].getTotal() > 21):
bust = True
print ("Bust!")
looper = True
while looper:
players[0].showHand("Dealer")
looper = players[0].dealerHand(deckOfCards)
dealBust = False
if players[0].getTotal() > 21:
dealBust = True
if players[1].getTotal() > players[0].getTotal() and not bust and not dealBust:
print ("You win!")
elif players[1].getTotal() == players[0].getTotal() and not bust and not dealBust:
print ("Push!")
elif not bust and dealBust:
print ("Dealer busts! You win!")
else:
print ("You lose.")
def movePrompt(player):
print ("Select a move:")
print ("1: Hit")
print ("2: Stay")
selection = int(input("Make selection:"))
if selection == 1:
print ("Hit me!")
player.addToHand(deckOfCards.cards.pop())
elif selection == 2:
return False
return True
def dealCards(players, deck):
for i in range(2):
for p in players:
card = deck.cards.pop()
p.addToHand(card)
if __name__ == '__main__':
main()
|
9e725eef9e3b10e062603d1a8ac628b0e5dc5deb | Nathaniel392/HammerOfTheScotsBayesian | /find_block.py | 231 | 3.875 | 4 | import blocks
def find_block(name, block_list):
'''
returns a block given a name in block_list
'''
for block in block_list:
if block.name == name.upper():
return block
raise Exception("cant find block with name: " , name) |
f0c10546a7e96ba24bde231847aacd23e367e103 | sundar-paul/Coursera-Python | /Coursera Python/Data Structures in Python/week 6/assignment.py | 385 | 3.546875 | 4 | name=input("Enter the file name: ")
fhandle=open(name+'.txt')
counts=dict()
for line in fhandle:
if not line.startswith('From:'):continue
words=line.split()
counts[words[1]]=counts.get(words[1],0)+1
bigcount=None
bigword=None
for k,v in counts.items():
if bigcount is None or v>bigcount:
bigword=k
bigcount=v
print(bigword,bigcount) |
7f623add05750f0a70f5c9a6e86bde41c7e1f24d | lee-gyu/happy_algorithm | /20_04_April/0411_python_study4/merge_sort.py | 800 | 3.6875 | 4 | '''
분할정복 알고리듬 연습
(Divide and Conquer)
Merge Sort
'''
import random
def merge_sort(ary, p, q):
if p == q:
return
m = (p + q) // 2
merge_sort(ary, p, m)
merge_sort(ary, m + 1, q)
merge(ary, p, m + 1, q)
def merge(ary, i, j, e):
tmp = []
# ary i -> j -> tmp에 오름차순 집어넣기
l = e - i + 1
p = i
q = j
while len(tmp) != l:
if q > e or (p < j and ary[p] < ary[q]):
tmp.append(ary[p])
p += 1
else:
tmp.append(ary[q])
q += 1
# tmp >> ary에 집어넣기
for id, x in enumerate(range(i, e + 1)):
ary[x] = tmp[id]
l = [1, 7, 1, 6, 5, 9, 3, 4, 2, 8, 4, 5]
print(l)
merge_sort(l, 0, len(l) - 1)
print('------Sorting------')
print(l)
|
12a83c5eacf73951cf83b678a4eca2d258861a56 | SpartanPlume/TosurnamentWeb | /server/helpers/crypt.py | 1,893 | 3.609375 | 4 | """Encrypt and decrypt datas"""
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto import Random
import constants
def hash_str(obj):
"""Hashes a string"""
if not obj:
return None
sha = SHA256.new()
sha.update(str.encode(obj, 'utf-8'))
return sha.digest()
def encrypt_str(obj):
"""Encrypts a string"""
if not obj:
return None
iv = Random.new().read(AES.block_size)
cipher = AES.new(constants.ENCRYPTION_KEY, AES.MODE_CFB, iv)
obj = iv + cipher.encrypt(str.encode(obj, 'utf-8'))
return obj
def decrypt_str(obj):
"""Decrypts a string"""
if not obj:
return None
iv = obj[0:AES.block_size]
obj = obj[AES.block_size:]
cipher = AES.new(constants.ENCRYPTION_KEY, AES.MODE_CFB, iv)
obj = cipher.decrypt(obj).decode('utf-8')
return obj
def encrypt_obj(obj):
"""Encrypts an object"""
if not obj:
return None
fields = vars(obj)
for key, value in fields.items():
if not key.startswith("_") and key != "to_hash" and key != "ignore":
if isinstance(value, str):
if obj.to_hash and key in obj.to_hash:
value = hash_str(value)
elif not obj.ignore or key not in obj.ignore:
value = encrypt_str(value)
setattr(obj, key, value)
return obj
def decrypt_obj(obj):
"""Decrypts an object"""
if not obj:
return None
fields = vars(obj)
for key, value in fields.items():
if not key.startswith("_") and key != "to_hash" and key != "ignore":
if isinstance(value, bytes):
if (obj.to_hash and key in obj.to_hash) or (obj.ignore and key in obj.ignore):
pass
else:
value = decrypt_str(value)
setattr(obj, key, value)
return obj
|
9113d81bd131056caff9dbf6094eeef87c0dbce0 | aboulay/kata-roman | /tests/test_roman_translator.py | 2,038 | 3.6875 | 4 | import unittest
from translator.roman import RomanTranslator
class TestRomanTranslator(unittest.TestCase):
def test_translate_when_asking_for_1(self):
# Given
given = "1"
expected = "I"
translator = RomanTranslator()
# When
result = translator.translate(given)
# Then
self.assertEqual(result, expected)
def test_translate_when_asking_for_2(self):
# Given
given = "2"
expected = "II"
translator = RomanTranslator()
# When
result = translator.translate(given)
# Then
self.assertEqual(result, expected)
def test_translate_when_asking_for_3(self):
# Given
given = "3"
expected = "III"
translator = RomanTranslator()
# When
result = translator.translate(given)
# Then
self.assertEqual(result, expected)
def test_translate_when_asking_for_5(self):
# Given
given = "5"
expected = "V"
translator = RomanTranslator()
# When
result = translator.translate(given)
# Then
self.assertEqual(result, expected)
def test_translate_when_asking_for_7(self):
# Given
given = "7"
expected = "VII"
translator = RomanTranslator()
# When
result = translator.translate(given)
# Then
self.assertEqual(result, expected)
def test_translate_when_asking_for_10(self):
# Given
given = "10"
expected = "X"
translator = RomanTranslator()
# When
result = translator.translate(given)
# Then
self.assertEqual(result, expected)
def test_translate_when_asking_for_16(self):
# Given
given = "16"
expected = "XVI"
translator = RomanTranslator()
# When
result = translator.translate(given)
# Then
self.assertEqual(result, expected)
if __name__ == '__main__':
unittest.main() |
bff93ec68ade0f6256ec562121023200adba75cc | Caleja/hacker_rank_exercises | /Day_15_LinkedLists.py | 659 | 3.890625 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
class Solution:
def display(self,head):
current = head
while current:
print(current.data,end=' ')
current = current.next
def insert(self,head,data):
new_node=Node(data)
if head is None:
self.head=new_node
return self.head
last_node=self.head
while last_node.next: #as long as next node exits->
last_node=last_node.next
last_node.next=new_node
return self.head
mylist=Solution()
T=[1,2,3,4,5,6]
head=None
for data in T:
print("data:",data)
head=mylist.insert(head,data)
mylist.display(head)
|
9b8b540e0ab79a9add805a1a760ff61b91946e19 | LordCthulhu123/AreaComputation | /Metodo2.py | 1,296 | 3.578125 | 4 | from typing import Callable
import random as rnd
import time, sys
def Metodo(is_in: Callable[..., bool], x0: float,
x1: float, y0: float, y1: float, number_of_seeds: int, points_per_seed: int) -> float:
"""
Implementa o cálculo de área por meio método.
"""
n_points_inside, n, m = 0, number_of_seeds, points_per_seed
for _ in range(0, n):
# A cada m pontos, eu troco a seed de geração de pontos.
rnd.seed(time.time())
for _ in range(0, m):
# Obtenhos a coordenadas do ponto de forma aleatória
x, y = rnd.uniform(x0, x1), rnd.uniform(y0, y1)
if is_in(x, y):
# Caso esteja na área desejada, inclementa-se a variável.
n_points_inside += 1
else:
pass
# Finalmente, a área é calculada de forma simples:
area = (n_points_inside/(n*m)) * ((y1 - y0) * (x1 - x0))
return area
if len(sys.argv) > 1:
def unit_circle(x, y):
if x**2 + y**2 <= 1:
return True
else:
return False
out = Metodo(unit_circle, float(sys.argv[1]), float(sys.argv[2]), float(sys.argv[3]), float(sys.argv[4]),
int(sys.argv[5]), int(sys.argv[6]))
exit(4 * out) |
3753d2d0a8cbf1de3222f49ac0679264b72b5f64 | Abhiniti/python-challenge | /PyPoll/main.py | 2,768 | 3.875 | 4 | #PyPoll
#Read the csv file; import correct modules
import os
import csv
csvpath = os.path.join("..", "PyPoll", "election_data.csv")
#Read the csv file per line
with open(csvpath, 'r') as csvfile:
electiondataCSV = csv.reader(csvfile)
#Skip the header
next(electiondataCSV)
#Count the total number of votes(rows) in the data set
# noVotes = sum(1 for row in electiondataCSV)
# print("Total Votes: " + str(noVotes))
#Create a list with candidate names and votes
candidateNames = []
candidateVotes = []
#Loop through rows in csv file
for row in electiondataCSV:
#Check if candidate name is not already in list
if row[2] not in candidateNames:
#If not, add it to the list
candidateNames.append(row[2])
#Since votes will have same length as candidate list, add a generic value to votes list
candidateVotes.append(0)
#Point back to the top of the csv file
csvfile.seek(0)
#Skip the header
next(electiondataCSV)
#Loop through rows in csv file
for row in electiondataCSV:
if row[2] in candidateNames:
#Check index of candidateNames
indexNo = candidateNames.index(row[2])
#Increment same index in candidateVotes
candidateVotes[indexNo] += 1
#Calculate percentageWon of each candidate
percentWon = []
#Sum up total number of votes
totalVotes = sum(candidateVotes)
#Loop through candidateVotes list
for number in candidateVotes:
#Calculate percent won for each candidate
percent = round((number/totalVotes*100),2)
#Add percentWon for each candidate into another list
percentWon.append(percent)
#Winner Function
def electionWinner(candidateVotes):
#Determine winner
maxVotes = max(candidateVotes)
#Detemine index for winner
maxIndex = candidateVotes.index(maxVotes)
#Get name for winner
return candidateNames[maxIndex]
#Return winner from function
winner = electionWinner(candidateVotes)
print("Election Results")
print("-------------------------")
print("Total Votes: " + str(totalVotes))
print("-------------------------")
#Format final results
finalArray = []
#Loop through list to get index
for name in candidateNames:
indexNo = candidateNames.index(name)
#Format: Name, percent won, votes
finalArray.append(str(candidateNames[indexNo]) + ": " + str(percentWon[indexNo]) + "% (" + str(candidateVotes[indexNo]) + ")")
#Present results in separate lines
print(*finalArray, sep='\n')
print("-------------------------")
print("Winner: " + str(winner))
print("-------------------------")
|
588dbee207afb52140429f62935b7519b24697ad | h2hyun37/algostudy | /study-algorithm/src/nedaair/euler/p37.py | 516 | 3.640625 | 4 | __author__ = 'nedaair'
from nedaair.util.smath import isPrime
index = 10
strangePrimeList = []
while True :
lenIndex = len(str(index))
isAllPrime = True
for i in range(0, lenIndex):
if (not isPrime(int(str(index)[0:i+1]))) or (not isPrime(int(str(index)[lenIndex-i-1:]))):
isAllPrime = False
break
if isAllPrime :
strangePrimeList.append(index)
if len(strangePrimeList) == 11 :
break
index = index + 1
print sum(strangePrimeList)
|
8c0876cbfa2c8dfb86f5e6619fc8305a25700cdc | Wictor-dev/ifpi-ads-algoritmos2020 | /iteração/6_tabuada.py | 389 | 3.890625 | 4 | #eu entendi essa questão de dois jeitos
# e esses dois jeitos estão aqui
# def main():
# n = int(input('Digite o número: '))
# m = 1
# while (m<=10):
# print(f'{n} * {m} = {n * m}')
# m += 1
# main()
n = 1
m = 1
while n <= 10:
while m<= 10:
print(f'{n} * {m} = {n * m}')
m += 1
n += 1
m = 1
|
e76e95ef8bb4c41f3801dff72619fa6cbe7db0ca | viggen-aero/PythonTraining | /RandNum/randomNumbers.py | 1,438 | 3.890625 | 4 | '''Program that generates a random number in range from 0 to 100 and asks user to guess it. In case of fail it asks again.'''
import random
generatedRand = (random.randint(0,100)) #generation of random number in range from 0 to 100 and 1st question for chosenNumber
chosenNumber = input("Zgaduj! Wybierz liczbę z zakresu 0-100: ") #ask user to guess the number for the 1st time
def number(): #function that asks user every next time he/she fails
global chosenNumber
chosenNumber = input("Wybierz następną liczbę: ")
exceptionHandling()
def exceptionHandling(): #checking if typed value is correct
global chosenNumber
try:
if float(chosenNumber).is_integer() == True:
if int(chosenNumber) < 0 or int(chosenNumber) > 100:
print("Musisz wpisać liczbę, która zawiera się w zadanym zakresie.")
number()
else:
print("Podawane liczby muszą należeć do zbioru liczb całkowitych.")
number()
except ValueError:
print("Znaki inne niż cyfry nie są dozwolone.")
number()
def mainloop():
exceptionHandling()
while int(chosenNumber) != generatedRand: #main loop
if int(chosenNumber) > generatedRand:
smallerOrBigger = 'mniejsza!'
else:
smallerOrBigger = 'większa!'
print('To nie ta liczba! Liczba której poszukujesz jest {}'.format(smallerOrBigger))
number()
print('Brawo! Wygrałeś talon! Koniec programu.')
try:
mainloop()
except:
print('Wystąpił nieznany błąd.')
raise
|
763045925ef3c16c74ba51106087413006ecfe81 | nlavanderos/learning-python | /orellyPython/chapter1_8/parte8.py | 1,089 | 4.03125 | 4 | #files
#a agrega alfinal de la linea el contenido de write
#Si el archivo existe hace el append sino
#crea el archivo y agrega la informacion.
with open('orellyPython\parte8.txt','a+') as f:
f.write('hello\n')
f.close()
#Lectura solo se necesita read(),pero para guardar el contenido en una lista ise uso de split()
#y elimino el ultimo espacio ya que el separador lo cuenta como caracter.
with open('orellyPython\parte8.txt','r') as f:
lectura=f.read().split('\n')
if lectura[-1]=='':
lectura.pop()
print(lectura)
#Es curioso pero no pueden haber mas de una instancia de lectura por with o open()
#read() muestra solo el string hello en pantalla aplicando caracteres especiales como \n
#readlines() me trae todo el contenido incluyendo los caracteres espciales como \n de manera literal o raw
#readline() para una linea
#Con with no es necesario cerrar el archivo.
#Por el contrario sin with es necesario cerrar el archivo con close()
#El modo w permite escribir y crear un archivo.Pero tambien elimina el contenido del archivo si este
#existia previamente
|
efb6fdbb9028e9217036d83a3619d994f522c92c | jorgesfj/Respostas-Uri | /iniciante/salario.py | 150 | 3.671875 | 4 | numero = int(input())
horas = int(input())
valor_horas = float(input())
print("""NUMBER = {}
SALARY = U$ {:.2f}""".format(numero,(horas*valor_horas))) |
ad3b2135be4e74f9301e13c1a34da19632de88e6 | Blessingshumba/learning | /ex2.py | 184 | 4.28125 | 4 | r = float(input("Enter the radius of the circle "))
if r < 0:
print("ooops the radius of the circle cannot be negative")
area = 3.148*r**2
print("Area of the circle =" + str(area)) |
07f67e895049ffc3f37dd552fd6f0fc1daeeedd0 | ddu0422/cloud | /Algorithm/DongBinNa/binary_search/concept/binary_search.py | 1,224 | 3.953125 | 4 | # 재귀
def binary_search_recursive(array, target, start, end):
# 원하는 값이 없는 경우
if start > end:
return
# 중간점
mid = (start + end) // 2
# 원하는 값을 찾은 경우
if target == array[mid]:
return mid
# 원하는 값이 중간 값보다 작은 경우 start ------ target ------- mid
elif target < array[mid]:
return binary_search_recursive(array, target, start, mid - 1)
# 원하는 값이 중간 값보다 큰 경우 mid ------ target ------- end
else:
return binary_search_recursive(array, target, mid + 1, end)
# 반복문
def binary_search_iteration(array, target, start, end):
while start <= end:
mid = (start + end) // 2
if target == array[mid]:
return mid
elif target < array[mid]:
end = mid - 1
else:
start = mid + 1
return None
n, target = list(map(int, input().split()))
array = list(map(int, input().split()))
result = binary_search_recursive(array, target, 0, n - 1)
result1 = binary_search_iteration(array, target, 0, n - 1)
if result == None:
print('원소 존재 x')
else:
print(result + 1)
print(result1 + 1)
|
169a6126ee2a7f586fd8abb8ef5a16e4200920fe | toasterbob/python | /Fundamentals1/Intro/practice.py | 1,749 | 3.65625 | 4 | "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!"
print("Hello World!.")
# python3 #to type in command line repl
# quit() # to exit # or press control + d.
# https://www.python.org/dev/peps/pep-0008/ #PEP 8 style guide
# DATA TYPES IN PYTHON
# Booleans: True and False (capitalize!)
# Numbers: integers and floats
# Strings: sequences of Unicode characters, like "hi", "bye", and "I love strings!"
# Lists: very similar to an array
# Tuples: Tuples are lists with immutable values - uses parentheses (4, 2, 1)
# Set: List with only unique values and no indexes - no order of elements within
# set("a", "b", "c").
#Dictionaries: An unordered key-value pair system. For example, a dictionary
# is similar to a hash in Ruby, or an object in JavaScript.
# Here's an example of a dictionary: {"key": "value", "a": 0}.
# To run the file, make sure you are in the Terminal/Command Line and run python3 first.py.
|
49c65c811e66690ae2b48edc6b1f87b627f74e7b | erjan/coding_exercises | /minimum_number_of_operations_to_convert_time.py | 2,176 | 3.609375 | 4 | class Solution:
def convertTime(self, current: str, correct: str) -> int:
cur = current
cor = correct
cur = cur.split(':')
print(cur)
cur_h = int(cur[0])
cur_m = int(cur[1])
cur_total_m = cur_h*60 + cur_m
cor = cor.split(':')
cor_h = int(cor[0])
cor_m = int(cor[1])
cor_total_m = cor_h*60 + cor_m
diff = abs(cur_total_m - cor_total_m)
print(diff)
count = 0
full, remainder = divmod(diff, 60)
count += full
diff = remainder
full, remainder = divmod(diff, 15)
count += full
diff = remainder
full, remainder = divmod(diff, 5)
count += full
diff = remainder
count += remainder
print(diff)
print('count', count)
return count
#another
class Solution:
def convertTime(self, current: str, correct: str) -> int:
current_time = 60 * int(current[0:2]) + int(current[3:5]) # Current time in minutes
target_time = 60 * int(correct[0:2]) + int(correct[3:5]) # Current time in minutes
diff = target_time - current_time # Difference b/w current and target times in minutes
count = 0 # Required number of operations
for i in [60, 15, 5, 1]:
count += diff // i # add number of operations needed with i to count
diff %= i # Diff becomes modulo of diff with i
return count
#another
def convertTime(self, current: str, correct: str) -> int:
if current==correct:
return 0
h=int(correct[:2])-int(current[:2])
m=int(correct[3:])-int(current[3:])
dit=h*60+m
count=0
if dit>=60:
count+=dit//60
dit=dit%60
if dit>=15:
count+=dit//15
dit=dit%15
if dit>=5:
count+=dit//5
dit=dit%5
if dit>=1:
count+=dit//1
dit=dit%1
return count
|
cbe934a5f282349cf9ce727f6bbd21e67d1a61a2 | manoj83r/TestPyProj | /Algorithm/BinarySearch.py | 472 | 3.609375 | 4 | pos = 0
def search(list2, s1):
lb = 0
ub = len(list2)
while lb<=ub :
mb = (lb+ub) // 2
if list2[mb] == s1:
globals()['pos'] = mb
return True
elif list2[mb] > s1:
ub = mb -1
else:
ub = mb +1
return False
list1 = [34, 56, 44, 21, 8, 4, 87, 36]
list1.sort(reverse=False)
s = 8
if search(list1, s):
print("Value Found at " + str(pos+1))
else:
print("Value Not Found")
|
b6c29cc54ac09ba7fa626c8cd6697086865da253 | mannhuynh/Python-Codes | /DSandA/python_basic.py | 684 | 3.96875 | 4 | # Write a function called "show_excitement" where the string
# "I am super excited for this course!" is returned exactly
# 5 times, where each sentence is separated by a single space.
# Return the string with "return".
# You can only have the string once in your code.
# Don't just copy/paste it 5 times into a single variable!
def show_excitement():
# Your code goes here!
count = 1
string = "I am super excited for this course! "
new_string = ''
for i in range(5):
new_string += string
return new_string
# result = ''
# while count <= 5:
# result += string
# count += 1
# return result
print(show_excitement())
|
2ebf1cd9f8cf3ea30aa602cd50f069def02ce10b | rosworld07/pythonprograms | /python programs/tupel1.py | 217 | 3.859375 | 4 |
t=10,20,30,40
print(type(t))
t=10 # for single value we have to put , other wise it will treat as a int
print(type(t))
t=10,
print(type(t))
#by using tupel function
l=[1,2,3,4,5]
t=tuple(l)
print(t) |
add04c452b24e3f409a85ea59a5bcf2dd7f174ec | tyree88/Object-Oriented-Programming | /HTML.py | 2,744 | 3.828125 | 4 | class Stack:
def __init__(self):
self.items = [ ]
def isEmpty (self):
return self.items == [ ]
def push (self, item):
self.items.append (item)
def pop (self):
return self.items.pop ()
def peek (self):
return self.items[-1]
def size (self):
return len(self.items)
def __str__(self):
return str(self.items)
##################################################
def filterTag(tags):
exceptions = ["meta", "br", "hr"]
validTags = []
t = Stack()
#Go through each tag
for tag in tags:
#check for exception tag
if tag in exceptions:
print("Tag",tag,"does not need to match: stack is", str(t))
continue #continue on to next loop because no matching tag
if tag not in validTags:
#start of a tag
if tag[0] != '/':
#check if tag is not in valid tags
validTags.append(tag) # add to list of valid tags
print("New tag", tag,"found and added to list of valid tags")
t.push(tag) #push to top of stack
print("Tag %s pushed: stack is now %s" % (tag, t))
else:
validTags.append(tag)
#Matching tag found
lastTag = t.pop()
if ("/"+lastTag) == tag:
print("Tag", tag," matches top of stack: stack is now",str(t))
continue
if t.isEmpty():
print("Stack is empty, all matches found")
return
else:
#If an exception is found"
return
print()
#If stack is empty then all tags have been filtered and found
if t.isEmpty():
print("Process complete all matches found")
validTags.sort()
print("VALID TAGS = ", validTags)
print("EXCEPTIONS = ", exceptions)
def getTag(file):
openB = "<"
closeB = ">"
tags = []
for i in range(len(file)):
#if string contains the start of a bracket
if file[i] == "<":
tag = ''
i+=1
#Gather everything in between the brackets
while (file[i] != closeB and file[i] != " ") and i<= len(file):
tag+= file[i]#create string for whats in between the brackets
i+=1 #iterates through the len of each line in the file
tags.append(tag) #put every tag into a list
return tags
def main():
infile = open("HTML.txt", "r")
html = infile.readlines()
allTags = []
for line in html:
allTags += getTag(line)
print(allTags)
filterTag(allTags)
infile.close()
main()
|
bd750f03bc9fa8f802bee616bd8f22f8db4d6c24 | ParulProgrammingHub/assignment-1-riyashekann | /prog4.py | 149 | 3.84375 | 4 | print"Celsius to Farhenheit conversion"
cel=input("enter the temperature in celsius")
far=cel*1.8 +32
print "The temperature in farheinheit is",far
|
00a1d4afed66c5420beb8751de0bce6a8afb911f | dcontant/checkio | /every_person_is_unique.py | 1,899 | 3.796875 | 4 | from datetime import date
class Person:
def __init__(self, first_name, last_name, birth_date, job, working_years, salary, country, city, gender='unknown'):
self.first_name = first_name
self.last_name = last_name
self.birth_date = date(*[int(data) for data in birth_date.split('.')[::-1]])
self.job = job
self.working_years = working_years
self.salary = salary
self.country = country
self.city = city
self.gender = gender
def name(self):
return self.first_name + ' ' + self.last_name
def age(self):
return (date(2018,1,1) - self.birth_date).days // 365
def work(self):
prefix = {'male': 'He is ', 'female': 'She is ', 'unknown': 'Is '}
return '{gender}a {job}'.format(gender=prefix[self.gender], job=self.job)
def money(self):
total_money = self.salary * 12 * self.working_years
millions = (str(total_money // 10**6)+' ') * bool(total_money // 10**6)
thousands = (str(total_money%10**6 // 1000)+' ') * bool(total_money // 1000)
hundreds = str(total_money%1000)
return '{0}{1}{2:0<3}'.format(millions, thousands, hundreds)
def home(self):
return 'Lives in {self.city}, {self.country}'.format(self=self)
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
p1 = Person("John", "Smith", "19.09.1979", "welder", 15, 3600, "Canada", "Vancouver", "male")
p2 = Person("Hanna Rose", "May", "05.12.1995", "designer", 2.2, 2150, "Austria", "Vienna")
assert p1.name() == "John Smith", "Name"
assert p1.age() == 38, "Age"
assert p2.work() == "Is a designer", "Job"
assert p1.money() == "648 000", "Money"
assert p2.home() == "Lives in Vienna, Austria", "Home"
print("Coding complete? Let's try tests!")
|
f013b87c15f2d21bbf286fa38b12d7da5a5172be | Khushal-ag/Python_Programs | /Data Structures/Dictionary/invert_key-value.py | 216 | 3.640625 | 4 | n,d1,d2 = int(input("Enter key-pairs to be enter: ")),{},{}
for i in range(n):
k = eval(input("Enter key: "))
v = input("Enter value: ")
d1[k] = v
print(d1)
for i in d1.keys():
d2[d1[i]] = i
print(d2) |
f5e065163236b6a311598f841cf518b5c48e426d | Edward-Sekula/OS-GCSE-computing-course | /python/snake eyes.py | 1,181 | 3.6875 | 4 | import random
def turn(player,playerscore):
print(player)
go=True
while go==True:
runscore1 = 0
d1 = random.randint(1,6)
d2 = random.randint(1,6)
runscore1 = (runscore1+d1+d2)
print(d1,' and ',d2)
if d1 == 1 or d2 == 1:
runscore1 = 0
print('snakeeyes no score')
if d1 ==1 and d2==1:
print('banked score set to zero')
p1ayerscore=0
go=False
else:
print('you lost running total set to zero')
go=False
else:
x = int(input('1.bank\n2.gamble\n'))
if x == 1:
playerscore = playerscore+runscore1
runscore1 = 0
go=False
elif x == 2:
print('gamble')
return playerscore
player1name="player1"
player2name="player2"
p1score=0
p2score=0
while p1score<20 and p2score<20:
p1score=turn(player1name,p1score)
if p1score<20:
p2score=turn(player2name,p2score)
if p1score>20:
print("p1 win")
else:
print("p2 wins")
|
aa3f2d98c1a730bf0efb94d942714feeaebd4ed1 | ruozhizhang/leetcode | /problems/linked_list/Flatten_a_Multilevel_Doubly_Linked_List.py | 1,352 | 4.125 | 4 | '''
https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/
You are given a doubly linked list which in addition to the next and previous pointers,
it could have a child pointer, which may or may not point to a separate doubly linked list.
These child lists may have one or more children of their own, and so on,
to produce a multilevel data structure, as shown in the example below.
Flatten the list so that all the nodes appear in a single-level, doubly linked list.
You are given the head of the first level of the list.
Constraints:
Number of Nodes will not exceed 1000.
1 <= Node.val <= 10^5
'''
"""
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:
def flatten(self, head: 'Node') -> 'Node':
if not head:
return head
s = [head]
while s:
cur = s.pop()
if cur.next:
s.append(cur.next)
if cur.child:
cur.next = cur.child
cur.child.prev = cur
s.append(cur.child)
cur.child = None
if not cur.next and not cur.child and s:
cur.next = s[-1]
s[-1].prev = cur
return head
|
a2fc78ecf32c14753e715f978e1a0501d7218ccb | zakkudata/python-automation-course | /module_0_basics/funciones_frecuencia_palabras.py | 1,741 | 4.375 | 4 | """
Escribir un programa que reciba una cadena de caracteres y devuelva un diccionario con cada palabra que contiene y su frecuencia. Escribir otra función que reciba el diccionario generado con la función anterior y devuelva una tupla con la palabra más repetida y su frecuencia.
text = 'Como quieres que te quiera si el que quiero que me quiera no me quiere como quiero que me quiera'
"""
from collections import Counter
def frecuencia_palabras_counter(texto):
c = Counter(texto.split())
return dict(c)
def palabra_mas_repetida_counter(diccionario_palabras):
c = Counter(diccionario_palabras)
return c.most_common(1)[0]
def frecuencia_palabras(texto):
dic_frec = {}
print(texto.split())
for palabra in texto.split():
print(palabra)
if palabra in dic_frec.keys():
dic_frec[palabra] += 1
print("Frecuencia +1")
else:
dic_frec[palabra] = 1
print("Añadida nueva palabra al diccionario")
print(dic_frec)
return dic_frec
def palabra_mas_repetida(diccionario_palabras):
frecuencia_max = 0
for t in diccionario_palabras.items():
if t[1] > frecuencia_max:
tupla_max = t
frecuencia_max = t[1]
return tupla_max
# Main
mi_diccionario = frecuencia_palabras("Como quieres quieres mesa quieres")
tupla_max = palabra_mas_repetida(mi_diccionario)
print(f"La palabra más repetida es '{tupla_max[0]}' con frecuencia {tupla_max[1]}.")
print("\nUsando Counter")
mi_diccionario = frecuencia_palabras_counter("Como quieres quieres mesa quieres")
tupla_max = palabra_mas_repetida_counter(mi_diccionario)
print(f"La palabra más repetida es '{tupla_max[0]}' con frecuencia {tupla_max[1]}.") |
e70a8a73dc030e4a3a72528294dab12bd7548a08 | bodik10/EulerSolving | /euler 056.py | 343 | 3.5 | 4 | maxSum = maxA = maxB = maxAB = 0
for a in range(99, 1, -1):
for b in range(99, 1, -1):
ab = str(a**b)
sumAB = sum(map(int, ab))
if sumAB > maxSum:
maxSum = sumAB
maxA, maxB, maxAB = a, b, ab
print ("Number %d^%d = %s has maximum digital sum (%d)" % (maxA, maxB, maxAB, maxSum))
|
6e10c7944cf26e6f6d8b35d4656a3db82fee13e8 | mayconrcampos/Python-Curso-em-Video | /Exercicios/Exercício - 069 - Análise de dados do Grupo - Jeito do Guanabara.py | 822 | 3.8125 | 4 | cont = cont_18 = cont_mulher = cont_homens = 0
while True:
print('-=' * 20)
print(' VALIDAÇÃO DE DADOS - IDADE E SEXO ')
idade = int(input('IDADE: '))
if idade >= 18:
cont_18 += 1
sexo = ' '
while sexo not in 'MF':
sexo = str(input('SEXO: M/F: ')).upper()
print('--' * 20)
if sexo == 'M':
cont_homens += 1
elif sexo == 'F' and idade < 20:
cont_mulher += 1
resp = ' '
while resp not in 'SN':
resp = str(input('Continua, S/N? ')).upper()
print('-=' * 20)
cont += 1
if resp == 'N':
break
print(f'{cont} pessoas foram cadastradas IDADE e SEXO. E destas...')
print(f'{cont_18} pessoas tem acima de 18 anos.')
print(f'{cont_homens} homens foram cadastrados.')
print(f'{cont_mulher} mulheres tem menos de 20 anos.') |
3dc8e3bc04eab330995f57fe21159d36869bb833 | neo4reo/euler | /euler 0079.py | 1,726 | 3.625 | 4 |
def addToPasscode(num, order, passcode):
if len(passcode) == 0:
#empty list
return [num]
elif passcode.count(num) > 0:
#already part of passcode
return passcode
# find last slot (0-2) that the number is used in
# must place num before any members of slots to right
# must place num after any members of slots to the left
for i in range(0, len(passcode)):
if not (passcode[i] in (order[num]['before'])):
if passcode[i] in order[num]['after']:
passcode.insert(i, num)
print(passcode)
return passcode
else:
passcode.insert(i+1, num)
print(passcode)
return passcode
# add to end of the list
passcode.append(num)
print(passcode)
return passcode
order = {}
f = open('keylog.txt', 'r')
# Build a before and after list for each num
for line in f.readlines(): #["319","680","180"]:
a, b, c = int(line[0]), int(line[1]), int(line[2])
if not a in order: order[a] = {'before': set(), 'after': set()}
if not b in order: order[b] = {'before': set(), 'after': set()}
if not c in order: order[c] = {'before': set(), 'after': set()}
print(a,b,c)
order[a]['after'].add(b)
order[a]['after'].add(c)
order[b]['before'].add(a)
order[b]['after'].add(c)
order[c]['before'].add(a)
order[c]['before'].add(b)
print(order)
passcode = []
f = open('keylog.txt', 'r')
for line in f.readlines(): #["319","680","180"]:
for i in range(0, 3):
passcode = addToPasscode(int(line.strip()[i]), order, passcode)
print(passcode)
|
451848899d8fc3c30878cad09386a7fd578afbe3 | All-Ears/backend | /app/models.py | 5,440 | 3.75 | 4 | from typing import Iterable, Optional, Tuple
from abc import ABC, abstractmethod
class InvalidRecordError(Exception):
pass
class MikeRecord:
class PrimaryKey(tuple):
def __new__(cls, mike_site_id: str, year: int):
if len(mike_site_id) == 3 and year >= 0:
return super().__new__(cls, (mike_site_id, year))
else:
raise InvalidRecordError()
def __init__(self, un_region: str, subregion_name: str, subregion_id: str,
country_name: str, country_code: str, mike_site_id: str,
mike_site_name: str, year: int,
carcasses: int, illegal_carcasses: int) -> None:
if len(subregion_id) == 2 and len(country_code) == 2 and len(
mike_site_id) == 3 and year >= 0 and carcasses >= 0 and illegal_carcasses >= 0:
self.un_region = un_region
self.subregion_name = subregion_name
self.subregion_id = subregion_id.lower()
self.country_name = country_name
self.country_code = country_code.lower()
self.mike_site_id = mike_site_id.lower()
self.mike_site_name = mike_site_name
self.year = year
self.carcasses = carcasses
self.illegal_carcasses = illegal_carcasses
else:
raise InvalidRecordError()
def get_primary_key(self) -> PrimaryKey:
return self.PrimaryKey(self.mike_site_id, self.year)
def to_tuple(self) -> Tuple[str, str, str, str, str, str, str, int, int, int]:
"""
Returns this object as a tuple
:return: (un_region, subregion_name, subregion_id, country_name, country_code, mike_site_id, mike_site_name,
mike_year, carcasses, illegal_carcasses)
"""
return (self.un_region,
self.subregion_name,
self.subregion_id,
self.country_name,
self.country_code,
self.mike_site_id,
self.mike_site_name,
self.year,
self.carcasses,
self.illegal_carcasses)
@classmethod
def from_tuple(cls, tuple_record: Tuple[str, str, str, str, str, str, str, int, int, int]):
"""
Constructs a MikeRecord from a tuple
:param tuple_record: (un_region, subregion_name, subregion_id, country_name, country_code, mike_site_id,
mike_site_name, year, carcasses, illegal_carcasses)
:return: MikeRecord
"""
return cls(tuple_record[0], tuple_record[1], tuple_record[2], tuple_record[3], tuple_record[4], tuple_record[5],
tuple_record[6], tuple_record[7], tuple_record[8], tuple_record[9])
class CountryRecord:
class PrimaryKey(tuple):
def __new__(cls, country_code: str, year: int):
return super().__new__(cls.__class__, (country_code, year))
def __init__(self, country_name: str, country_code: str, year: int, carcasses: int,
illegal_carcasses: int) -> None:
self.country_name = country_name
self.country_code = country_code
self.year = year
self.carcasses = carcasses
self.illegal_carcasses = illegal_carcasses
def get_primary_key(self) -> PrimaryKey:
return self.PrimaryKey(self.country_code, self.year)
@classmethod
def from_tuple(cls, tuple_record: Tuple[str, str, int, int, int]):
"""
Constructs a CountryRecord from a tuple
:param tuple_record: (country_name, country_code, year, carcasses, illegal_carcasses)
:return: CountryRecord
"""
return cls(tuple_record[0], tuple_record[1], tuple_record[2], tuple_record[3], tuple_record[4])
# Data Provider Interfaces
class DataAccessError(Exception):
pass
class NoMasterPasswordError(Exception):
pass
class MasterPasswordProvider(ABC):
@abstractmethod
def verify_pwd(self, plain_pwd: str) -> bool:
pass
@abstractmethod
def set_master_pwd(self, new_pwd: str):
pass
class InvalidPrimaryKeyOperationError(DataAccessError):
def __init__(self, record: MikeRecord):
self.record = record
super().__init__()
class MikeRecordProvider(ABC):
@abstractmethod
def add_mike_record(self, record: MikeRecord):
pass
@abstractmethod
def add_mike_records(self, records: Iterable[MikeRecord]):
pass
@abstractmethod
def add_or_overwrite_mike_records(self, records: Iterable[MikeRecord]):
pass
@abstractmethod
def get_mike_record(self, record_key: MikeRecord.PrimaryKey) -> Optional[MikeRecord]:
pass
@abstractmethod
def get_all_mike_records(self) -> Iterable[MikeRecord]:
pass
@abstractmethod
def update_mike_record(self, record: MikeRecord):
pass
@abstractmethod
def update_mike_records(self, records: Iterable[MikeRecord]):
pass
@abstractmethod
def remove_mike_record(self, record_key: MikeRecord.PrimaryKey):
pass
@abstractmethod
def remove_mike_records(self, record_keys: Iterable[MikeRecord.PrimaryKey]):
pass
class CountryRecordProvider(ABC):
@abstractmethod
def get_country_record(self, record_key: CountryRecord.PrimaryKey) -> Optional[CountryRecord]:
pass
@abstractmethod
def get_all_country_records(self) -> Iterable[CountryRecord]:
pass
|
4d63a157fbc26497c0088427a782ba216aa5e7aa | whojayantkumar/py-projects | /RockPaperScissors/main.py | 573 | 3.953125 | 4 | import random
def play():
user_choice = input("What is Your choice ? \n 'r' for rock, 'p' for paper, 's' for scissors : ").lower()
computer_choice = random.choice(['r','p','s'])
if computer_choice == user_choice:
return 'It\'s a tie'
if is_win(computer_choice, user_choice):
return "You Won!"
return "You lost!"
def is_win(opponent, player):
if (player == 'r' and opponent == "s") or (player == 'p' and opponent == "r") or (player == 's' and opponent == "p"):
return True
if __name__ == "__main__":
print(play()) |
5f8f0e7a293cc93b75ab59c72fa1421c79af38b0 | rabiixx/GestionSistemas | /P0-IntroPython/test.py | 1,644 | 4.53125 | 5 | # Python3 List Methods
# append(): add a single element at the end of the list
# animal list
animal = ['cat', 'dog', 'rabbit']
# an element is added
animal.append('guinea pig')
#Updated Animal List
print('Updated animal list: ', animal)
# >>>Updated animal list: ['cat', 'dog', 'rabbit', 'guinea pig']
# extend(): Add Elements of a list to another list
# insert(index, type): Add a elements in the gives index
mixed_list = [{1, 2}, [5, 6, 7]]
# number tuple
number_tuple = (3, 4)
# inserting tuple to the list
mixed_list.insert(1, number_tuple)
print('Updated List: ', mixed_list)
#################
# vowel list
vowel = ['a', 'e', 'i', 'u']
# inserting element to list at 4th position
vowel.insert(3, 'o')
print('Updated List: ', vowel)
# remove(): Removes Element from the List
# animal list
animal = ['cat', 'dog', 'rabbit', 'guinea pig']
# 'rabbit' element is removed
animal.remove(animal[1])
animal.remove('rabbit')
#Updated Animal List
print('Updated animal list: ', animal)
# index(element): returns smallest index if element in list
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# element 'e' is searched
index = vowels.index('e')
# index of 'e' is printed
print('The index of e:', index)
# element 'i' is searched
index = vowels.index('i')
# only the first index of the element is printed
print('The index of i:', index)
# >>> The index of e: 1
# >>> The index of i: 2
# count(element): returns occurrences of element in a list
# pop(index): Removes element at given index
# sort(): sorts elements of a list
# clear(): removes all items from a list
#
|
264ab705d69494e20fa9476922b77ac80358e77d | Brunoenrique27/Exercicios-em-Python | /desafio14 - Conversor de Temperaturas.py | 166 | 4 | 4 | print('Conversao de temperatura de c pra f')
c = float(input('Digite uma temperatura em ºC'))
f = ((9*c)/5)+32
print(f'A temperatura de {c}ºC corresponde a {f}"F!') |
1cf5da4684052ca774e679484568662affa78878 | matdelaterra/Desarrollos | /DifFinCalor.py | 7,452 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 2 10:24:15 2019
@author: Jorge Antonio Matias López
"""
#Programa que soluciona la ecuación de laplace mediante diferencias finitas, ejemplo del libro Numerical Analysis
#capitulo 12.1 generalizado para n dimensiones
import numpy as np
import matplotlib.pyplot as plt
import math
from time import time
####################################################################
def sumalista(listaNumeros):#suma los elementos de una lista
Suma = 0
for i in listaNumeros:
Suma = Suma + i
return Suma
####################################################################
def posicion(n,i,j):#posicion en la matriz
pos=(n-1)*(i-1)+j-1
return pos
#####################################################################
def gauss(matriz,vect,tol):#Método de Gauss-Seidel
print('Gauss-Seidel')
dim=matriz.shape
comp=np.zeros(dim[0])
itera=1000
res=np.zeros(dim[0])
error=[]
k=0
t_ini=time()
while k<itera:
suma=0
k=k+1
for ren in range(0,dim[0]):
suma=0
for col in range(0,dim[1]):
if (col != ren):
suma=suma+matriz[ren,col]*res[col]
res[ren]=(vect[ren]-suma)/matriz[ren,ren]
del error[:]
#Comprobación
for ren in range(0,dim[0]):
suma=0
for col in range(0,dim[1]):
suma=suma+matriz[ren,col]*res[col]
comp[ren]=suma
dif=abs(comp[ren]-vect[ren])
error.append(dif)
#print('Iteracion',k)
if all( i<=tol for i in error) == True:
break
t_fin=time()
t_ejecucion=round(t_fin-t_ini,10)
print(res)
print('El tiempo de ejecución Gauss-Seidel es '+str(t_ejecucion)+' segundos')
return(res)
###############################################################################
def gauss_crs(matriz,vector,tol):#Gauss-seidel con CRS
print('CRS Gauss-Seidel')
x,y=matriz.shape
val=[]
col_ind=[]
ren_elem=[]
di=[]
cont=0
for i in range(x):
ren_elem.append(cont)
for j in range(y):
if i!=j:
if matriz[i,j]!=0:
val.append(matriz[i,j])
col_ind.append(j)
cont=cont+1
else:
di.append(matriz[i,j])
valor=np.array(val)
col=np.array(col_ind)
ren=np.array(ren_elem)
diag=np.array(di)
#return(valor,col,ren,diag)
##GaussSeidel
maxitera=1000
res=np.zeros(x)
exa=np.linalg.solve(matriz,vector)
error=[]
k=0
t_ini=time()
while k<maxitera:
suma=0
k=k+1
for i in range(0,ren.size):
suma=0
if i != ren.size-1:
for j in range(ren[i],ren[i+1]):
suma=suma+valor[j]*res[col[j]]
res[i]=(vector[i]-suma)/diag[i]
else:
for j in range(ren[i],valor.size):
suma=suma+valor[j]*res[col[j]]
res[i]=(vector[i]-suma)/diag[i]
del error[:]
#Comprobación
for i in range(0,res.size):
dif=abs(exa[i]-res[i])
error.append(dif)
if all( i<=tol for i in error) == True:
break
t_fin=time()
t_ejecucion=round(t_fin-t_ini,10)
#print(res)
print('El tiempo de ejecución CRS_gauss es '+str(t_ejecucion)+' segundos')
return res
################################################################################
def matbld():#construccion de la matriz cuadrada de tamaño n y el vector de constantes
const=[]#vector de constantes
mat=[]#renglón de la matriz(se anexa un renglón en cada ciclo)
for k in range(0,(n-1)**2):#llena el renglón auxiliar con ceros
mat.append(0)
pos=posicion(n,i,j)
mat[pos]=4
#condiciones de frontera
if j-1>0:
mat[posicion(n,i,j-1)]=-1
else:
const.append(0)
if j+1<n:
mat[posicion(n,i,j+1)]=-1
else:
const.append((n-i)*grad)
if i-1>0:
mat[posicion(n,i-1,j)]=-1
else:
const.append(j*grad)
if i+1<n:
mat[posicion(n,i+1,j)]=-1
else:
const.append(0)
matriz.append(mat)#agregla el renglón creado a la matriz principal
#agrega la suma de los coeficientes en las fronteras al vector de coeficientes
vector.append(sumalista(const))
return()
##########################################################################################################
def solexa(n,i,j):#solucion exacta
x=(j+1)*dx
y=(n-i-1)*dy
exa=abs(400*x*y)
'''print('x','y','Solución exacta')
print(x,y,exa)'''
return(exa)
##########################################################################################################
def error(exa,cal,n):
err=np.zeros([(n-1),(n-1)])
for i in range(n-1):
for j in range(n-1):
err[i,j]=abs(exa[i,j]-cal[i,j])#error
err[i,j]=err[i,j]**2
error=math.sqrt(np.sum(err))
return(error)
###########################################################################################################
###########################################################################################################
#### Inicio ###
e=[]
tam=[]
for k in range(4,17,2):
matriz=[]
vector=[]
mx=100#condición de frontera (valor máximo)
n=k
print('n='+str(n))
tol=0.00000001
grad=mx/n
#Tamaño del dominio
lx=0.5
ly=0.5
dx=lx/n
dy=ly/n
for i in range(1,n):
for j in range(1,n):
matbld()
mat=np.array(matriz)
vec=np.array(vector)
#soluciones por diferentes metodos
solucion=np.linalg.solve(mat,vec)#solución del sistema de ecuaciones linalg python
#sol_gauss=gauss(mat,vec,tol)#solucion Gauss-Seidel
# solucion=gauss_crs(mat,vec,tol)#solucion Gauss-Seidel matriz CRS
solcal=np.zeros([(n-1),(n-1)])
sol=np.zeros([(n-1),(n-1)])
solex=np.zeros([(n-1),(n-1)])
for i in range(n-1):
for j in range(n-1):
solex[i,j]=solexa(n,i,j)#matriz solución exacta
solcal[i,j]=solucion[(i*(n-1))+j]#matriz solucion calculada
sol[i,j]=round(solucion[(i*(n-1))+j],2)#matriz solución calculada
errorN2=error(solex,solcal,n)
# e.append(errorN2)
# tam.append(n)
e.append(math.log10(errorN2))
tam.append(math.log10(n))
# e.append(-math.log10(errorN2))
# tam.append(math.log10(n))
X=np.array(tam)
Y=np.array(e)
#razón de convergencia
fig,ax0=plt.subplots()
ax0.plot(X,Y)
ax0.grid()
ax0.set(xlabel='tamaño', ylabel='Error',
title='Razón de convergencia -log-log')
#graficas
'''fig, ax = plt.subplots()#Solo genera una grafica
im = ax.imshow(sol)
for i in range(sol.shape[0]):
for j in range(sol.shape[0]):
text = ax.text(j, i, sol[i, j],ha="center",
va="center", color="w")
ax.set_title("Solución °C")
cbar = fig.colorbar(im)
fig.tight_layout()'''
plt.show |
a057f30f6641944dee626fa198349989271d6051 | hania250/AnimalShelter_manager | /AnimalShelter.py | 3,053 | 4.03125 | 4 |
class Animal:
def __init__(self, name, date, condition, vaccination):
self.name = name
self.date = date
self.condition = condition
self.vaccination = vaccination
def print(self):
print(self.name, self.date, self.condition)
def set_vaccination(self, value):
if value == 'tak':
self.vaccination = True
else:
self.vaccination = False
class AnimalBot:
def __init__(self):
self.list = []
def add_animal(self, name, date, condition, vaccination):
a = Animal(name, date, condition, vaccination)
self.list.append(a)
def print_animal(self, index):
animal = self.list[index]
print('{:2} | {:5} | {:5} | {:5} | {:5}'.format(index, animal.name, animal.date, animal.condition, animal.vaccination))
def add_animal_from_input(self):
name = input('Podaj imie: ')
date = input('Data przyjecia: ')
condition = input('Podaj stan: ')
vaccination = input("Czy zwierzak był szczepiony? ")
if vaccination == "tak":
vaccination = True
else:
vaccination = False
self.add_animal(name, date, condition, vaccination)
def print_all_animals(self):
for index in range(len(self.list)):
self.print_animal(index)
def set_animal_vaccination(self, animal_index, vaccination):
animal = self.list[animal_index]
animal.set_vaccination(vaccination)
def print_vaccinated(self):
for i in range(len(self.list)):
animal = self.list[i]
if animal.vaccination:
self.print_animal(i)
def save_animals(self):
text_animals = []
for i in range(len(self.list)):
animal = self.list[i]
text = '{};{};{};{}'.format(animal.name, animal.date, animal.condition, animal.vaccination)
text_animals.append(text)
with open('shelter.csv', 'w') as f:
for line in text_animals:
f.write(line + '\n')
def load_animals(self):
with open('shelter.csv', 'r') as f:
for line in f:
animal_list = line.split(';') # tworzy listę elementow
if animal_list[3] == 'True\n':
vaccination = True
else:
vaccination = False
self.add_animal(animal_list[0], animal_list[1], animal_list[2], vaccination)
bot = AnimalBot()
bot.load_animals()
while True:
command = input('Co chcesz zrobic? ')
if command == 'dodaj':
bot.add_animal_from_input()
elif command == 'wszystkie':
bot.print_all_animals()
elif command == 'zmien':
index = int(input('Podaj indeks:'))
vaccination = input('czy byl szczepiony? ')
bot.set_animal_vaccination(index, vaccination)
elif command == 'pokaz zaszczepione':
bot.print_vaccinated()
elif command == 'zapisz':
bot.save_animals()
else:
print('Nie wiem co zrobic ') |
5539eb396047b06caf644b17189205b309c3f84a | connormcl10/turtleletters2020 | /turletters.py | 2,752 | 3.609375 | 4 | import turtle
def turtleLetter(letter,tur):
if letter=="box":
tur.setheading(0)
tur.forward(40)
tur.right(90)
tur.forward(60)
tur.right(90)
tur.forward(40)
tur.right(90)
tur.forward(60)
elif letter == "A":
tur.setheading(0)
tur.pu()
tur.fd(5)
tur.right(90)
tur.fd(5)
tur.pd()
tur.fd(30)
tur.right(180)
tur.fd(30)
tur.right(90)
tur.fd(20)
tur.right(90)
tur.fd(30)
tur.right(180)
tur.fd(15)
tur.left(90)
tur.fd(20)
tur.pu()
#fixes
tur.right(90)
tur.fd(20)
tur.right(90)
tur.fd(35)
#tur.right(180)
elif letter == "B":
tur.setheading(0)
tur.left(90)
tur.fd(100)
tur.right(90)
tur.td(40)
tur.right(90)
tur.fd(50)
tur.right(90)
tur.fd(40)
tur.left(180)
tur.fd(50)
tur.right(90)
tur.fd(50)
tur.right(90)
tur.fd(50)
tur.right(90)
tur.fd(100)
tur.right(90)
tur.fd(50)
elif letter == "C":
pass
elif letter == "D":
import turtle
t = turtle.Turtle()
t.up()
t.backward(400)
t.left(90)
t.down()
t.forward(250)
t.right(90)
t.forward(62.5)
t.backward(62.5 * 2)
t.forward(62.5)
t.right(90)
t.forward(250)
t.right(90)
t.forward(62.5)
t.backward(62.5 * 2)
t.up()
t.backward(100)
t.right(90)
t.down()
t.forward(250)
for x in range(180):
t.forward(1)
t.right(1)
elif letter == "E":
pass
elif letter == "F":
pass
elif letter == "G":
pass
elif letter == "H":
pass
elif letter == "I":
pass
elif letter == "J":
pass
elif letter == "K":
pass
elif letter == "L":
pass
elif letter == "M":
pass
elif letter == "N":
pass
elif letter == "O":
pass
elif letter == "P":
pass
elif letter == "Q":
pass
elif letter == "R":
pass
elif letter == "S":
pass
elif letter == "T":
pass
elif letter == "U":
pass
elif letter == "V":
pass
elif letter == "W":
pass
elif letter == "X":
pass
elif letter == "Y":
pass
elif letter == "Z":
pass
elif letter == "Ax":
# code here
tur.forward(40)
else:
#handles space, punctuation, and anything else
tur.forward(40)
if __name__ == "__main__":
window = turtle.Screen()
tur = turtle.Turtle()
tur.speed(1)
#turtleLetter("box",tur)
turtleLetter("A",tur)
window.exitonclick()
|
8d8446a68ddabba4d8c6d958577650d358a4e441 | jmctsm/Udemy_2020_Complete_Python_BootCamp | /polymorphism_practice.py | 980 | 3.875 | 4 | class Dog():
def __init__(self, name):
self.name = name
def speak(self):
return self.name + " says woof!"
class Cat():
def __init__(self, name):
self.name = name
def speak(self):
return self.name + " says meow!"
niko = Dog("niko")
felix = Cat("felix")
print(niko.speak())
print(felix.speak())
def pet_speak(pet):
print(pet.speak())
for pet in [niko, felix]:
print(type(pet))
print(type(pet.speak()))
print(pet.speak())
pet_speak(niko)
class Animal():
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("SubClass must implement this abtstact method")
class Dog(Animal):
def speak(self):
return self.name + " says woof!!"
class Cat(Animal):
def speak(self):
return self.name + " says meow!!"
#my_animal = Animal("Fred")
#my_animal.speak()
fido = Dog("Fido")
isis = Cat("Isis")
print(fido.speak())
print(isis.speak())
|
9be39685ddad8440058924a59518b0f746dc0020 | zedaster/ImaevIntensive | /12easy/12_4.py | 190 | 3.640625 | 4 | s = '1' * 82
while '1'*5 in s or '888' in s:
if '1'*5 in s:
s = s.replace('1'*5, '88', 1)
elif '888' in s:
s = s.replace('888', '8', 1)
print(s, len(s))
print(s) |
bea8d8985c7d788e65de369ec99731e03040cb78 | NefiTS/Login | /login.py | 4,501 | 3.515625 | 4 | from PyQt5 import uic,QtWidgets #Qwidgets para trabalhar com elementos graficos
import sqlite3 #importando o sqllite3
def chama_segunda_tela(): # Ao clicar no botão de login vai executar a lógica de comparação dos dados digitados com os que contém no sistema
primeira_tela.label_4.setText("") #string vazia para limpar o campo
nome_usuario = primeira_tela.lineEdit.text() # pega a primeira caixa de texto que o usuario digitou e guarda nessa variavel
senha = primeira_tela.lineEdit_2.text() # O mesmo para a senha
banco = sqlite3.connect('banco_cadastro.db') #Declarado a conexão com o banco
cursor = banco.cursor() # Criando a variavel de cursor para fazer as querys no banco
try:
cursor.execute("SELECT senha FROM cadastro WHERE login='{}'".format(nome_usuario)) # Pegar a senha gravada no banco de dados, passando cadastro como nome da tabela,
# pegar a senha na mesma linha onde o login tem o mesmo valor que o usuario digitou
senha_bd = cursor.fetchall()#recuperando a senha do banco para posteriormente realizar a validação
banco.close() # Sempre fechar a conexão com o banco
except:
print("Erro ao validar o Login") # Criando exceção para não fechar o banco mesmo digitando usuário inexistente
if senha == senha_bd[0][0] : #Definindo as credencias para comparação
primeira_tela.close() # confirmação de login
segunda_tela.show() #dentro do sistema
else:
primeira_tela.label_4.setText(" Dados de Login Incorretos ! ") # caso não for conforme acima não inicializa uma nova tela e informa o erro
def logout(): # Pega a segunda tela de logout e fecha e abre a primeira tela de login
segunda_tela.close() #fechar
primeira_tela.show() #abrir
def abre_tela_cadastro(): # Ao clicar no botão de abrir a tela de cadastro
tela_cadastro.show() # colocando a tela na função para ser chamado posteriormente pelo botão
def cadastrar(): #Lógica de pegar os dados da tela e colocar no banco
nome = tela_cadastro.lineEdit.text() # Pegar os dados do formulário, usando a line corresponde com a função teste salvando na variável
login = tela_cadastro.lineEdit_2.text()
senha = tela_cadastro.lineEdit_3.text()
c_senha = tela_cadastro.lineEdit_4.text()
if (senha == c_senha): # verificando se a senha inserida no primeiro campo é igual a do segundo campo para confirmação
try: # tentar cadastrar no banco
banco = sqlite3.connect('banco_cadastro.db') #Função sqlite para criar o banco, connect serve para criar o banco caso já exista o mesmo não é criado
cursor = banco.cursor() # Objeto para manipular o banco com as query
cursor.execute("CREATE TABLE IF NOT EXISTS cadastro (nome text,login text,senha text)") # Criando a tabela caso não exista, caso já existir a linha é ignorada
cursor.execute("INSERT INTO cadastro VALUES ('"+nome+"','"+login+"','"+senha+"')") # inserindo os dados inseridos no banco
banco.commit() # Commit(fazer as alterações no banco)
banco.close() # Fechar o banco de dados
tela_cadastro.label.setText("Usuario cadastrado com sucesso") # informando ao usuario que foi cadastrado com sucesso
except sqlite3.Error as erro: # caso de alguma excessão informar, informar o erro que aconteceu ao cadastrar
print("Erro ao inserir os dados: ",erro)
else:
tela_cadastro.label.setText("As senhas digitadas estão diferentes") # informando que as senhas digitas são diferentes
#Declaração dos arquivos gerados no QtDesigner
app=QtWidgets.QApplication([])
primeira_tela=uic.loadUi("primeira_tela.ui") #Carregando a primeira tela para utilização no código quando necessário
segunda_tela=uic.loadUi("segunda_tela.ui") # Carregando a segunda tela
tela_cadastro =uic.loadUi("tela_cadastro.ui")# Carregando a tela de cadastro
primeira_tela.pushButton.clicked.connect(chama_segunda_tela)
segunda_tela.pushButton.clicked.connect(logout)
primeira_tela.lineEdit_2.setEchoMode(QtWidgets.QLineEdit.Password) # usando QtWidgets com o nome da Classe QlineEdit e usando para criar um campo do tipo senha
primeira_tela.pushButton_2.clicked.connect(abre_tela_cadastro) # Para quando clicar no botão chamar a tela de cadastro
tela_cadastro.pushButton.clicked.connect(cadastrar)
primeira_tela.show()
app.exec()
|
eeaaa1d97ace05a8fbe5208f5da9bd8ebe8c4822 | manavnarang/Hackerrank-30-days-of-Code | /Day 6: Let's Review/LetsReview.py | 279 | 3.671875 | 4 | T=int(input( ))
for i in range(0,T):
string=input( )
for j in range(0,len(string)):
if(j%2==0):
print(string[j], end='')
print(' ',end='')
for j in range(0, len(string)):
if(j%2!=0):
print(string[j],end='')
print("")
|
339369e196cbc022f5c14566ba82bab11d579ae2 | vijayroykargwal/Infy-FP | /PF/Day4/src/Assign31.py | 408 | 4.09375 | 4 | #PF-Assgn-31
'''
Created on Feb 25, 2019
@author: vijay.pal01
'''
def check_palindrome(word):
str= word
str1=word[::-1]
if(str == str1):
return True
else:
return False
#Remove pass and write your logic here
status=check_palindrome("malayalam")
if(status):
print("word is palindrome")
else:
print("word is not palindrome")
|
89fa31ee3930f43ac84fb156d41502651f99b7ca | matiascevallos/COSC499GithubExercise | /List Sorting.py | 2,374 | 4.4375 | 4 | # This will sort lists that are either integer or string
def sortDescending(intList):
newSortedList = sorted(intList, key=int, reverse=True)
return newSortedList
def sortAscending(intList):
newSortedList = sorted(intList, key=int, reverse=False)
return newSortedList
def sortDescending(strList):
newSortedList = sorted(strList, key=str, reverse=True)
return newSortedList
def sortAscending(strList):
newSortedList = sorted(strList, key=str, reverse=False)
return newSortedList
def main():
typeOfList = input("Does your list have integers or strings? ")
if typeOfList == 'integers':
n = int(input("Enter the number of elements in your list: "))
userList = list(map(int,input("\nEnter the numbers : ").strip().split()))[:n]
print("\nUser's List: ", userList)
print(f'Your list sorted in descending order is: {sortDescending(userList)}')
print(f'Your list sorted in ascending order is: {sortAscending(userList)}')
if typeOfList == 'strings':
userList = list(map(str,input("\nEnter the strings : ").split()))
print("\nUser's List: ", userList)
print(f'Your list sorted in descending order is: {sortDescending(userList)}')
print(f'Your list sorted in ascending order is: {sortAscending(userList)}')
def testingStrings():
assert sortDescending(['abc', 'cde', 'zef']) == ['zef', 'cde', 'abc'], "Should be ['zef', 'cde', 'abc']"
assert sortAscending(['abc', 'cde', 'zef']) == ['abc', 'cde', 'zef'], "Should be ['abc', 'cde', 'zef']"
assert sortDescending(['abc', 'abcd', 'abbc']) == ['abcd', 'abc', 'abbc'], "Should be ['abcd', 'abc', 'abbc']"
assert sortAscending(['abc', 'abcd', 'abbc']) == ['abbc', 'abc', 'abcd'], "Should be ['abbc', 'abc', 'abcd']"
def testingIntegers():
assert sortDescending([1, 1, 1]) == [1, 1, 1], "Should be [1, 1, 1]"
assert sortAscending([1, 1, 1]) == [1, 1, 1], "Should be [1, 1, 1]"
assert sortDescending([1, 0, 0]) == [1, 0, 0], "Should be [0, 0, 0]"
assert sortAscending([1, 0, 0]) == [0, 0, 1], "Should be [0, 0, 1]"
assert sortDescending([-1, 0, 10000000]) == [10000000, 0, -1], "Should be [10000000, 0, -1]"
assert sortAscending([-1, 0, 10000000]) == [-1, 0, 10000000], "Should be [-1, 0, 10000000]"
#testingStrings()
#testingIntegers()
main() |
b726d6f7023faadb5f1db110be112cf8f158a8cc | hrishikeshtak/Coding_Practises_Solutions | /leetcode/LeetCode-150/Graphs/695-Max-Area-of-Island.py | 1,231 | 3.578125 | 4 | """
695. Max Area of Island
"""
from typing import List
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
if not grid:
return 0
rows, cols = len(grid), len(grid[0])
q = []
visited = set()
island = 0
dirs = [[0, -1], [0, 1], [-1, 0], [1, 0]]
ans = 0
def bfs(i, j):
q.append((i, j))
visited.add((i, j))
area = 1
while q:
r, c = q.pop(0)
for dr, dc in dirs:
row, col = r + dr, c + dc
if row in range(rows) and \
col in range(cols) and \
grid[row][col] == 1 and \
(row, col) not in visited:
area += 1
q.append((row, col))
visited.add((row, col))
return area
for i in range(rows):
for j in range(cols):
if grid[i][j] == 1 and ((i, j) not in visited):
island += 1
area = bfs(i, j)
ans = max(ans, area)
# print(f"island: {island}")
return ans
|
b294461587d6e6ffcf322eed0961db010a3aed42 | marcuspepperl/Project-Euler | /11-20/Eulerp20.py | 165 | 3.546875 | 4 | import math
product=1
for i in range(1,101):
product=product*i
product_string=str(product)
sum=0
for ch in product_string:
ch=int(ch)
sum+=ch
print(sum)
|
6b0f21c7fea82a3fa92b1d2649e09495d7f010b5 | Aasthaengg/IBMdataset | /Python_codes/p03042/s193902148.py | 335 | 3.765625 | 4 | def check_my(string):
if 1 <= int(string) <= 12:
return 'YorM'
else:
return 'Y'
s = input()
my_set = (check_my(s[0:2]), check_my(s[2:4]))
if my_set == ('YorM', 'YorM'):
print('AMBIGUOUS')
elif my_set == ('YorM', 'Y'):
print('MMYY')
elif my_set == ('Y', 'YorM'):
print('YYMM')
else:
print('NA')
|
8963f2f1fbe763a0267921cf6fa60be690918f0b | KochetovNicolai/Python_822 | /zemerov/life/field.py | 5,194 | 3.609375 | 4 | import pygame
import button
import colours
class Field:
"""Основной класс, который будет управлять игровым полем"""
height = 12
width = 12
margin = 2
menu_height = 30
FONT = 'arial'
FONT_SIZE = 40
def __init__(self, number=40):
self.number = number
self.score = 0 # Максимальное количество клеток за игру
# Заполняем игровое поле нулями
self.grid = [[0 for x in range(number)] for y in range(number)]
# Задаём квадратное поле
self.field_size = (
number * Field.height + (number + 1) * Field.margin,
number * Field.height + (number + 1) * Field.margin + Field.menu_height,
)
self.pure_height = number * Field.height + (number + 1) * Field.margin
self.pure_width = number * Field.height + (number + 1) * Field.margin
# Счётчик живых клеток
self.live_cells = 0
self.is_dead = False
self.previous = []
def draw(self, surface):
"""Отрисовывает на surface игровое поле на текущий момент"""
for row in range(self.number):
for column in range(self.number):
color = colours.WHITE
if self.grid[row][column] == 1:
color = colours.BLUE
pygame.draw.rect(surface,
color,
[(Field.margin + Field.width) * column + Field.margin,
(Field.margin + Field.height) * row + Field.margin,
Field.width,
Field.height])
def click(self, place):
"""Изменение состояния клетки пользователем"""
column = min(place[0] // (Field.width + Field.margin), self.number - 1)
row = min(place[1] // (Field.height + Field.margin), self.number - 1)
if self.grid[row][column] == 1:
self.grid[row][column] = 0
self.live_cells -= 1
else:
self.grid[row][column] = 1
self.live_cells += 1
def evolution_step(self):
"""Обновляет состояние живых и мертвых клеток"""
tmp = [[0 for x in range(self.number)] for y in range(self.number)]
tmp_num = 0
for i in range(self.number):
for j in range(self.number):
n_neigh = self.__count_neighbours__(i, j)
if self.grid[i][j] == 0 and n_neigh == 3:
tmp[i][j] = 1
tmp_num += 1
elif self.grid[i][j] == 1 and (n_neigh == 2 or n_neigh == 3):
tmp[i][j] = 1
tmp_num += 1
else:
tmp[i][j] = 0
if tmp_num == 0:
self.is_dead = True
else:
self.live_cells = tmp_num
self.score = max(self.score, tmp_num)
if len(self.previous) > 10:
self.previous.pop(0)
self.previous.append(self.grid) # Добавляем текующую конфигурацию в previous
if tmp in self.previous:
self.is_dead = True
self.grid = tmp
def __count_neighbours__(self, row, column):
"""Подсчёт количества соседей"""
ans = 0
# Обработать крайние клетки
for i in range(-1, 2):
for j in range(-1, 2):
if not (i == j == 0):
if row == 0 and i == -1:
continue
elif row == self.number - 1 and i == 1:
continue
elif column == 0 and j == -1:
continue
elif column == self.number - 1 and j == 1:
continue
ans += self.grid[row + i][column + j]
return ans
def refresh(self):
"""В случае restart происходит обновление игрового поля"""
self.grid = [[0 for x in range(self.number)] for y in range(self.number)]
self.score = 0
self.live_cells = 0
self.is_dead = False
def game_over(self, surface):
game_over_text = button.Button(
'GAME OVER',
Field.FONT,
Field.FONT_SIZE,
160,
150,
colours.WHITE,
colours.GAMEOVER
)
score_text = button.Button(
'MAX SCORE {}'.format(self.score),
Field.FONT,
Field.FONT_SIZE,
140,
190,
colours.WHITE,
colours.GAMEOVER
)
window = pygame.Surface((self.pure_width, self.pure_height))
window.set_alpha(2)
window.fill(colours.GAMEOVER)
surface.blit(window, (0, 0))
game_over_text.draw(surface, is_rect=False)
score_text.draw(surface, is_rect=False)
|
694623102003ebc3e2b467de71ac9d59903f54cd | mcdallas/Euler | /Python/e23.py | 1,316 | 4 | 4 | # e23.py
'''
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number.
For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28,
which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is less than n
and it is called abundant if this sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16,
the smallest number that can be written as the sum of two abundant numbers is 24.
By mathematical analysis, it can be shown that all integers greater than 28123
can be written as the sum of two abundant numbers. However, this upper limit cannot
be reduced any further by analysis even though it is known that the greatest number
that cannot be expressed as the sum of two abundant numbers is less than this limit.
Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
'''
from e21 import proper_factors
def abundants(n):
abundant = set()
for i in range(2, n+1):
if sum(proper_factors(i)) > i:
abundant.add(i)
return abundant
if __name__ == '__main__':
new = set()
s = abundants(28123)
for i in s:
for j in s:
new.add(i+j)
print(sum(set(range(28124)) - new))
|
b342f9447244a3f992dbb233ec9a225880c9e9d7 | codeAligned/CTCIv5.0 | /Arrays and Strings/Python Solutions/1_5.py | 490 | 3.625 | 4 | input = raw_input('Enter String: ')
count = 1
resultantStr = str()
finalStr = str()
length = len(input)
comparator = input[0]
lst = list()
for alphabet in input:
lst.append(alphabet)
for item in lst[1:length]:
if item == comparator:
count=count+1
else:
resultantStr = resultantStr + comparator + str(count)
comparator=item
count=1
finalStr = resultantStr+comparator+str(count)
if len(finalStr) >= length:
print input
else:
print finalStr
|
8a4492faa45996fc38c7302415441b495d2929b3 | flynnthomas1227/projects | /Birthday_problem_scaled_program.py | 12,591 | 3.96875 | 4 | #This program answers the following questions
#by using the functions class_simulator, school_simulator, and district simulator
#to calculated to derised probabilities.
#I. Consider a class with p students. What is the probability that at least k of them share a birthday?
#(Example: In a class with 10 people, what is the probability that at least 2
#of them share a birthday (here, p = 10 and n = 2).)
#II. Consider a school with c classes, each with p students. What is the probability
#that in at least l of those classes, at least k of the students share a birthday?
#(Example: In a school with 100 classes of 10 students each, what is the probability
#that there are at least 5 classes in which at least 2 of the students share a birthday
#(here, c = 100, p = 10, l = 5, and n = 2).)
#III. Consider a school district with s schools, each with c classes that each have p students.
#What is the probability that in at least m of those schools, there are at least l classes in which
#at least k of the students share a birthday? (Example: In a school district with 500 schools,
#each with 100 classes of 10 students each, what is the probability that there are at least
#50 schools that have 5 classes in which at least 2 of the students share a birthday
#(here, s = 500, c = 100, p = 10, m = 50, l = 5, and n = 2).)
#Written by Thomas Flynn
#leap year is 97 out of 400 years
#This function is a random birthday generator that outputs the number of day
#the birthday is with feb. 29, the leap year day being 366.
def generate_birthday():
from random import randint
x = (randint(1,400))
if x > 97:
return(randint(1,365))
else:
return(randint(1,366))
#This function generates a class(list) of num_students which are randomly generated birthday values.
def generate_class(num_students):
return([generate_birthday() for student in range(num_students)])
#This function takes a class(class_roster) generated by generate_class and a number of
#desired birthday matches to check(num_matches) and checks to see how many birthdays in the class are the same
#it then compares the birthday matches with the desired bithday matches to check and if the actual
#matches is gretaer than or equal to the desired birthday matches it returns True, else it returns False
def class_checker(class_roster,num_matches):
#class_roster.count(birthday) for birthday = 1,2,3,4,5,... 366
actual_matches = max(([class_roster.count(birthday) for birthday in class_roster]))
if actual_matches >= num_matches:
return(True)
else:
return(False)
#This function does the class_checker function on 1000 randomly generated classes and divides
#the number of Trues by the number of trials to give the probability that
#there will be num_matches in a class of num_students
def class_simulator(num_students,num_matches):
num_trials = 1000
valid_matches = 0
for test in range(num_trials):
my_class = generate_class(num_students)
my_match = class_checker(my_class,num_matches)
if my_match is True:
valid_matches += 1
probability = valid_matches/num_trials
print('The probability of {} birthday matches in a class of {} \
students is approximately {:.4f}.'.format(num_matches,num_students,probability))
#This function generates a school of randomly generated classes
def generate_school(num_classes,num_students_per_class):
return([generate_class(num_students_per_class) for my_class in range(num_classes)])
#This function checks to see if the school of num_classes has num_class_matches with num_student_matches
def school_checker(school_classes,num_class_matches,num_student_matches):
student_matches=[class_checker(my_class,num_student_matches) for my_class in school_classes]
if sum(student_matches) >= num_class_matches:
return(True)
else:
return(False)
#This function generates 1000 schools and divides the amount of schools that have num_class_matches by the 1000 trials
#to get the probability that a school of num_classes with num_students will have num_class_matches with num_student_matches.
def school_simulator(num_classes,num_students_per_class,num_class_matches,num_student_matches):
num_trials = 1000
valid_class_matches = 0
for test in range(num_trials):
my_school = generate_school(num_classes,num_students_per_class)
my_class_matches = school_checker(generate_school(num_classes,num_students_per_class),num_class_matches,num_student_matches)
if my_class_matches is True:
valid_class_matches += 1
school_probability = valid_class_matches/num_trials
print('The probability of {} class matches with {} birthday matches in {} classes of {} \
students is approximately {:.4f}.'.format(num_class_matches,num_student_matches,num_classes,num_students_per_class,school_probability))
#This function generates a district with num_schools with num_classes with num_students
def generate_district(num_schools,num_classes,num_students_per_class):
return([generate_school(num_classes,num_students_per_class) for my_school in range(num_schools)])
#This function checks the district to see if it has num_school_matches with num_class_matches with num_student_matches
def district_checker(district_schools,num_school_matches,num_class_matches,num_student_matches):
district_match = [school_checker(my_school,num_class_matches,num_student_matches)for my_school in district_schools]
if sum(district_match) >= num_school_matches:
return(True)
else:
return(False)
#This function gives you the probability that a generated district will have
#num_school_matches with num_class_matches with num_student_matches
def district_simulator(num_schools,num_classes,num_students_per_class,num_school_matches,num_class_matches,num_student_matches):
num_trials = 1000
valid_school_matches = 0
for test in range(num_trials):
my_district = generate_district(num_schools,num_classes,num_students_per_class)
my_school_matches = district_checker(generate_district(num_schools,num_classes,num_students_per_class),num_school_matches,num_class_matches,num_student_matches)
if my_school_matches is True:
valid_school_matches += 1
district_probability = valid_school_matches/num_trials
print('The probability of {} school matches with {} class matches with {} birthday matches in a district of {} schools of {} classes of {} \
students is approximately {:.4f}.'.format(num_school_matches,num_class_matches,num_student_matches,num_schools,num_classes,num_students_per_class,district_probability))
#the next two functions can be used to answer the question "IV. Suppose you are made the following offer. If you teach a class at a school,
#you will be given $1000 for each student in the class. However, if at least 3 students in the class share a birthday,
#you get no money for the class. You get to choose how many students are in the class. How many students should you put
#in the class?" by calculating the expected values at certain class sizes and choosing the highest one.
def expected_value_class(num_students,num_matches):
num_trials = 1000
valid_matches = 0
for test in range(num_trials):
my_class = generate_class(num_students)
my_match = class_checker(my_class,num_matches)
if my_match is True:
valid_matches += 1
probability = valid_matches/num_trials
expected_value = (1-probability)*(num_students*1000)
return(expected_value)
#the next two functions can be used to answer the question "V. Suppose you are made the following offer.
#If you run a school filled with classes of 25 students each, you will be given $500 for each class that your
#school offers. However, if there are at least 5 classes in which at least 3 students share a birthday, you get
#no money for running the school. You get to choose how many classes are offered at the school. How many classes
#should you offer at the school?" by calculating the expected values at certain school sizes and choosing the highest one.
def highest_expected_value_class(num_students,num_matches):
my_expected_values = [expected_value_class(item,num_matches) for item in range(65,80)]
print(my_expected_values)
def expected_value_school(num_classes,num_students_per_class,num_class_matches,num_student_matches):
num_trials = 1000
valid_class_matches = 0
for test in range(num_trials):
my_school = generate_school(num_classes,num_students_per_class)
my_class_matches = school_checker(generate_school(num_classes,num_students_per_class),num_class_matches,num_student_matches)
if my_class_matches is True:
valid_class_matches += 1
school_probability = valid_class_matches/num_trials
expected_value = (1-school_probability)*(num_classes*500)
return(expected_value)
#the next two functions can be used to answer the question "VI. Suppose you are made the following offer.
#If you run a district filled with schools of 100 classes of 25 students each, you will be given $5000 for each school
#in your district. However, if there are at least 3 schools in which there are at least 5 classes in which
#at least 3 students share a birthday, you get no money for running the district.
#You get to choose how many schools are in the district. How many schools should you put in your district?"
#by calculating the expected values at certain district sizes and choosing the highest one.
def highest_expected_value_school(num_classes,num_students,num_class_matches,num_student_matches):
my_expected_values = [expected_value_school(item,num_students,num_class_matches,num_student_matches) for item in range(240,244)]
print(my_expected_values)
def expected_value_district(num_schools,num_classes,num_students_per_class,num_school_matches,num_class_matches,num_student_matches):
num_trials = 1000
valid_school_matches = 0
for test in range(num_trials):
my_district = generate_district(num_schools,num_classes,num_students_per_class)
my_school_matches = district_checker(generate_district(num_schools,num_classes,num_students_per_class),num_school_matches,num_class_matches,num_student_matches)
if my_school_matches is True:
valid_school_matches += 1
district_probability = valid_school_matches/num_trials
expected_value = (1-district_probability)*(num_schools*5000)
def highest_expected_value_district(num_schools,num_classes,num_students_per_class,num_school_matches,num_class_matches,num_student_matches):
my_expected_values = [expected_value_district(item,num_classes,num_students_per_class,num_school_matches,num_class_matches,num_student_matches) for item in range(10,11)]
print(my_expected_values)
#IV. The solution I would choose to question IV is 70 students. The reason I would choose 70 students is that choosing 70 students would give you the highest
#expected value. In other words it will most likely give me the greatest amount of money. The way I calculated this is by calculating the probability
# of there being 3 shared birthdays in classes ranging from 1-100 students. I then multiplied the amount of money I would get(num_students*1000) by
#the probability of there not being 3 shared birthdays(1-probability of there being 3 shared birthdays) to get the expected values. I did this 10
#times and found the class size with the highest expected value each time, then added them together and divided by ten to get an average which is the class size
#that would result in the highest expected value which was 70 students.
#V. I would choose 230 classes for this question because I made another program for the amount of classes in a school rather than students in a class and it did the same process to come up with 230 classes.
#VI. I would choose 70 schools.I chose this answer because I made a program similar to the previous 2 programs except for
#the amount of schools rather than classes or students. This program took a long time to run because of
#machine limitations so I observed the sweet spot probabilities that gave the highest expected value with
#the last two questions and they both came out to about .3. So I tried what amount of schools would give a probability
#of .3 by using a proportion from one of my trials with less schools and I got about 70 schools. This combined with
#the program that calculates expected value gave me the most confident answer I could come up with whic was 70 schools.
|
bdccf6ab0d9bb1037a5837de96498225345b39b6 | gourisnair/Python-Basics | /Strings.py | 1,733 | 4.28125 | 4 | a = 'Hello, World!'
#string is also an array
print(a[0])
#use ''' or """ to indicate multiline strings
b = '''India is my country. All Indians are my Brothers and Sisters
I love my country and I am proud of its rich and varied heritage.
I shall always strive to be worthy of it.
I shall give my parents, teachers and all elders respect and treat everyone with courtesy.
To my country and my people, I pledge my devotion.
In their well being and prosperity alone, lies my happiness. Jai Hind!'''
print(b)
#Slicing of strings
print(a[7:12]) #prints from 8 to 12 inclusive
#Negative indexing: to start slicing from the end
print(a[-12:-7])
#String length
print(len(a))
#String methods
#strip(): removes white spaces from beginning or end
print(a.strip())
#lower(): returns string in lower case
print(a.lower())
#upper(): returns string in upper case
print(a.upper())
#replace(): replaces a string with another strings
print(a.replace("Hello", "Fellow"))
#split(): splits the string into substrings where it finds the instances of the seperator
print(a.split(","))
#to check if a substring present or not
txt = "An apple a day keeps the doctor away"
x = 'apple' in txt
print(x)
y = 'apple' not in txt
print(y)
print('apple' in txt)
#String concatenation
a = 'Happy'
b = ' coding!'
print(a+b)
#String format
#format(): formats the argument and places them where the placeholders{} are
age = 20
msg = 'My name is Google and I am {} years old'
print(msg.format(age))
#format() takes unlimited number of arguments
a = 1
b = 2
c = 3
txt = 'I am {}, she is {} and he is {}'
print(txt.format(a, b, c))
#use index numbers for proper placing of the arguments
txt = 'I am {2}, she is {0} and he is {1}'
print(txt.format(a, b, c))
|
1df7d8de0ea47c52a303a26d35c8050b8f1ecb86 | mwhit74/practice_examples | /scientific_python/ch_1/ball_output1.py | 248 | 4.03125 | 4 | # Program for computing the height of a ball in vertical motion
v0 = 5 # initial velocity
g = 9.81 # acceleration of gravity
t = 0.6 # time
y = v0*t - 0.5*g*t**2 # vertical position
print 'At t=g% s, the height of the ball is %.2f .' % (t,y)
|
d616dcea5807b8d029d544b9ff28edfd8cd7351b | TigerYassin/Machine_Learning | /Network_in_tf.py | 5,648 | 3.671875 | 4 | import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
#import MNIST dataset from TF
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/dataset", one_hot=True) #loads the dataset each time it runs
#Load train data
x_train = mnist.train.images
y_train = mnist.train.labels
#Load test data
x_test = mnist.test.images
y_test = mnist.test.labels
x_train = x_train[:50000]
y_train = y_train[:50000]
#pring out the training data
print(x_train.shape)
print(y_train.shape)
#print out the testing data
print(x_test.shape)
print(y_test.shape)
def show_digit(index):
label = y_train[index].argmax(axis=0) #the argmax gets the one_hot array and return the index where the 1 exists
#get the 1D 784 array and reshape it into a 2D 28x28 array
Reshaped_2D_array = x_train[index].reshape([28,28])
# print(Reshaped_2D_array) This will print out the 28x28 array
fig, axes = plt.subplots(1)
fig.subplots_adjust(hspace=0.5, wspace=0.5)
plt.title("Training data, index: {}, Label: {}".format(index,label))
plt.imshow(Reshaped_2D_array, cmap='Greens')
plt.show()
def show_predicted_digit(image, pred, label):
image = image.reshape([28, 28])
plt.title("Original Image, Pred: {}, True label:{}".format(pred, label))
plt.imshow(image)
plt.show()
# show_digit(1)
# show_digit(2)
# show_digit(3)
#
#
# show_predicted_digit(x_train[1], 3,3)
batch_x, batch_y = mnist.train.next_batch(64)
print(batch_x.shape)
learning_rate = 0.001
training_epochs = 4
batch_size = 100
display_step = 1
model_path = "./talk_save/model1.ckpt"
alt_model_path = ".talk_save/model.ckpt"
n_input = 784 #MNIST data input(img shape: 28x28, flattened to be 784
n_hidden_1 = 384 #first layer number of nuerons
n_hidden_2 = 100 #2nd layer number of neurons
n_classes = 10 #MNIST classes for prediction(digits 0-9)
#the graph
tf.reset_default_graph()
with tf.name_scope("Inputs") as scope:
x = tf.placeholder("float", [None, n_input], name='x_input')
y = tf.placeholder("float", [None, n_classes], name='labels')
def multilayer_perceptron(x): #pass in the training set into x
with tf.name_scope('hidden_01') as scope:
#hidden layer 01 with RELU activation
#weights and bias tensor
h1weight = tf.Variable(tf.truncated_normal([n_input, n_hidden_1], stddev=0.1), name='h1_weights')
h1bias = tf.Variable(tf.truncated_normal([n_hidden_1], stddev=0.1), name='b1_bias')
#hidden layer 01 Operations
layer_1 = tf.add(tf.matmul(x, h1weight), h1bias, name='Layer1_matmul') # (x* h1weight) + h1bias:: y = Wx +b
layer_1 = tf.nn.relu(layer_1, name='Layer1_Relu') #activation Relu passes anything above 0 and blocks negatives
#tensorboard histograms for layer 01
tf.summary.histogram('weights_h1', h1weight)
tf.summary.histogram('bias_h1', h1bias)
with tf.name_scope('hidden_02') as scope:
#hidden layer 02 with RELU activation
h2weights = tf.Variable(tf.truncated_normal([n_hidden_1, n_hidden_2], stddev=0.1), name='h2_weights')
h2bias = tf.Variable(tf.truncated_normal([n_hidden_2], stddev=0.1), name='b2_bias')
layer_2 = tf.add(tf.matmul(layer_1, h2weights), h2bias, name='Layer2_add') #multiplies the layer and h2weights and adds h2bias:: y = Wx + b
layer_2 = tf.nn.relu(layer_2, name='Layer2_Relu')
#tensorboard histograms for layer 02
tf.summary.histogram('weights_h2', h2weights)
tf.summary.histogram('bias_h2', h2bias)
with tf.name_scope('output_layer') as scope:
#Logits layer with linear activation
output_weights = tf.Variable(tf.truncated_normal([n_hidden_2, n_classes], stddev=0.1), name='output_weights')
output_bias = tf.Variable(tf.truncated_normal([n_classes], stddev=0.1), name='out_bias')
logits_layer = tf.add(tf.matmul(layer_2, output_weights), output_bias, name='logits') #here we create the equation y =Wx +b
return logits_layer
pred = multilayer_perceptron(x) #we pass it the x placeholder created before the method above
#Create the loss
with tf.name_scope('cross_entropy'):
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=pred))
#create the optimizer
with tf.name_scope('train'):
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss) #optimizer makes changes to the weights and the biases
#optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(loss) #uses the gradient descent
with tf.name_scope('accuracy'):
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#initialize the variables
init = tf.global_variables_initializer()
#create a saver to save and restore all the variables
saver = tf.train.Saver()
#run the graph on tensorboard
#file_writer = tf.summary.FileWriter('log_simple_graph/8', sess.graph)
"""
todo must revisit tensor board graph
"""
#Launch the graph and train the network by running the session
with tf.Session() as sess:
sess.run(init)
#training cycle
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
#Loop over all batches
for i in range(total_batch):
batch_x, batch_y = mnist.train.next_batch(batch_size)
#run optimization op (backprop) and cost op (to get loss value)
_, c,summary = sess.run([optimizer, loss, summary_op], )
|
2bb5d71e2c9cbbefd69a6800ffb2844d9d85bc6b | karolp6/pytest-vistula | /python_basics/data_types.py | 487 | 3.859375 | 4 | a_int = 1 # integers
a_float = 1.0 # float
a_string = "cat" # string
a_boolean = True # boolean
a_list = [1, "cat", [1, 2, 3], "dog"] # list
a_dict = {
"cat": "meow",
"dog": "woof woof"
}
a_tuple = (1, 2, "cat")
# a_tuple[0] = 3 # not support item assignment
# print(a_tuple[0])
# print(a_dict["cat"]) # reading value for key
# print(a_list[4]) # out of range
# print(a_list[-1]) # last element
# print(a_string[1]) # 2nd value
# print(1/2) # 0.5
# print(1 //2) # 0
|
6c2155563671218fef49af201a6328d6b6bb5f7c | Aasthaengg/IBMdataset | /Python_codes/p02548/s501222809.py | 157 | 3.828125 | 4 | def func(N):
result = 0
for A in range(1,N):
result += (N-1)//A
return result
if __name__ == "__main__":
N = int(input())
print(func(N)) |
3e6bad80f216e9a46f40d301b7cd3771e6eda793 | franklingu/leetcode-solutions | /questions/candy/Solution.py | 1,403 | 3.921875 | 4 | '''
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
Example 1:
Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.
Example 2:
Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
The third child gets 1 candy because it satisfies the above two conditions.
'''
'''
Initialize all candies to be 1.
Run from left to right, if current is bigger than previous, set
current's candy to be bigger than previous.
And run from right to left, if current is biggern than previous,
set current's candy to be max of previous can + 1 and current candy.
Essentially greedy.
'''
class Solution:
def candy(self, ratings: List[int]) -> int:
nums = [1] * len(ratings)
for i in range(1, len(ratings)):
if ratings[i - 1] < ratings[i]:
nums[i] = nums[i - 1] + 1
for i in range(len(ratings) - 1, 0, -1):
if ratings[i - 1] > ratings[i]:
nums[i - 1] = max(nums[i] + 1, nums[i - 1])
return sum(nums)
|
bd69ce82eded280eb0f6ce2134e3bcebb7f894e7 | slahser0713/Coding-for-Interviews | /剑指offer/032-把数组排成最小的数/剑指032-把数组排成最小的数.py | 716 | 3.75 | 4 | class Solution:
# 两个数排列,a1+ a2更小就将a1放在a2前面
# 利用冒泡排序,将排列起来最小的a1冒到最前面
def PrintMinNumber(self, numbers):
if not numbers:
return ""
def compare(a1,a2): # 比较函数
if a1+ a2 < a2 + a1:
return 1
else:
return 0
for j in range(len(numbers)-1): # 冒泡函数
for i in range(len(numbers)-1,j,-1):
if compare(str(numbers[i]),str(numbers[i-1])):
numbers[i-1],numbers[i] = numbers[i],numbers[i-1]
return "".join([str(x) for x in numbers])
a = Solution()
print(a.PrintMinNumber([3,5,1,4,2])) |
85693e83b92f0892f9f92262cfff835c0ac8dce1 | BeefAlmighty/CrackingCode | /LinkedLists/LinkedList.py | 1,969 | 4.15625 | 4 | # Implementation of linked list data structure
class LinkedList:
def __init__(self, node=None):
self.head = node
def __repr__(self):
temp = self.head
ans = temp.__repr__()
while temp.next:
temp = temp.next
ans += " --> " + temp.__repr__()
ans += " --> [ X ]"
return ans
def __eq__(self, other):
temp = self.head
temp_2 = other.head
while temp and temp_2:
if temp != temp_2:
return False
temp = temp.next
temp_2 = temp_2.next
if temp is None and temp_2 is not None:
return False
elif temp is not None and temp_2 is None:
return False
else:
return True
def make_from_list(self, ls):
"""
Helper for doing testing, makes a singly linked list object from
a List object
:param ls: List
:return: self
"""
self.head = Node(ls[0])
temp = self.head
idx = 1
while idx < len(ls):
temp.next = Node(ls[idx])
idx += 1
temp = temp.next
return
def __len__(self):
temp = self.head
ans = 0
while temp:
ans += 1
temp = temp.next
return ans
class Node:
def __init__(self, item, next=None, prev=None):
self.item = item
self.next = next
self.prev = prev
def __repr__(self):
return f"[ {self.item} ]"
def __eq__(self, other):
return self.item == other.item and self.next == other.next
def main():
node = Node(3.14)
print(node)
node = Node(2.718, node)
head = Node(1.615, node)
linked_list = LinkedList(head)
print(linked_list)
linked_list = LinkedList()
linked_list.make_from_list([1, 2, 3])
print(linked_list)
print(len(linked_list))
if __name__ == "__main__":
main() |
16b7a6452c1c6b95be6eb3db899739f2f47cea7a | fabiosabariego/curso-python | /pacote-download/Python/modulo01/python01ex/ex082.py | 774 | 3.90625 | 4 | """
Crie um programa que vá ler vários numeros e colocar em uma lista. Depois disso, crie duas listas extras que vão
conter apenas os valores pares e os valores impares digitados, respectivamente. No final mostre o conteudo das
3 listas geradas
"""
num = []
par = []
imp = []
cnt = ''
inc = 0
while True:
if cnt != 'N':
num.append(int(input('Digite um Valor: ')))
cnt = str(input('Deseja Continuar? [S/N]: ')).strip().upper()
if num[inc] % 2 == 0:
par.append(num[inc])
if num[inc] % 2 != 0:
imp.append(num[inc])
inc += 1
else:
break
print('=' * 40)
print(f'Lista Criada com valores digitados: {num}')
print(f'Lista Com os valores Pares: {par}')
print(f'Lista Com os valores Impares: {imp}') |
47b4a6d97eee9f4f10146ce487c084f7b006f1af | jh-lau/leetcode_in_python | /02-算法思想/设计/155.最小栈.py | 1,114 | 3.828125 | 4 | """
@Author : liujianhan
@Date : 2020/3/25 上午11:35
@Project : leetcode_in_python
@FileName : 155.最小栈.py
@Description : 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) -- 将元素 x 推入栈中。
pop() -- 删除栈顶的元素。
top() -- 获取栈顶元素。
getMin() -- 检索栈中的最小元素。
"""
# 80ms, 16.5MB
class MinStack:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, x: int) -> None:
self.stack.append(x)
if not self.min_stack or x <= self.min_stack[-1]:
self.min_stack.append(x)
def pop(self) -> None:
if self.stack.pop() == self.min_stack[-1]:
self.min_stack.pop()
def top(self) -> int:
return self.stack[-1]
def get_min(self) -> int:
return self.min_stack[-1]
if __name__ == '__main__':
ms = MinStack()
ms.push(-2)
ms.push(0)
ms.push(-3)
print(ms.get_min())
ms.pop()
print(ms.top())
print(ms.get_min())
|
e6f3754f27abea896ed39d360bb7f0ba0d06fe33 | KevinArellanoMtz/AprendiendoPyhton | /Guiadepython(programas)/tempCodeRunnerFile.py | 741 | 4.125 | 4 | #Kevin Luis Arel
#Matricula 1878209
#haremos un programa que compruebe que un numero
#sea multiplo de 3,5 y 7
#primero pediremos en numero a evaluar
numeroaevaluar=int(input("Dame un numero que sea multiplo de 3,5 o 7 : "))
#aqui se declara cuales son los multiplos de 3,5 y 7
multiplode3=((numeroaevaluar%3)==0)
multiplode5=((numeroaevaluar%5)==0)
multiplode7=((numeroaevaluar%7)==0)
#se usara un if es decir un si esta es un condicionador aqui usaremos and y or
#el and es una condicion (y) que compara dos cosas y estas dos tienen que ser verdaderas
#el or (o) se cumple si una de esas es verdadera
if ((multiplode3 and multiplode5) or multiplode7):
print("Tu numero es correcto")
else:
print("Tu numero no es correcto") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.