blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
d8968493d4b89f821c9979e7ed9eefff3e3f76b5 | Jerrydperry/cs114 | /magic8ballv3.py | 766 | 4.15625 | 4 | print ("what is your name?")
name = input()
print ("welcome " + str(name) + " I hope you're ready for your fate.")
import random
r = random.randint(1,3)
def getAnswer(r):
# if r == 1:
# fortune ='your fate is looking grim.'
# elif r == 2:
# fortune = 'your fate will be of nuetral concern.'
# elif r == 3:
# fortune = 'your fate is looking most beneficial'
fortune = [
'your fate is looking grim' ,
'your fate will be of nuetral concern' ,
'your fate is looking most beneficial']
if r == 1:
answer = fortune[1]
elif r == 2:
answer = fortune[2]
elif r == 3:
amswer = fortune[3]
return answer
def main():
answer = getAnswer(r)
return print(answer)
main()
|
1472a1673eded1685a80a9fb87eba58e947fe04d | xpls7/softuni-python-fundamentals | /Exercise_4_Functions/ex.3.py | 171 | 3.78125 | 4 |
def all_symbol(ch_1, ch_2):
for i in range((ord(char_1))+1, ord(ch_2)):
print(chr(i), end=" ")
char_1 = input()
char_2 = input()
all_symbol(char_1, char_2)
|
f62ba1358cd8d88a67950709c9d24dbfe5388d1b | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/srepking/lesson07/part1/L7_populate_personjob.py | 5,987 | 3.5 | 4 | """
Loads the database that includes Department for assignment 7. You need
to delete the database personjob.db before you run this.
"""
import logging
import sqlite3
from L7_create_personjob import *
from peewee import *
import pprint
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
from datetime import datetime
def populate_people():
"""
add person data to database
"""
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)
logger.info('Starting to load people')
PERSON_NAME = 0
LIVES_IN_TOWN = 1
NICKNAME = 2
people = [
('Andrew', 'Sumner', 'Andy'),
('Peter', 'Seattle', None),
('Susan', 'Boston', 'Beannie'),
('Pam', 'Coventry', 'PJ'),
('Steven', 'Colchester', None)
]
try:
for person in people:
with database.transaction():
new_person = Person.create(
person_name=person[PERSON_NAME],
lives_in_town=person[LIVES_IN_TOWN],
nickname=person[NICKNAME])
new_person.save()
logger.debug('People data add successful')
logger.debug('Print the Person records we saved...')
except Exception as e:
logger.info(f'Error creating = {person[PERSON_NAME]}')
logger.info(e)
finally:
logger.info('finished loading people')
def populate_departments():
"""
Add department data to database with columns Department Number,
Department Name, Department Manager, Job Name, and Total Days
position was held.
"""
DEPT_number = 0
DEPT_name = 1
DEPT_manager = 2
logger.info('Starting to load deparatment data.')
department_data = [
('C191', 'Operations', 'Dick'),
('C291', 'Transmission', 'Mary'),
('C391', 'Generation', 'Pat'),
('C491', 'HumanResources', 'Rob'),
('C591', 'Distribution', 'Cindy')
]
try:
for departs in department_data:
with database.transaction():
new_dept = Department.create(
dept_number=departs[DEPT_number],
dept_name=departs[DEPT_name],
dept_manager=departs[DEPT_manager]
)
new_dept.save()
finally:
logger.info('finished loading department data.')
def populate_jobs():
"""
Add jobs data to database.
"""
JOB_NAME = 0
START_DATE = 1
END_DATE = 2
SALARY = 3
PERSON_EMPLOYED = 4
DEPT_NUMBER = 5
logger.info('Starting to load jobs')
jobs = [
('Analyst', '2001-09-22', '2003-01-30', 65500, 'Andrew', 'C191'),
('Senior analyst', '2003-02-01', '2006-10-22', 70000, 'Andrew', 'C191'),
('Senior business analyst', '2006-10-23', '2016-12-24', 80000,
'Andrew', 'C191'),
('Admin supervisor', '2012-10-01', '2014-11-10', 45900, 'Peter', 'C291'),
('CEO', '2014-11-14', '2018-01-05', 45900, 'Peter', 'C291')
]
try:
for job in jobs:
with database.transaction():
new_job = Job.create(
job_name=job[JOB_NAME],
start_date=job[START_DATE],
end_date=job[END_DATE],
salary=job[SALARY],
days_held = None,
person_employed=job[PERSON_EMPLOYED],
dept_num=job[DEPT_NUMBER])
new_job.save()
# Calculate days help in a position from the data in the tables
for job in Job:
with database.transaction():
date_format = "%Y-%m-%d"
# Get start_date and end_date from Job Table and parse
# date string into python format
startday = datetime.strptime(job.start_date, date_format)
endday = datetime.strptime(job.end_date, date_format)
totaldays = (endday - startday).days # returning the days only
job.days_held = totaldays
job.save()
# Print how long each person worked in their job.
for job in Job:
logger.info(f'{job.person_employed} worked as '
f'{job.job_name} for {job.days_held} days.')
finally:
logger.info('finished loading jobs')
def join_classes():
"""
Create a list of every department each person worked for.
Joins the Person table to Job table, and then those results get joined
to the Department table.
"""
try:
database.connect()
database.execute_sql('PRAGMA foreign_keys = ON;')
query = (Person
.select(Person.person_name, Job.job_name, Department.dept_name.alias("dept_name"))
.join(Job, JOIN.INNER).objects()
.join(Department, JOIN.INNER).objects()) # Joins Job -> Department
query_tuple = [] # Create a list to hold person, job, and dept.
for job in query:
query_tuple.append((job.person_name, job.job_name,
job.dept_name))
return query_tuple
except Exception as e:
logger.info(f'Error creating query')
logger.info(e)
finally:
logger.info('database closes after join_classes')
database.close()
if __name__ == '__main__':
logger.info('Creating the Database.')
database = SqliteDatabase('personjob.db')
database.create_tables([
Job,
Person,
PersonNumKey,
Department
])
database.connect()
logger.info('database connects')
database.execute_sql('PRAGMA foreign_keys = ON;')
populate_people()
populate_departments()
populate_jobs()
database.close()
logger.info('Call join_classes and print the person, '
'their job, and the department they were in.')
pprint.pprint(join_classes())
|
f32040cf8be0569800906ba537a6da197f200a43 | kiranKrishna0801/Coursera_IIPP | /week0/week0b/week0b_practice_exercise_6.py | 155 | 4.09375 | 4 | PI = 3.14
radius = 8
area=PI*radius**2
print "A circle with a radius of " + str(radius),
print "inches has an area of " + str(area) + " square inches." |
34bd52c9dd72807cef5dce83c0850c70e0ced478 | evianyuji/the-self-taught-programmer | /3章/3-2.py | 88 | 3.625 | 4 | x = 9
if x < 10:
print("xは10未満です")
else:
print("xは10以上です")
|
cd7b77c065c0fdbd02e29199fdc6bc8b058d8637 | freonzx/cs50stuff | /pset6/credit/credit.py | 1,157 | 4.09375 | 4 | # Function that checks the card
def check_card(number):
# Holds the sum of numbers
soma = 0
# Holds the number of digits
count = len(number)
# Reverse the number so we can work with it
number = number[::-1]
# iterates through number string converting digit to integer and working with it
for index, digit in enumerate(number):
digit = int(digit)
if ((index + 1) % 2 == 0):
digit *= 2
if digit > 9:
digit -= 9
soma += digit
if soma % 10 == 0:
return 1
else:
return 0
# Main
def main():
number = input('Number: ')
length = len(number)
# Gets 2 first digits and converts to int
company = int(number[0:2:])
if (check_card(number) == 1 and length > 13):
if (company > 50 and company < 56 and length == 16):
print('MASTERCARD')
elif (company == 34 or company == 37 and length == 15):
print('AMEX')
elif (company / 10 == 4 and length == 13 or length == 16 or length == 19):
print('VISA')
else:
print('INVALID')
if __name__ == "__main__":
main() |
c6da7f030d95854ea6c0d4d76ad5f2e0e4a11b58 | gabriellaec/desoft-analise-exercicios | /backup/user_265/ch37_2020_09_16_20_53_13_466941.py | 202 | 3.84375 | 4 | senha = True
while senha:
a = str(input('Palavra '))
if a != 'desisto':
a = str(input('Palavra '))
else:
senha = False
print('Você acertou a senha!')
|
703b4307b4c717a34fe8a2681f5d73444f3d9036 | diaosj/python-data-structure | /english_ruler.py | 1,439 | 4.5625 | 5 | """
Consider how to draw the markings of a typical English ruler.
For each inch, we place a tick with a numeric label. Denote the length of the tick designating a whole inch as the
major tick length. Between the marks for whole inches, the ruler contains a series of minor ticks, placed at intervals
of 1/2 inch, 1/4 inch, and so on. As the size of the interval decreases by half, the tick length decreases by one.
---- 0
-
--
-
---
-
--
-
---- 1
-
--
-
---
-
--
-
---- 2
A 2-inch ruler with major tick length 4.
In general, an interval with a central tick length L>=1 is composed of:
* An interval with a central tick length L-1
* A single tick of length L
* An interval with a central tick length L-1
"""
def draw_line(tick_length, tick_label=''):
"""Draw one line with given tick length (followed by optional label)."""
line = '-' * tick_length
if tick_label:
line += ' ' + tick_label
print line
def draw_interval(center_length):
"""Draw tick interval based upon a central tick length."""
if center_length > 0:
draw_interval(center_length - 1)
draw_line(center_length)
draw_interval(center_length - 1)
def draw_ruler(num_inches, major_length):
"""Draw English ruler with given number of inches, major tick length."""
draw_line(major_length, '0')
for j in range(1, 1 + num_inches):
draw_interval(major_length - 1)
draw_line(major_length, str(j))
|
13c396c8d436ebd601fc7b033a105a0960e11eda | LivHackSoc/Workshop | /python/intro.py | 628 | 4.0625 | 4 | print "This is Python programming!" + "\n"
# variable in python
greenApple = 2
redApple = 3 # data type: integer
totalApple = greenApple + redApple
# print information to console
print ('The total number of apples: ' + str(totalApple) + "\n")
# declare a function using the keyword 'def'
def totalApplePrice(totalGreenApple, totalRedApple):
greenUnitPrice = 0.15 # this data type is know as 'float'
redUnitPrice = 0.12
totalPrice = (totalGreenApple * greenUnitPrice) + (totalRedApple * redUnitPrice)
return ("The total price is: " + str(totalPrice) + "\n")
print totalApplePrice(greenApple, redApple)
|
a0c76170f7f6ecbef94d0493a403b99cc4932bd8 | samuel129/Old-programs-from-2020 | /real coin change finder.py | 658 | 3.953125 | 4 | # change calculator
money = float(input('How much money did you pay?: $'))
cost = float(input('How much money did it cost?: $'))
money = money*100
cost = cost*100
quarter = 25
dime = 10
nickel = 5
penny = 1
money2 = money - cost
quarter2 = money2 // 25
money3 = money2 % 25
dime2 = money3 // 10
money4 = money3 % 10
nickel2 = money4 // 5
money5 = money4 % 5
penny2 = money5 // 1
money6 = money5 % 1
if quarter2 >= .5:
print('Number of quarters: ', int(quarter2))
if dime2 >= .5:
print('Number of dimes: ', int(dime2))
if nickel2 >= .5:
print('Number of nickels: ', int(nickel2))
if penny2 >= .5:
print('Number of pennies: ', int(penny2))
|
fc19dac05d4e08d0c8d7a9f34b3f336f8a079c57 | JSBCCA/pythoncode | /early_projects/theater.py | 2,721 | 3.8125 | 4 | import myshop
def movie(name):
two = round((9.99 * 1.07), 2)
print("Here is your Ticket and movie receipt.\n[Ticket for", name,
" - $" + str(two) + "]\nEnjoy the film!")
def concession():
print(" Refreshments:\n"
"Popcorn - $5.05\n"
"Coke - $2.19\n"
"Cookies - $1.50\n"
"Alright, you want to buy-\n")
a = int(input("How many Popcorn buckets? ").strip())
b = int(input("How many Cokes? ").strip())
c = int(input("How many Cookies? ").strip())
myshop.myshop(a, b, c)
def theater():
name = input("Hello! What is your name?").strip().capitalize()
film = input("Thank you for coming, " + name + "! " + "Welcome to "
"the Malco Theater!\n"
"What film would you like to go see today?\n"
" Films:\n"
"The Avengers: 8:00\n"
"Frozen: 7:00\n"
"Star Wars: 7:30\n"
"Harry Potter: 5:00\n"
"Shrek: 4:30\n"
"\n"
" Tickets: $9.99").strip().lower()
if film == "the avengers":
would = input("Would you like to buy some concessions?").strip().lower(
)
if would == "yes":
concession()
movie(film.title())
else:
print("Just the movie then? Alright.")
movie(film.title())
elif film == "frozen":
would = input("Would you like to buy some concessions?").strip().lower(
)
if would == "yes":
concession()
movie(film.title())
else:
print("Just the movie then? Alright.")
movie(film.title())
elif film == "star wars":
would = input("Would you like to buy some concessions?").strip().lower(
)
if would == "yes":
concession()
movie(film.title())
else:
print("Just the movie then? Alright.")
movie(film.title())
elif film == "harry potter":
would = input("Would you like to buy some concessions?").strip().lower(
)
if would == "yes":
concession()
movie(film.title())
else:
print("Just the movie then? Alright.")
movie(film.title())
elif film == "shrek":
would = input("Would you like to buy some concessions?").strip().lower(
)
if would == "yes":
concession()
movie(film.title())
else:
print("Just the movie then? Alright.")
movie(film.title())
else:
print("Oh, did you change your mind...? Well then, have a nice day!")
theater()
|
e55e5e9953188bba3474f8e7d07f7c8edfc4066a | elsagrasia/UG10_D_71210761 | /1_D_71210761.py | 579 | 3.59375 | 4 | a = int(input("Harga makanan sebesar RP "))
b = int(input("Harga snack sebesar Rp "))
c = int(input("Harga minuman sebesar Rp "))
d = int(input("Uang yang anda bawa sebesar Rp "))
e = a+b+c
total = d-e
if d<e:
print("Total yang harus anda bayar sebesar Rp", e)
print("Uang anda kurang! Anda memiliki hutang sebesar Rp", total*-1)
elif d>e:
print("Total yang harus anda bayar sebesar Rp", e)
print("Anda memiliki kembalian sebesar Rp", total)
else:
print("Total yang harus anda bayar sebesar Rp", e)
print("Uang anda pas! Tidak ada kembalian dan Utang :D") |
29ef3b294a878de6ed699ed80a72750df64fbead | Sean1708/Regetron3.0 | /regetron/engine.py | 8,098 | 3.828125 | 4 | import re
import sys
import os
CMD_PATTERN = re.compile("^!([a-z]+)\s*(.*)$")
class ArtificialException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Regetron:
def __init__(self):
self.infile_name = None
self.infile = ""
self.match_mode = False
self.from_script = False
self.prompt = "> "
self.commands = {
"help": ("print a help message for the given command",
"""Usage: !help [cmd]
When called with no arguments this command prints a short description of
all available commands. If an argument is supplied a longer description of
just that command will be printed."""),
"data": ("load a string into memory to be searched",
"""Usage: !data "string"
This command loads the string enclosed in matching quotation marks into
memory to be searched by the entered regex. Seperate lines can be
delimited by the escape character '\\n'. Subsequent calls to this command
will overwrite the previous one."""),
"load": ("load a file into memory to be searched",
"""Usage: !load filename
Loads the specified file into memory so that it can be searched, seperate
lines in the file are loaded into memory as seperate line. Tilde expansion
is performed when loading the file."""),
"match": ("switch between match mode and search mode",
"""Usage: !match
Switches between search mode (default) and match mode. Match mode will
only match if the regex occurs at the beginning of the line whereas in
search mode the regex can match at any point in the line. In other words
match mode bahaves as if each regex pattern begins with the caret '^'
character."""),
"parse": ("read regex from a file",
"""Usage: !parse filename
Matches the regex in the specified file to the loaded text. The regex in
the file can be written verbosely. Tilde expansion is performed when
searching for the file."""),
"prompt": ("change the prompt",
"""Usage: !prompt [string]
Sets the prompt to the specified string (default is '> '). If no string is
given, no prompt is used."""),
"rep": ("mimic search and replace style regex",
"""Usage: !rep expression
Replaces matched regex with another string. The expression should be of the
form /exp/rep/ where / is any character. The first section exp is the regex
to match and the second section rep is the string to replace it with.""")
}
def load_input_file(self, infile_name):
# could this cause problems for windows users?
if infile_name[0:2] == '~/':
infile_name = os.path.join(
os.path.expanduser('~'), infile_name[2:]
)
self.infile_name = infile_name
if not os.path.exists(self.infile_name):
print("File {0} doesn't exist.".format(self.infile_name))
# allows cmdline.py to know if data couldn't be loaded
return False
else:
self.infile = open(self.infile_name).readlines()
print("File {0} has been loaded.".format(self.infile_name))
return True
def load_script(self, fname):
sys.stdin = open(fname)
self.from_script = True
def setup_readline(self):
try:
import readline
import atexit
histfile = os.path.join(os.path.expanduser("~"), ".regetronhist")
try:
readline.read_history_file(histfile)
except IOError:
pass
atexit.register(readline.write_history_file, histfile)
readline.parse_and_bind("TAB: complete")
except:
print("No readline support, so no scroll back for you.")
def run_input_loop(self):
regex = self.read_input()
while regex:
self.print_matches(regex)
regex = self.read_input()
def print_matches(self, regex):
if not self.infile:
print("Input file is empty. Use !load to load something.")
return
for i, line in enumerate(self.infile):
res = self.test_regex(regex, line)
if res:
if res.groups():
print("{0:04d}: {1!r}".format(i, regex.findall(line)))
else:
print("{0:04d}: {1!s}".format(i, line), end="")
def test_regex(self, regex, line):
if self.match_mode:
return regex.match(line)
else:
return regex.search(line)
def read_input(self):
while True:
try:
exp = self.read_line(self.prompt)
command = CMD_PATTERN.match(exp)
if exp == "":
return self.read_verbose()
elif command:
result = self.handle_command(*command.groups())
if result:
return result
else:
return re.compile(exp)
except EOFError:
print("" if self.from_script else "\nBYE")
return False
except Exception as e:
print("ERROR", e)
def read_line(self, prompt=""):
exp = input(prompt)
if self.from_script:
print(exp)
return exp
def read_verbose(self):
exp = []
l = self.read_line()
while l:
exp.append(l)
l = self.read_line()
return re.compile('\n'.join(exp), re.VERBOSE)
def handle_command(self, command, args):
if command == "data":
self.set_data(args)
elif command == "help":
self.print_help(args)
elif command == "load":
self.load_input_file(args)
elif command == "match":
self.match_mode = not self.match_mode
print("Match mode: {0}".format(
"match" if self.match_mode else "search"
))
elif command == "parse":
sample = open(args).read()
return re.compile(sample, re.X)
elif command == "prompt":
self.prompt = args
elif command == "rep":
self.replace_regex(args)
else:
raise ArtificialException(
"invalid command, see !help for valid commands"
)
def set_data(self, args):
self.infile_name = None
# remove accidental whitespace
args = args.strip()
args = self.check_and_remove_quotes(args)
data = str(args).split("\\n")
self.infile = [l + "\n" for l in data]
def check_and_remove_quotes(self, args):
if (args[0] == args[-1]) and (args[0] in ["'", '"']):
return args[1:-1]
else:
raise ArtificialException(
"Data must be enclosed in matching quotation marks."
)
def print_help(self, cmd):
if not cmd:
print("Available commands are:")
for k, v in self.commands.items():
print("\t{0:10} - {1}".format(k, v[0]))
else:
try:
print("{0}".format(self.commands[cmd][1]))
except KeyError:
raise ArtificialException(
"{0} is not a valid command".format(cmd)
)
def replace_regex(self, args):
bound_char = args[0]
pattern = args.split(bound_char)
if len(pattern) != 4:
print(
"ERROR format is: !reg /REGEX/REPLACE/ and / can be any char."
)
else:
reg, rep = pattern[1], pattern[2]
regex = re.compile(reg)
for i, line in enumerate(self.infile):
if self.test_regex(regex, line):
print(re.sub(regex, rep, line), end="")
|
6bf70383383d015f4876c1f7146fb68880270aed | pangyouzhen/data-structure | /other/162 findPeakElement.py | 583 | 3.546875 | 4 | from typing import List
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
if len(nums) == 1:
return 0
nums.append(float('-inf'))
for i in range(len(nums) + 1):
if nums[i + 1] - nums[i] < 0:
return i
if __name__ == '__main__':
sol = Solution()
nums = [1]
nums2 = [1, 2, 3, 1]
nums3 = [1, 2]
assert sol.findPeakElement(nums) == 0
assert sol.findPeakElement(nums2) == 2
assert sol.findPeakElement(nums3) == 1
print(sol.findPeakElement(nums3))
|
9e23381cb448a784a829905a5e2183d21ce4e28d | mcxu/code-sandbox | /PythonSandbox/src/misc/coin_change_min_num_of_coins.py | 2,990 | 3.765625 | 4 | """
Given array of pos ints representing denominations, and a single non-negative
int representing a target amount of money, implement function that returns
SMALLEST NUMBER OF COINS needed to make change for target amount.
Sample input: 7, [1,5,10]
Sample output: 3 (2x1 + 1x5)
"""
class Prob:
'''
Dynamic programming, iterative. Using minWays array to store solns to subproblems.
Let n=amount, d=len(denoms)
Time complexity: O(n*d).
Space complexity: O(n), since mnc stores <= n+1 solns to subproblems.
'''
@staticmethod
def minNumOfCoinsForChangeDP(n, denoms):
denoms = sorted(denoms)
# init array to store min number of ways
# Let mnc (min num coins) be an array to store solns to subproblems.)
mnc = [float("inf") for i in range(n+1)] # O(n) space
mnc[0] = 0 # if n=0, then there are 0 number of coins needed.
print("initial min in mnc: ", min(mnc))
for i in range(n+1): # O(n) time
print("i=", i)
for d in range(len(denoms)): # O(d) time
denom = denoms[d]
print(" d= {}, denom= {}".format(d,denom))
if i >= denom:
mnc[i] = min(mnc[i], mnc[i-denom] + 1)
print(" mnc: ", mnc)
else:
print(" denom > i. breaking")
break
print("mnc: ", mnc)
minWaysFinal = mnc[n]
if minWaysFinal == float("inf"):
return -1
return minWaysFinal
@staticmethod
def test1(alg):
n = 7
denoms = [1,5,10]
numCoins = alg(n, denoms)
print("test1 numCoins: ", numCoins)
@staticmethod
def test2(alg):
n = 0
denoms = [1,2,3]
numCoins = alg(n, denoms)
print("test2 numCoins: ", numCoins)
@staticmethod
def test3(alg):
# this sample input from: https://www.youtube.com/watch?v=HWW-jA6YjHk&t=528s
# correct ans is 4.
n = 31
denoms = [25,10,1]
numCoins = alg(n, denoms)
print("test3 numCoins: ", numCoins)
@staticmethod
def test4(alg):
# correct answer is 2
n = 135
denoms = [39, 45, 130, 40, 4, 1, 60, 75]
numCoins = alg(n, denoms)
print("test4: num coins: ", numCoins)
@staticmethod
def test5(alg):
n = 9
denoms = [3,5]
numCoins = alg(n, denoms)
print("test5: num coins: ", numCoins)
@staticmethod
def test6(alg):
n = 6249
denoms = [186,419,83,408]
numCoins = alg(n, denoms)
print("test6: num coins: ", numCoins)
@staticmethod
def test7(alg):
n = 10
denoms = [2,3,4]
numCoins = alg(n, denoms)
print("test6: num coins: ", numCoins)
alg = Prob.minNumOfCoinsForChangeDP
#Prob.test1(alg)
#Prob.test2(alg)
#Prob.test3(alg)
#Prob.test4(alg)
#Prob.test5(alg)
#Prob.test6(alg)
Prob.test7(alg) |
98f912cc42ac8fc7b579b256911cefec110de1e6 | vasjanovak/Vehicle-Manager | /vehicles.py | 4,188 | 4 | 4 | class Vehicle:
def __init__(self, make, model, mileage, service):
self.make = make
self.model = model
self.mileage = mileage
self.service = service
def list_of_vehicles(vehicles):
if not vehicles:
print('')
print("You don't have any vehicles on your list")
print('')
else:
for index, vehicle in enumerate(vehicles):
print('')
print('Id: {}'.format(index))
print('Make: {}'.format(vehicle.make))
print('Model: {}'.format(vehicle.model))
print('Mileage: {}'.format(vehicle.mileage))
print('Last service: {}'.format(vehicle.service))
print('')
def edit_mileage(vehicles):
for index, vehicle in enumerate(vehicles):
print('')
print('Id: {}'.format(index))
print('Make: {}'.format(vehicle.make))
print('Model: {}'.format(vehicle.model))
print('Mileage: {}'.format(vehicle.mileage))
print('')
selected_id = input('Please select vehicle Id:')
selected_vehicle = vehicles[selected_id]
new_milage = input('Enter new mileage for {}:'.format(selected_vehicle.make + ' ' + selected_vehicle.model))
selected_vehicle.mileage = new_milage
print('Mileage for {} {} was secesfully changed.'.format(selected_vehicle.make, selected_vehicle.model))
print('')
def edit_date_of_service(vehicles):
for index, vehicle in enumerate(vehicles):
print('')
print('Id: {}'.format(index))
print('Make: {}'.format(vehicle.make))
print('Model: {}'.format(vehicle.model))
print('Last service: {}'.format(vehicle.service))
print('')
selected_id = input('Please select vehicle Id:')
selected_vehicle = vehicles[selected_id]
new_service_date = input('Enter new date of service for {}:'.format(selected_vehicle.make + ' ' + selected_vehicle.model))
selected_vehicle.service = new_service_date
print('Date of service for {} {} was secesfully changed.'.format(selected_vehicle.make, selected_vehicle.model))
print('')
def add_vehicle(vehicles):
print('Please enter information about new vehicle')
new_make = input('Enter make of car: ')
new_model = input('Enter a model of {}: '.format(new_make))
new_mileage = input('Enter current mileage of {} {}: '.format(new_make, new_model))
new_service = input('Enter date of service for {} {}'.format(new_make, new_model))
new_car = Vehicle(make=new_make, model=new_model, mileage=new_mileage, service=new_service)
vehicles.append(new_car)
print('You succesfully entered {} {} on your list.'.format(new_make, new_model))
print('')
def delete_vehicle(vehicles):
for index, vehicle in enumerate(vehicles):
print('')
print('Id: {}'.format(index))
print('Make: {}'.format(vehicle.make))
print('Model: {}'.format(vehicle.model))
print('')
selected_id = int(input('Please select vehicle Id:'))
selected_vehicle = vehicles[selected_id]
vehicles.remove(selected_vehicle)
print('')
print('{} {} was successfully removed'.format(selected_vehicle.make, selected_vehicle.model))
def save_to_file(vehicles):
with open('vehicles.txt', 'w+') as vehicle_file:
for index, vehicle in enumerate(vehicles):
vehicle_file.write('Id: {}\n'.format(index))
vehicle_file.write('Make: {}\n'.format(vehicle.make))
vehicle_file.write('Model: {}\n'.format(vehicle.model))
vehicle_file.write('Mileage: {}\n'.format(vehicle.mileage))
vehicle_file.write('Service: {}\n'.format(vehicle.service))
vehicle_file.write('\n')
def main():
vehicles = []
while True:
print('What would you like to do?')
print('1. List of all vehicles.')
print('2. Edit mileage for vehicle.')
print('3. Edit date of last service.')
print('4. Add new vehicle.')
print('5. Delete vehicle.')
print('6. Save and quit.')
selected = int(input('Pick a number of the task:'))
if selected == 1:
list_of_vehicles(vehicles)
elif selected == 2:
edit_mileage(vehicles)
elif selected == 3:
edit_date_of_service(vehicles)
elif selected == 4:
add_vehicle(vehicles)
elif selected == 5:
delete_vehicle(vehicles)
elif selected == 6:
save_to_file(vehicles)
print('')
print('Thank you for using out program.')
print('Hvae a nice day.')
print('Bye')
break
else:
print('Please enter number of task you want to make!')
if __name__ == '__main__':
main()
|
4ed5e33077d6194e4d3b25d831b7600301d47f77 | sanjitroy1992/PythonCodingTraining | /coderbyte/binary_wildcard.py | 259 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
binary wildcard combinations
"""
def ans(s):
ans = [""]
for i in s:
if i == "?":
ans = [x + "0" for x in ans] + [x + "1" for x in ans]
else:
ans = [x + i for x in ans]
return ans |
b0544010531e643f3576a2ec4982b2be42b457fe | wangtao666666/leetcode | /20181002-7-Reverse_Integer.py | 579 | 3.875 | 4 | # encoding='utf-8'
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
mindata = -pow(2, 31)
maxdata = pow(2, 31) - 1
if x < mindata or x > maxdata:
return 0
else:
if x < 0:
result = -int(str(-x)[::-1])
else:
result = int(str(x)[::-1])
if result < mindata or result > maxdata:
return 0
else:
return result
x = 123
test = Solution()
result = test.reverse(x)
print(result) |
66369f29a7756e00c599c42b52119debb5e0b2d0 | eltolis/ZombieAdventure | /zombieadventure/old_building.py | 2,992 | 3.75 | 4 | # -*- coding: utf-8 -*-
import prompt
import custom_error
import score
import death
def enter(the_player):
the_player.location = 'Old Building'
the_player.directions = ['March Street','Old Building (first floor)']
print "\nLocation:", the_player.location
print "-" * 30
num_of_tries = 4
if the_player.location in the_player.visited and 'flashlight' in the_player.inventory.keys():
print "You turn on the flashlight. Suddenly you can see all"
print "the dead bodies in the room."
if 'first time flash light' in the_player.visited:
print "You see the trunk."
else:
the_player.visited.append('first time flash light')
score.calculate(the_player,'turn on lights')
print "Apart from the horrendous scene you notice a large trunk"
print "in the back of the room."
print "You come closer to open it but discover that"
print "it has a mechanical lock on it with three"
print "cylinders with number on them."
print "The trunk has letters 'AK' crudely painted on it."
if 'Wanda' in the_player.visited:
print "\nWanda: 'That trunk is where our stuff should be.'"
elif the_player.location in the_player.visited:
print "You are at the lobby of %s again. It's dark here." % the_player.location
else:
the_player.visited.append(the_player.location)
print "It's very dark inside and the smell is horrible."
print "You can't see anything but you see a little"
print "light coming from the other side of the lobby."
print "You see some stairs leading up to first floor."
if 'Wanda' in the_player.visited:
print "\nWanda: 'This is it, this is the building. The stuff"
print "must be somewhere here.'"
while True:
action = prompt.standard(the_player)
if action == "march street" or 'out' in action:
return 'March Street'
elif action == "stairs" or action == "first floor":
return 'Old Building (first floor)'
elif action == "trunk" and not 'map' in the_player.inventory.keys():
if 'Wanda' in the_player.visited:
print "\n'The code is 498 but be careful"
print "because you only have few tries."
print "There's a special poison needle"
print "to avoid hassling with the lock'"
else:
pass
while True:
if num_of_tries != 0:
try:
passcode = int(raw_input("Enter three digits, '000' to go away > "))
num_of_tries = num_of_tries - 1
except ValueError:
print "Put three numbers only"
if passcode == 000:
break
elif passcode == 498:
the_player.inventory['boat key'] = 1
score.calculate(the_player, 'key')
print "You find some junk inside but most importantly,"
print "the key for the boat is there. It is squared-shaped"
print "and kind of unique."
if 'Wanda' in the_player.visited:
print "Wanda: 'We got the key! Let's go.'"
else:
pass
break
else:
print "It's still locked."
else:
death.type(9, the_player)
else:
custom_error.errortype(3)
pass |
bd1ae9bbd1b08e8ce21cafe34ed4abfd7c4ee39e | namyangil/edu | /Python/codeup/codeup_3014.py | 150 | 3.796875 | 4 | for i in range(20):
if i==19:
print("hello",end=" ")
else:
print("hello",end="")
for j in range(30):
print("world",end="") |
9887e3b2746475fac540a33f0f6af53140341740 | Thiagolino8/Documentos | /main.py | 213 | 3.5625 | 4 | from Documento import Documento
while True:
documento = (input("Insira seu documento: ")).strip()
documento = Documento.cria(documento)
if not documento:
continue
break
print(documento)
|
54b11cc13895b9a8e14645c1fbfb21b003aa9249 | sxdegithub/pythonExercise | /pythonExercise/py001/py001_a.py | 972 | 3.953125 | 4 | # coding=utf-8
# https://github.com/Show-Me-the-Code/show-me-the-code
# 做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?
import random
import string
# 大小写字母,数字
letter = string.ascii_letters
digit = string.digits
# 连接后作为取样的population
chars = letter + digit
# print(chars)
# tuple_a = ("222", "112", "3", "224", "22")
# random.sample()
# 生成8个随机字符
def get_8():
return "".join(random.sample(chars, 8))
# print(" ".join(random.sample(tuple_a, 2)))
# 将4个8位字符通过-拼接
def get_32():
return "-".join([get_8() for i in range(4)])
# 需要获取的组数
def get_group(num):
return [get_32() for i in range(num)]
# if __name__ == "__main__":
# group = get_group(10)
# for i in group:
# print(i)
"""
HfLdnuOQ-KS4AhnQH-1KP3RuUG-KLIShGZ3
PYr5WRi2-AsoT9H7f-y4oVxirP-8SiQtw29
KmN16Ysg-lceCaiHJ-y8zDCALo-Nc4iUXvB
Y84Wqctx-mZrR0w3t-vNJj1plb-MlLnxkV5
r1HSyBcP-gSbKBuVj-QutBkVHW-iLBJOgER
7jDgyFSo-m7qazn09-Vfv4Y9rA-yGKFEfUw
dcfF2KMb-U1MJ7cle-Sw05G2fm-XnlzUQDF
wCo27jIp-KPqU0evE-sepUmIyb-TBQps5Vm
cB395Vg7-mI1sOY26-IRu4fWp0-9rW16Blc
LxytR2vp-1un56B2O-SuN5v7e9-ZDP96UIb
"""
|
d0aecaa08d47e70707d924278fb715db5b8dbcc2 | PedroBernini/ipl-2021 | /set_0/p0_4.py | 485 | 3.8125 | 4 | # Programa baseado no algoritmo de Zeller, que calcula o dia da semana em que uma determinada data caiu (ou cairá).
year = 2017
month = 1
day = 9
def zellerAlgorithm(year, month, day):
if month in [1, 2]:
y1 = year - 1
m1 = month + 12
else:
y1 = year
m1 = month
y2 = y1 % 100
c = int(y1 / 100)
return (day + int((13 * (m1 + 1)) / 5) + y2 + int(y2 / 4) + int(c / 4) - 2 * c) % 7
out = zellerAlgorithm(year, month, day)
print(out) |
89d0c6969bb3083f25af28f7877fcb4e19c32815 | SamanehGhafouri/DataStructuresInPython | /list.py | 1,687 | 3.765625 | 4 | # ***************************************** List comprehension ***********************
x = list()
y = ['a', 25, 'dog', 8.43]
tuplel = (10, 2)
z = list(tuplel)
# List comprehension
a = [m for m in range(8)]
print(a)
b = [i**2 for i in range(10) if i > 4]
print(b)
# ***************************************** DELETE ***********************
x = [5, 3, 8, 6]
del(x[1])
print(x)
del(x)
# ***************************************** Append ***********************
x = [5, 3, 8, 6]
x.append(7)
print(x)
# ***************************************** Extend ***********************
x = [5, 3, 8, 6]
y = [12, 13]
x.extend(y)
print(x)
# ***************************************** Insert ***********************
x = [5, 3, 8, 6]
x.insert(1, 7) # insert(index, value)
print(x)
x.insert(1, ['a', 'm'])
print(x)
# ***************************************** Pop *********************************
x = [5, 3, 8, 6]
x.pop()
print(x)
print(x.pop())
# ***************************************** Remove *********************************
x = [5, 3, 8, 6, 3]
x.remove(3) # python starts finding the elements from the beginning of the list
print(x) # finds the first matching
# ***************************************** Reverse *********************************
x = [5, 3, 8, 6]
x.reverse()
print(x)
# ***************************************** Sort *********************************
x = [5, 3, 8, 6] # sorted() is not the inplace sort, it returns a new list
x.sort() # sort() is an inplace sort
print(x)
# ***************************************** inplace reverse *********************************
x = [5, 3, 8, 6]
x.sort(reverse=True)
print(x) |
78621bcc3b475c835b62d468b6c5df4a9ae53b72 | henryji96/LeetCode-Solutions | /Easy/409.longest-palindrome/longest-palindrome.py | 455 | 3.59375 | 4 | from collections import Counter
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
sDict = dict(Counter(s))
ans = 0
existOrder = 0
for num in sDict.values():
ans += num // 2
if num % 2 != 0:
existOrder = 1
return ans * 2 + existOrder
if __name__ == '__main__':
print(s.longestPalindrome("abccccdd"))
|
7496df61eec6f34b10c6272be8dd699256acc55d | geediegram/parsel_tongue | /gideon/else_statement.py | 709 | 3.640625 | 4 | # year = int(input())
# print("Leap" if year % 400 == 0 or year % 4 == 0 and year % 100 != 0 else "Ordinary")
# year = int(input())
# if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
# print("Leap")
# else:
# print("Ordinary")
# num_1 = int(input())
# num_2 = int(input())
# maximum = num_1
# if num_2 > maximum:
# minimum = num_1
# maximum = num_2
# print(maximum)
# print(minimum)
# num_1 = int(input())
# num_2 = int(input())
# maximum = num_1
# if num_2 > maximum:
# print(num_2)
# print(num_1)
# else:
# print(num_1)
# print(num_2)
# k = int(input())
# count = 1
# while count <= k:
# count = count + 1
# total = count + k
# print(total)
|
6cdb09fbf24fcf74e244f33f48ea87948ffe9f2e | astikanand/Interview-Preparation | /Algorithms/7. String Algorithms /3_kmp_algo.py | 1,169 | 3.546875 | 4 | def calculate_lps(pat):
m = len(pat)
lps = [0]*m
i = 1; j = 0
while(i < m):
if(pat[i] == pat[j]):
lps[i] = j+1
i+=1
j+=1
elif(j>0):
j = lps[j-1]
else:
lps[i] = 0
i+=1
return lps
# print("LPS Example-1:")
# pat = "ababaca"
# print(str(calculate_lps(pat)))
# print("\nLPS Example-2:")
# pat = "abcdabeabf"
# print(str(calculate_lps(pat)))
# Complexity:
# Time: O(m)
# Space: O(m)
def KMP_search(pat, text):
lps = calculate_lps(pat)
i=0; j=0
m = len(pat)
n = len(text)
while(i<n):
if(text[i] == pat[j]):
i+=1
j+=1
if(j == m):
print("Found at index {}".format(i-j))
j = lps[j-1]
elif(j>0):
j = lps[j-1]
else:
i+=1
print("KMP Example-1:")
txt = "bacbabababacaca"
pat = "ababaca"
KMP_search(pat, txt)
print("\nKMP Example-2:")
txt = "abracadabra"
pat = "ab"
KMP_search(pat, txt)
print("\nKMP Example-3:")
txt = "AABAACAADAABAABA"
pat = "AABA"
KMP_search(pat, txt)
# Complexity:
# Time: O(m+n)
# Space: O(m) |
e7abec69343691d132e2481c8aff7645d30ea235 | tarunnagole/bankmanagementsystems | /bank.py | 3,437 | 4.03125 | 4 | import sys
import sqlite3
import random as r
class customer:
bank_name='Welcome To SBI BANK'
conn=None
def __init__(self):
self.conn=sqlite3.connect('customer.db')
self.cursor=self.conn.cursor()
self.cursor.execute("create table if not exists customer(accno int primary key,name varchar(20),balance int)")
def getaccount(self):
accno=r.randint(100001,999999)
name=input("Enter Your Name")
balance=int(input("Enter your balance"))
self.cursor.execute("insert into customer values(?,?,?)",(accno,name,balance))
self.conn.commit()
print("Hello",name,"Your Account got Created")
self.cursor.execute("select accno from customer where name='{}'".format(name))
AccountNumber=self.cursor.fetchone()
for i in AccountNumber:
print("plz notedown your AccountNumber:",i)
sys.exit()
def deposit(self):
acno=int(input("Enter your account number"))
dpst=int(input("Enter your amount to deposit"))
self.cursor.execute("update customer set balance=balance+{} where accno={}".format(dpst,acno))
self.conn.commit()
self.cursor.execute("select balance from customer where accno={}".format(acno))
bal=self.cursor.fetchone()
for i in bal:
print("Hi After deposit your balance Amount is:",i)
def withdraw(self):
acno=int(input("Enter your account number"))
wdamt=int(input("Enter your amount to withdraw"))
self.cursor.execute("select balance from customer where accno={}".format(acno))
bal=self.cursor.fetchone()
t=0
for i in bal:
t=int(i)
if wdamt>t:
print("Sorry..Insufficient Funds in Your Account")
sys.exit
else:
self.cursor.execute("update customer set balance=balance-{} where accno={}".format(wdamt,acno))
self.conn.commit()
self.cursor.execute("select balance from customer where accno={}".format(acno))
bal=self.cursor.fetchone()
for i in bal:
print("Hi After withdraw your balance Amount is:",i)
def loaddata(self):
#self.conn = sqlite3.connect("customer.db")
acno=int(input("enter your account number"))
query = "SELECT * FROM customer where accno={}".format(acno)
self.cursor.execute(query)
r=self.cursor.fetchone()
print(r)
def alldata(self):
#self.conn = sqlite3.connect("customer.db")
#acno=int(input("enter your account number"))
query = "SELECT * FROM customer"
self.cursor.execute(query)
rows=self.cursor.fetchall()
for i in rows:
print(i)
self.conn.close()
print("Welcome to Python",customer.bank_name)
c1=customer()
print("Are You Existing Customer or New Customer")
print("E-Existing\nN-New Customer")
option=input("choose your option")
if option=='N' or option=='n':
c1.getaccount()
elif option=='E' or option=='e':
while True:
print("D-Deposit\nW-Withdraw\nS-Show\nA-all\nE-Exit")
option=input("choose your option")
if option=='D' or option=='d':
c1.deposit()
elif option=='W' or option=='w':
c1.withdraw()
elif option=='S' or option=='s':
c1.loaddata()
elif option=='A' or option=='a':
c1.alldata()
else:
print("Invalid Option choose valid Option please")
|
886e97dd71088eaff7bbcd3f592b05b56bdbbbab | JinXiaozhao/python_learn | /data_structure/LinkList/link_list.py | 3,766 | 4.03125 | 4 | class ListNode(object):
def __init__(self,now_data,next_data=None):
self.data = now_data
self.next = next_data
class LinkList(object):
def __init__(self):
self.head = None
def set(self):
print('以空格键结束输入!')
print('input:')
data = input()
if data != ' ':
self.head = ListNode(int(data))
p = self.head
else:
print('over!')
return
while 1:
data = input()
if data != ' ':
p.next = ListNode(int(data))
p = p.next
else:
print('over!')
break
@property
def show(self):
print('链表的元素如下所示:')
p = self.head
if p == None:
print('Empty!')
return
while p:
print(p.data,end = ',')
p = p.next
print('over!')
return
@property
def isempty(self):
p = self.head
if p == None:
return True
else:
return False
@property
def length(self):
l = 0
p = self.head
while p :
l += 1
p = p.next
return l
@property
def reverse(self):
new_head = self.head
self.head = None
while new_head:
p = new_head
new_head = new_head.next
p.next = self.head
self.head = p
return
def insert(self,data,pos):
if pos <= 0:
raise Exception('wrong position!')
if self.isempty and pos != 1:
raise Exception('wrong position!')
p = self.head
if pos == 1:
self.head = ListNode(int(data))
self.head.next = p
return
n = 2
while n < pos and p.next != None:
p = p.next
n += 1
if n == pos:
tmp = p.next
p.next = ListNode(int(data))
p = p.next
p.next = tmp
elif n < pos:
raise Exception('wrong position!')
return
def delete(self,pos):
if pos <= 0:
raise Exception('wrong position!')
if pos > self.length :
raise Exception('wrong position!')
if pos == 1:
self.head = self.head.next
else:
p = self.head
for i in range(pos-2):
p = p.next
p.next = p.next.next
return
def swap(self,m,n):
if m <= 0 or n <= 0 or m==n or m>self.length\
or n>self.length:
raise Exception('wrong position!')
if m>n:
x=m
m=n
n=x
new_head = ListNode(-1)
new_head.next = self.head
p = new_head
for i in range(m-1):
p = p.next
tmp = p
for i in range(m-1,n-1):
p = p.next
tmp.next,p.next = p.next,tmp.next
tmp.next.next,p.next.next = p.next.next,tmp.next.next
self.head = new_head.next
return
if __name__=='__main__':
x = LinkList()
x.show
x.set()
x.show
print('链表长度为:%d'%x.length)
print('删除第一个元素')
x.delete(1)
x.show
print('删除第5个元素')
x.delete(5)
x.show
print('在第4处插入元素4')
x.insert(4,4)
x.show
print('链表翻转')
x.reverse
x.show
print('将第2个元素与第6个元素交换位置')
x.swap(3,2)
x.show
|
6d46d003abb0565a90362ab87d8c9f1f6e035ffd | vincenzorm117/CCI_6edition | /problems/chapter5/2_binary_to_string/python/solution.py | 456 | 3.578125 | 4 | #!/usr/local/bin/python3
# Number is between 0 and 1
def binary_to_string(x):
binary = [0] * 32
mantissaIndex = 0
c = x
while c != 1 and mantissaIndex < 32:
c *= 2
if 1 < c:
binary[mantissaIndex] = 1
c -= 1
mantissaIndex += 1
if c != 1:
return "ERROR"
else:
binary[mantissaIndex] = 1
return '.'+''.join(str(x) for x in binary)
testcases = [
0.15625
] + [1/2**x for x in range(32)]
for t in testcases:
print(binary_to_string(t)) |
9969c47cb73f7c4018ad3919d45b0c31c62fade1 | LTMenezes/fluid-playlist | /fluidplaylist/spotify_helper.py | 7,366 | 3.625 | 4 | import random
import bcolors as colors
from spotipy import oauth2, client
class Spotify(object):
"""
Spotify serves as a helper to extend the spotipy library.
Args:
client_id (str): Spotify client id.
client_secret (str): Spotify client secret.
callback_url (str): Spotify callback url.
"""
def __init__(self, client_id, client_secret, callback_url):
self.client_id = client_id
self.client_secret = client_secret
self.callback_url = callback_url
def get_user_id(self, token):
"""
Get user id.
Args:
token (str): Spotify access token.
Returns:
string: User id.
"""
sp = client.Spotify(token)
user = sp.me()
return user['id']
def welcome_user(self, token):
"""
Welcome user in the terminal using their spotify user id.
Args:
token (str): Spotify access token.
"""
sp = client.Spotify(token)
user = sp.me()
print(colors.BITALIC + 'Nice to meet you '+ user['id']
+ ', let\'s create your fluent playlist.' + colors.ENDC)
def get_spotify_access_token(self):
"""
Prompts the user in the terminal for their access token.
Returns:
string: User access token.
"""
print(colors.BLUE + "Getting user token" + colors.ENDC)
sp_credentials = oauth2.SpotifyOAuth(self.client_id, self.client_secret, self.callback_url, scope='user-library-read playlist-read-private playlist-modify-private')
authorize_url = sp_credentials.get_authorize_url()
print('Visit this url: ' + authorize_url)
code = input('Input the spotify code: ')
token = sp_credentials.get_access_token(code)
print('This is your access token: ' + str(token['access_token']))
return token['access_token']
def get_spotify_access_token_from_access_code(self, access_code):
"""
Gets user access token from a given access code.
Args:
access_code (str): Spotify access code.
Returns:
string: User access token.
"""
sp_credentials = oauth2.SpotifyOAuth(self.client_id, self.client_secret, self.callback_url, scope='user-library-read playlist-read-private playlist-modify-private')
token = sp_credentials.get_access_token(access_code)
return token['access_token']
def get_authorize_url(self):
"""
Returns a valid authorize url for user authentification.
Returns:
string: User authorize url
"""
sp_credentials = oauth2.SpotifyOAuth(self.client_id, self.client_secret, self.callback_url, scope='user-library-read playlist-read-private playlist-modify-private')
return sp_credentials.get_authorize_url()
def get_current_user_saved_tracks(self, token, max_number_of_tracks):
"""
Get user saved tracks.
Args:
token (str): Spotify access token.
max_number_of_tracks (int): Maximum number of tracks to retrieve.
Returns:
Array: User saved tracks.
"""
sp = client.Spotify(token)
print(colors.BLUE + "Getting saved tracks" + colors.ENDC)
saved_tracks = []
offset = 0
while len(saved_tracks) < max_number_of_tracks:
input_tracks = sp.current_user_saved_tracks(min(max_number_of_tracks - len(saved_tracks), 50), offset)
for track in input_tracks['items']:
saved_tracks.append(track)
if (input_tracks['next'] is None):
break
offset += 50
print(colors.OK + "Sucessfully got "+ str(len(saved_tracks)) +" saved tracks" + colors.ENDC)
return saved_tracks
def get_tracks_audio_features(self, token, tracks):
"""
Get tracks audio features.
Args:
token (str): Spotify access token.
tracks (arr): Array of tracks.
Returns:
Array: Tracks audio features.
"""
audio_features = []
sp = client.Spotify(token)
print(colors.BLUE + "Getting "+ str(len(tracks)) + " tracks audio features" + colors.ENDC)
for index in range(0, len(tracks), 100) :
tracks_ids = []
for internal_index in range(index, min(index + 100, len(tracks))):
tracks_ids.append(tracks[internal_index]['track']['id'])
audio_feature = sp.audio_features(tracks_ids)
for internal_index in range(0, len(audio_feature)):
if audio_feature[internal_index] is not None:
audio_features.append(audio_feature[internal_index])
print(colors.OK + "Sucessfully got "+ str(len(audio_features)) +" tracks audio features" + colors.ENDC)
return audio_features
def get_featured_tracks(self, token, max_number_of_tracks):
"""
Get featured tracks.
Args:
token (str): Spotify access token.
max_number_of_tracks (int): Maximum number of tracks.
Returns:
Array: Featured tracks.
"""
print(colors.BLUE + "Getting featured tracks" + colors.ENDC)
sp = client.Spotify(token)
featured_playlists = sp.featured_playlists(limit=50)['playlists']['items']
featured_tracks = []
index = 0
while index < len(featured_playlists):
tracks = self.get_tracks_from_playlist(token, featured_playlists[index], max_number_of_tracks - len(featured_tracks))
for track in tracks:
featured_tracks.append(track)
index += 1
featured_tracks = random.sample(featured_tracks, max_number_of_tracks)
print(colors.OK + "Sucessfully got "+ str(len(featured_tracks)) +" featured tracks" + colors.ENDC)
return featured_tracks
def get_tracks_from_playlist(self, token, playlist, max_number_of_tracks):
"""
Get tracks from a playlist.
Args:
token (str): Spotify access token.
playlist (obj): Spotify playlist.
Returns:
Array: Playlist tracks.
"""
sp = client.Spotify(token)
user_id = playlist['owner']['id']
playlist_id = playlist['id']
saved_tracks = []
offset = 0
while len(saved_tracks) < max_number_of_tracks:
input_tracks = sp.user_playlist_tracks(user_id, playlist_id, limit=min(max_number_of_tracks - len(saved_tracks), 100))
for track in input_tracks['items']:
saved_tracks.append(track)
if (input_tracks['next'] is None):
break
offset += 100
return saved_tracks
def create_playlist(self, token, playlist, playlist_name):
"""
Creates a spotify playlist.
Args:
token (str): Spotify access token.
playlist (obj): Spotify playlist.
playlist_name (str): Playlist name.
"""
sp = client.Spotify(token)
me_id = sp.me()['id']
playlist_id = sp.user_playlist_create(me_id, playlist_name, False)['id']
playlist_tracks_id = []
for track in playlist:
playlist_tracks_id.append(track['uri'])
sp.user_playlist_add_tracks(me_id, playlist_id, playlist_tracks_id)
|
86f0108e27b8183198e174549d7867c1d069a275 | YidanLong1229/UVic_Projects | /CSC265_Software_Development_Methods/Online_Analytical_Processing_queries_1stprinciple/OLAP | 13,961 | 3.5 | 4 | #!/usr/bin/env python3
import argparse
import os
import sys
import csv
def main():
# deliberately left blank for your implementation - remove this comment and begin
arguments = sys.argv
groupby_flag = False
groupby_field = []
calculation_flag = False
calculation_label_field = []
labels = ['--min', '--max', '--mean', '--sum']
top_flag = False
top_args = []
count_flag = True
if("--group-by" in arguments):
groupby_flag = True
count_flag = False
for i in range(len(arguments)):
if arguments[i] == '--group-by':
groupby_field.append(arguments[i+1].lower())
break
for i in range(len(arguments)):
if(arguments[i] in labels):
calculation_label_field.append((arguments[i], arguments[i+1].lower()))
if(len(calculation_label_field) !=0):
calculation_flag = True
count_flag=False
if('--top' in arguments):
top_flag = True
count_flag = False
for i in range(len(arguments)):
if(arguments[i] == '--top'):
top_args.append(arguments[i+1])
top_args.append(arguments[i+2])
break
if("--count" in arguments):
count_flag = True
# print(groupby_flag, groupby_field)
# print(calculation_flag, calculation_label_field)
# print(count_flag)
# print(top_flag, top_args)
if(len(arguments)<=2):
print("invalid command line")
exit(0)
#filename
filename = arguments[2]
#Check that the CSV file provided in the first command-line argument exists
csv_reader =None
if(filename.endswith('.csv')):
try:
# check the file is readable
csv_file = open(filename, encoding='utf-8-sig')
csv_reader = csv.reader(csv_file, delimiter=',')
except:
print(filename+" is not readable!")
else:
print("no input file specified")
exit(0)
line_number = 0
lines = []
if csv_reader is not None:
for row in csv_reader:
lines.append(row.copy())
# lines = list(csv_reader)
# '''
#Validate the command line arguments
if(len(lines) !=0):
columns = lines[0]
count = len(lines)-1
# columns_set = set(columns) #headers
columns_set = {item.lower() for item in columns}
# print("header: ", columns_set)
#check the compuation field are all valid
calculation_field_set = {item[1] for item in calculation_label_field}
if(calculation_field_set.issubset(columns_set)):
pass
else:
notfound = calculation_field_set - (calculation_field_set&columns_set)
str_notfound = [str(item) for item in notfound]
error_msg = 'Error: '+filename+':no field with name ' +', '.join(str_notfound) +' found'
print(error_msg)
errorfile(8, error_msg)
writeoutput("")
exit(8)
#check the group by field are all valid
groupby_field_set = set(groupby_field)
if(groupby_field_set.issubset(columns_set)):
pass
else:
groupby_notfound = groupby_field_set - (groupby_field_set&columns_set)
str_notfound = [str(item) for item in groupby_notfound]
error_msg = 'Error: '+filename+':no group-by argument with name ' +', '.join(str_notfound) +' found'
# print(error_msg)
errorfile(9, error_msg)
writeoutput("")
exit(9)
else:
print("no content read")
#now start processing
#first only compute
# print(groupby_flag,calculation_flag, count_flag)
if(len(lines) !=0):
header = [item.lower() for item in columns]
if(groupby_flag==False and calculation_flag==False and count_flag==True):
msg = 'count\n'+str(len(lines)-1)
writeoutput(msg)
exit(0)
if(groupby_flag==False and calculation_flag==True):
result ={}
data = []
for i in range(1, len(lines)):
data.append((i, lines[i].copy()))
for item in calculation_label_field:
fun = item[0].replace('--','')
label = item[1]
key = fun+'_'+label
index = header.index(label)
if(fun=='max'):
r = max_fun(data, index, label, filename)
if(r !=None):
result[key] = '"'+str(r)+'"'
else:
errmsg = "Error: "+filename+":more than 100 non-numeric values found in aggregate column" + label
# errmsg = "Error: "+filename+":more than 100 non-numeric values found in aggregate column"
errorfile(7, errmsg)
exit(7)
elif(fun=='mean'):
r = mean_fun(data, index, label, filename)
if(r !=None):
result[key] = '"'+str(r)+'"'
else:
errmsg = "Error: "+filename+":more than 100 non-numeric values found in aggregate column" + label
# errmsg = "Error: "+filename+":more than 100 non-numeric values found in aggregate column "+label
errorfile(7, errmsg)
exit(7)
elif(fun=='min'):
r = min_fun(data, index, label, filename)
if(r !=None):
result[key] = '"'+str(r)+'"'
else:
errmsg = "Error: "+filename+":more than 100 non-numeric values found in aggregate column" + label
# errmsg = "Error: "+filename+":more than 100 non-numeric values found in aggregate column "+label
errorfile(7, errmsg)
exit(7)
elif(fun=='sum'):
r = sum_fun(data, index, label, filename)
if(r !=None):
result[key] = '"'+str(r)+'"'
else:
errmsg = "Error: "+filename+":more than 100 non-numeric values found in aggregate column" + label
# errmsg = "Error: "+filename+":more than 100 non-numeric values found in aggregate column "+label
errorfile(7, errmsg)
exit(7)
# print(result)
message = ",".join(result.keys())+"\n"+",".join(result.values())
writeoutput(message)
# second, first group then count and compute
if(groupby_flag==True):
keys = []
data ={}
grouplabel = groupby_field[0]
index = header.index(grouplabel)
result = {}
if(count_flag ==True):
outputheader = [grouplabel, 'count']
else:
outputheader = [grouplabel]
for i in range(1, len(lines)):
curr = lines[i][index]
if(curr in keys):
data[curr].append( (i, lines[i].copy()) )
else:
keys.append(curr)
data[curr] = [ (i, lines[i].copy())]
keys = sorted(keys)
#if more than 20 distinct values
if(len(keys)>20):
errmsg = 'Error:'+filename+":ticker has been capped at 20 distinct values"
errorfile("n", errmsg)
writeoutput("")
print("more then 20")
exit(0)
for outkey in keys:
if(count_flag ==True):
result[outkey] = [outkey, str(len(data[outkey]))]
else:
result[outkey] = [outkey]
# print(calculation_label_field)
if(calculation_flag==True):
for outkey in keys:
# print(calculation_label_field)
for item in calculation_label_field:
fun = item[0].replace('--','')
label = item[1]
key = fun+'_'+label
if(key in outputheader):
pass
else:
outputheader.append(key)
# print("***:", key)
index = header.index(label)
if(fun=='max'):
r = max_fun(data[outkey], index, label, filename)
if(r !=None):
result[outkey].append('"'+str(r)+'"')
else:
errmsg = "Error: "+filename+":more than 100 non-numeric values found in aggregate column" + label
# errmsg = "Error: "+filename+":more than 100 non-numeric values found in aggregate column"
errorfile(7, errmsg)
exit(7)
elif(fun=='mean'):
r = mean_fun(data[outkey], index, label, filename)
if(r !=None):
result[outkey].append('"'+str(r)+'"')
else:
errmsg = "Error: "+filename+":more than 100 non-numeric values found in aggregate column" + label
# errmsg = "Error: "+filename+":more than 100 non-numeric values found in aggregate column "+label
errorfile(7, errmsg)
exit(7)
elif(fun=='min'):
r = min_fun(data[outkey], index, label, filename)
if(r !=None):
result[outkey].append('"'+str(r)+'"')
else:
errmsg = "Error: "+filename+":more than 100 non-numeric values found in aggregate column" + label
# errmsg = "Error: "+filename+":more than 100 non-numeric values found in aggregate column "+label
errorfile(7, errmsg)
exit(7)
elif(fun=='sum'):
r = sum_fun(data[outkey], index, label, filename)
if(r !=None):
result[outkey].append('"'+str(r)+'"')
else:
errmsg = "Error: "+filename+":more than 100 non-numeric values found in aggregate column" + label
# errmsg = "Error: "+filename+":more than 100 non-numeric values found in aggregate column "+label
errorfile(7, errmsg)
exit(7)
# print(result)
message = ",".join(outputheader)+"\n"
for k,v in result.items():
message+= ",".join(v)+"\n"
message = message[:-1]
writeoutput(message)
if(top_flag==True):
data =[]
# result = []
k = int(top_args[0])
top_label = top_args[1]
# print(top_label)
top_index = header.index(top_label)
for i in range(1, len(lines)):
data.append((i, lines[i].copy()))
if(groupby_flag==False):
r = top_fun(data, top_index, label, filename)
if(r!=None):
message = "top_"+top_label+"\n"+'"'+",".join(r[:k])+'"'
writeoutput(message)
exit(0)
else:
message = "Error: "+filename+" "+label+" has been capped at 20 distinct values"
# message = "Error: "+filename+" "+label+" has been capped at 20 distinct values"
errorfile("20_distint_err", message)
exit(6)
else:
keys = []
data_dict ={}
grouplabel = groupby_field[0]
index = header.index(grouplabel)
result = {}
outputheader = [grouplabel, "top_"+top_label]
for i in range(1, len(lines)):
curr = lines[i][index]
if(curr in keys):
data_dict[curr].append( (i, lines[i].copy()) )
else:
keys.append(curr)
data_dict[curr] = [ (i, lines[i].copy())]
keys = sorted(keys)
message = ",".join(outputheader)+"\n"
for key in keys:
r = top_fun(data_dict[key], top_index, label, filename)
if(r!=None):
message+= key+',"'+",".join(r[:k])+'"'+"\n"
# else:
# message = "Error: "+filename+" "+label+" has been capped at 20 distinct values"
# # message = "Error: "+filename+" "+label+" has been capped at 20 distinct values"
# errorfile("20_distint_err", message)
# exit(6)
message = message[:-1]
writeoutput(message)
exit(0)
def errorfile(errnum, errmsg):
errfilename = str(errnum)+".err"
f = open(errfilename,"w")
f.write(errmsg+"\n")
print(errmsg)
f.close()
def writeoutput(msg):
# f = open('output.csv',"w")
# f.write(msg+"\n")
print(msg)
# f.close()
def non_numeric_err(errmsg):
f = open('non_numeric_error',"a+")
f.write(errmsg+"\n")
print(errmsg)
f.close()
def max_fun(arr, index, label, filename):
maxvalue = -1000000
non_numeric_count = 0
for item in arr:
line = item[0]
val = item[1]
try:
current = float(val[index])
if(current>maxvalue):
maxvalue = current
except:
# print(label, str([val[index]]))
# print(val, index)
errmsg = 'Error: '+ filename+':'+str(line)+": can’t compute max on non-numeric value "+"'"+val[index]+"'\n"
non_numeric_err(errmsg)
non_numeric_count+=1
if(non_numeric_count>100):
return None
return maxvalue
def mean_fun(arr, index, label, filename):
meanvalue = 0
count=0
non_numeric_count = 0
for item in arr:
line = item[0]
val = item[1]
try:
current = float(val[index])
meanvalue+=current
count+=1
except:
errmsg = 'Error: '+ filename+':'+str(line)+": can’t compute mean on non-numeric value "+"'"+val[index]+"'\n"
non_numeric_err(errmsg)
non_numeric_count+=1
if(non_numeric_count>100):
return None
return meanvalue/count
def min_fun(arr,index, label, filename):
minvalue = 1000000
non_numeric_count = 0
for item in arr:
line = item[0]
val = item[1]
try:
current = float(val[index])
if(current<minvalue):
minvalue = current
except:
errmsg = 'Error: '+ filename+':'+str(line)+": can’t compute min on non-numeric value "+"'"+val[index]+"'\n"
non_numeric_err(errmsg)
non_numeric_count+=1
if(non_numeric_count>100):
return None
return minvalue
def sum_fun(arr, index, label, filename):
sumvalue = 0
non_numeric_count = 0
for item in arr:
line = item[0]
val = item[1]
try:
current = float(val[index])
sumvalue+=current
except:
# print(label, str([val[index]]))
# print(val, index)
errmsg = 'Error: '+ filename+':'+str(line)+": can’t compute sum on non-numeric value "+"'"+val[index]+"'\n"
non_numeric_err(errmsg)
non_numeric_count+=1
if(non_numeric_count>100):
return None
# exit(0)
return sumvalue
def top_fun(arr, index, label, filename):
tempresult = {}
keys = []
for item in arr:
line = item[0]
val = item[1]
key = val[index]
if(key in keys):
tempresult[key]+=1
else:
tempresult[key]=1
keys.append(key)
if(len(keys)>20):
return None
r = []
for k,v in tempresult.items():
r.append((k,v))
for i in range(len(r)-1):
for j in range(i+1,len(r)):
if(r[i][1]<r[j][1]):
t = r[j]
r[j] = r[i]
r[i] = t
return [ele[0]+": "+str(ele[1]) for ele in r]
if __name__ == '__main__':
main()
|
7de35716a35ed54f1940a5a5571eca1dfc710990 | gabriellaec/desoft-analise-exercicios | /backup/user_227/ch26_2020_03_07_19_48_48_200459.py | 342 | 4.0625 | 4 | valor_da_casa = float(input("Qual o valor da casa a comprar? "))
salário = float(input("Qual seu salário? "))
anos = int(input("Qual a quantidade de anos a pagar? "))
valor_da_prestação = (valor_da_casa/(12*anos))
if valor_da_prestação > 0.3*salário :
print("Empréstimo não aprovado")
else:
print("Empréstimo aprovado")
|
f21eb9182e50564efb9036f298c5be46f5bec68c | 0helloword/pytest | /src/practice/get_phone_num.py | 715 | 3.96875 | 4 | # -*- coding: utf-8 -*-
import os
import random
phone_number_list = [133, 153, 180, 181, 189, 130, 131, 132, 145, 155, 156, 185, 186, 134, 135, 136, 137,
138, 139, 147, 150, 151, 152, 157, 158, 159, 182, 183, 184, 187, 188]
def get_phone_number():
phone_number = ''
eight_number_count = 0
phone_three_start_number = phone_number_list[random.randint(0, len(phone_number_list)-1)]
phone_number += str(phone_three_start_number)
while eight_number_count < 8:
phone_number += str(random.randint(0, 9))
eight_number_count += 1
pass
return phone_number
pass
if __name__ == '__main__':
print(get_phone_number()) |
0f88dac5c3e8c6826f4b38f26b9e7f2845bc5715 | terrysky18/Python-repo | /My Python Scripts/Python Game Lesson/explode_example.py | 1,072 | 3.5625 | 4 | """
The explosion example in code skulptor
"""
import simpleguitk as simplegui
EXPLOSION_CENTRE = [50, 50]
EXPLOSION_SIZE = [100, 100]
EXPLOSION_DIM = [9, 9]
explosion_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/explosion.hasgraphics.png")
# create timer that iterate current_sprite_centre through sprite
time = 0
# define draw handler
def draw(canvas):
global time
explosion_index = [time % EXPLOSION_DIM[0], (time // EXPLOSION_DIM[0]) % EXPLOSION_DIM[1]]
canvas.draw_image(explosion_image,
[EXPLOSION_CENTRE[0] + explosion_index[0] * EXPLOSION_SIZE[0],
EXPLOSION_CENTRE[1] + explosion_index[1] * EXPLOSION_SIZE[1]],
EXPLOSION_SIZE, EXPLOSION_CENTRE, EXPLOSION_SIZE)
time += 1
# end of draw()
# create frame and size frame based on 100x100 pixel sprite
frame = simplegui.create_frame("Asteroid sprite", EXPLOSION_SIZE[0], EXPLOSION_SIZE[1])
# set draw handler and canvas background using custom HTML colour
frame.set_draw_handler(draw)
frame.set_canvas_background("blue")
# start animation
frame.start()
|
cb1485e166e193c3521d8a66ebd45cc5ca3cb8be | rrrituraj/python | /OOPS/multiple_inheritence_example.py | 5,499 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 21 12:29:14 2016
@author: RITURAJ
"""
"""
The class Clock is used to simulate a clock.
"""
class Clock():
def __init__(self , hours , minutes , seconds):
"""
The paramaters hours, minutes and seconds have to be
integers and must satisfy the following equations:
0 <= h < 24
0 <= m < 60
0 <= s < 60
"""
self.Set_Clock(hours , minutes , seconds)
def Set_Clock(self , hours , minutes , seconds):
"""
The paramaters hours, minutes and seconds have to be
integers and must satisfy the following equations:
0 <= h < 24
0 <= m < 60
0 <= s < 60
"""
if type(hours) == int and 0 <= hours and hours < 24:
self._hours = hours
else:
raise TypeError("Hours have to be integers between 0 and 23!")
if type(minutes) == int and 0 <= minutes and minutes < 60:
self.__minutes = minutes
else:
raise TypeError("minutes have to be integers between 0 and 60!")
if type(seconds) == int and 0 <= seconds and seconds < 60:
self.__seconds = seconds
else:
raise TypeError("seconds have to be integers between 0 and 60!")
def __str__(self):
return "{0:02d}:{1:02d}:{2:02d}".format(self._hours,
self.__minutes,
self.__seconds)
def tick(self):
'''
This method lets the clock "tick", this means that the
internal time will be advanced by one second.
'''
if self.__seconds == 59:
self.__seconds = 0
if self.__minutes == 59:
self.__minutes = 0
if self._hours == 23:
self._hours = 0
else:
self._hours += 1
else:
self.__minutes += 1
else:
self.__seconds += 1
"""
The class Calendar implements a calendar.
"""
class Calendar(object):
months = (31,28,31,30,31,30,31,31,30,31,30,31)
date_style = "British"
@staticmethod
def leapyear(year):
"""
The method leapyear returns True if the parameter year
is a leap year, False otherwise
"""
if year % 4 == 0:
if year % 100 == 0:
# divisible by 4 and by 100
if year % 400 == 0:
leapyear = True
else:
leapyear = False
else:
# divisible by 4 but not by 100
leapyear = True
else:
# not divisible by 4
leapyear = False
return leapyear
def __init__(self , d , m , y):
self.Set_Calendar(d , m , y)
def Set_Calendar(self , d , m , y):
if type(d) == int and type(m) == int and type(y) == int:
self.__days = d
self.__months = m
self.__years = y
else:
raise TypeError("d, m, y have to be integers!")
def __str__(self):
if Calendar.date_style == "British":
return "{0:02d}/{1:02d}/{2:4d}".format(self.__days,
self.__months,
self.__years)
else:
# assuming American style
return "{0:02d}/{1:02d}/{2:4d}".format(self.__months,
self.__days,
self.__years)
def advance(self):
"""
This method advances to the next date.
"""
max_days = Calendar.months[self.__months-1]
if self.__months == 2 and Calendar.leapyear(self.__years):
max_days += 1
if self.__days == max_days:
self.__days= 1
if self.__months == 12:
self.__months = 1
self.__years += 1
else:
self.__months += 1
else:
self.__days += 1
"""
Modul, which implements the class CalendarClock.
"""
class CalendarClock(Clock , Calendar):
"""
The class CalendarClock implements a clock with integrated
calendar. It's a case of multiple inheritance, as it inherits
both from Clock and Calendar
"""
def __init__(self,day, month, year, hours, minutes, seconds):
Clock.__init__(self,hours, minutes, seconds)
Calendar.__init__(self,day, month, year)
def tick(self):
"""
advance the clock by one second
"""
previous_hour = self._hours
Clock.tick(self)
if (self._hours < previous_hour):
self.advance()
def __str__(self):
return Calendar.__str__(self)+',' + Clock.__str__(self)
if __name__ == "__main__":
x = CalendarClock(31,12,2013,23,59,58)
print("One tick from ",x, end=" ")
x.tick()
print("to ", x)
x = CalendarClock(28,2,1900,23,59,59)
print("One tick from ",x, end=" ")
x.tick()
print("to ", x)
|
8d6045df812f7c68ab116130a02a1db51f5377d1 | Ankit-29/competitive_programming | /Strings/increasingDecreasingString.py | 1,968 | 3.84375 | 4 | '''
Given a string s. You should re-order the string using the following algorithm:
- Pick the smallest character from s and append it to the result.
- Pick the smallest character from s which is greater than the last appended character to the result and append it.
- Repeat step 2 until you cannot pick more characters.
- Pick the largest character from s and append it to the result.
- Pick the largest character from s which is smaller than the last appended character to the result and append it.
- Repeat step 5 until you cannot pick more characters.
- Repeat the steps from 1 to 6 until you pick all characters from s.
- In each step, If the smallest or the largest character appears more than once you can choose any occurrence and
append it to the result
Return the result string after sorting s with this algorithm.
Constraints:
- 1 <= s.length <= 500
- s contains only lower-case English letters.
Input: s = "aaaabbbbcccc"
Output: "abccbaabccba"
Explanation: After steps 1, 2 and 3 of the first iteration, result = "abc"
After steps 4, 5 and 6 of the first iteration, result = "abccba"
First iteration is done. Now s = "aabbcc" and we go back to step 1
After steps 1, 2 and 3 of the second iteration, result = "abccbaabc"
After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba"
Input: s = "rat"
Output: "art"
'''
def sortString(s: str) -> str:
frequency = [0]*26
ans = ""; lengthAns = 0; lengthS = len(s)
for char in s:
frequency[ord(char)-ord('a')] += 1
while(lengthAns != lengthS):
for idx in range(0,26):
if(frequency[idx]!=0):
ans += chr(idx+ord('a'))
lengthAns += 1
frequency[idx] -= 1
for idx in range(26-1,-1,-1):
if(frequency[idx]!=0):
ans += chr(idx+ord('a'))
lengthAns += 1
frequency[idx] -= 1
return ans
s = "aaaabbbbcccc"
print(sortString(s))
|
eb8c729b54d0df553b1a62a91d236bb45a068f66 | forrestliao/datastructure-algorithms | /array_stack.py | 817 | 3.859375 | 4 | class ArrayStack:
def __init__(self):
self.top = 0
self.stack = list()
def print_stack(self):
if not self.is_empty():
print(self.stack[:self.top])
else:
print("it's empty")
def is_empty(self):
return self.top == 0
def push(self, num):
if len(self.stack)>self.top:
self.stack[self.top] = num
else:
self.stack+= [num]
self.top+=1
def pop(self):
if not self.is_empty():
self.top-=1
else:
print("it's empty.")
if __name__=="__main__":
stack1 = ArrayStack()
stack1.push(14)
stack1.push(9)
stack1.pop()
stack1.push(7)
stack1.push(9)
stack1.pop()
stack1.pop()
stack1.pop()
stack1.pop()
stack1.print_stack() |
822ab0a4ac361e3c32efe243b3181d6a6e328206 | FapCod/Python | /Condicionales/ejercicioCinco.py | 764 | 4.03125 | 4 | saldo=1000
print("\t\t'Menu'")
print("1. Ingresar dinero en la cuenta")
print("2. Retirar dinero de la cuenta")
print("3. Mostrar dinero disponible")
print("4. Salir")
opc = int (input("digite una opcion del menu:"))
print()
if opc==1:
extra =float (input("cuanto dinero quiere ingresar--->"))
saldo += extra
print(f"Su saldo es de: {saldo} ")
elif opc==2:
retiro=float(input("cuanto dinero desea retirar --->"))
if retiro>saldo or saldo<=0:
print("no puede realizar el retiro")
else:
saldo=saldo-retiro
print(f"en su cuenta queda con un slado de {saldo}")
elif opc==3:
print(f"su saldo es de {saldo}")
elif opc==4:
print("gracias por venir")
exit()
else:
print(f"'esa {opc}'no esta programada ")
|
eff68ee869c3c9551a1c79f7e7752ec4104583cc | mich7095/curso_de_poo_y_algoritmos_python | /ordenamiento_insercion.py | 1,188 | 3.78125 | 4 | import random
def ordenamiento_por_insercion(lista):
# el for va guardando cada valor en memoria
# del siguiente numero en la lista, porque el
# for se inicializo desde 1
for indice in range(1, len(lista)):
valor_actual = lista[indice]
posicion_actual = indice
# este while esta validando que los numeros sea positivos (mayores a cero)
# y que (posicion actual - 1) sea mayor quela siguiente y si eso se cumple
# se intercamia los valores dejando el menor enla posicion anterior, cabe destacar que se
# coloca la"posicion actual - 1" ya que los vectores inicializa en 0 y en el for
# lo comenzamos en 1
while posicion_actual > 0 and lista[posicion_actual - 1] > valor_actual:
lista[posicion_actual] = lista[posicion_actual - 1]
posicion_actual -= 1
lista[posicion_actual] = valor_actual
return lista
if __name__=='__main__':
tamana_de_lista = int(input('de que tamaño quieres la lista: '))
lista = [random.randint(0, 100) for i in range(tamana_de_lista)]
print(lista)
lista_ordenada = ordenamiento_por_insercion(lista)
print(lista_ordenada) |
bf54a23cf162a76eecda59d85ae7f54cc0abedac | ranajoy-dutta/TechGig | /30-Day-Challenge/Day14_Lets_Make_A_Dictionary_Order.py | 162 | 3.765625 | 4 | def main():
n = int(input())
arr = []
for i in range(n):
arr.append(input())
arr = sorted(arr)
for i in arr:
print(i)
main()
|
26d083191f7d9a06da742fcee90b8c338dab7145 | challakarthikreddy/project_euler | /10001_prime_number.py | 229 | 3.578125 | 4 | count = 1
for num in range(2,10000000):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
count = count +1
print str(num) + '-----' + str(count) +'st prime' |
3f5f69c4e6367e25c885f5fc1217284ac665e4c2 | poojataksande9211/python_data | /python_tutorial/excercise_2/func_range.py | 227 | 4.1875 | 4 | #Write a Python function to check whether a number is in a given range
def range_with(n):
if n in range(3,9):
print("%s is in the range"%str(n))
else:
print("%s is out of the range"%str(n))
range_with(8) |
7cd01c71f45fbf08b2465ddd8ef9b77e241ffc3c | ttessaractt/Programming2_Tessa | /Problems/Plotting Problems/matplotlib_CTA_ridership.py | 2,535 | 4.09375 | 4 | # CTA Ridership (28pts)
# Get the csv from the following data set.
# https://data.cityofchicago.org/Transportation/CTA-Ridership-Annual-Boarding-Totals/w8km-9pzd
# This shows CTA ridership by year going back to the 80s
#1 Make a plot of rail usage for the most current 10 year period. (year on x axis, and ridership on y) (5pts)
#2 Plot bus usage for the same years as a second line on your graph. (5pts)
#3 Plot bus and rail usage together on a third line on your graph. (5pts)
#4 Add a title and label your axes. (5pts)
#5 Add a legend to show data represented by each of the three lines. (5pts)
#6 What trend or trends do you see in the data? Offer at least two hypotheses which might explain the trend(s). (3pts)
import matplotlib.pyplot as plt
import csv
plt.figure(1, tight_layout=True, figsize=(8, 6))
with open('CTA_-_Ridership_-_Annual_Boarding_Totals.csv') as f:
reader = csv.reader(f) # create a reader object from csv library
data = list(reader) # cast it as a list
header = data.pop(0)
year = [x[0] for x in data]
# Rail usage last 10 years
rail = [x[3] for x in data]
rail_ten = rail[-10:]
year_ten = year[-10:]
ten_year = [int(x) for x in year_ten]
ten_rail = [int(x) for x in rail_ten]
plt.plot(ten_year, ten_rail, color='pink', label="Rail")
plt.title("CTA Ridership By Year - Last 10 Years")
plt.xlabel("Year")
plt.ylabel("Ridership")
plt.xticks(ten_year, rotation=45, fontsize=8)
# Bus usage for same years
bus_usage = [x[1] for x in data]
bus = [x[1] for x in data]
bus_ten = bus[-10:]
ten_bus = [int(x) for x in bus_ten]
plt.plot(ten_year, ten_bus, color='lightblue', label="Bus")
# Plot both together on the same line (add them together)
total = [x[4] for x in data]
total_ten = total[-10:]
ten_total = [int(x) for x in total_ten]
plt.plot(ten_year, ten_total, color='thistle', label="Total")
plt.legend()
plt.show()
'''
Trends
After 2012 the total ridership of the CTA drops, with the bus riders dropping and the rail riders going slightly up,
but then declining a bit in 2016. Also the rails seemed to be gaining more riders since 2008, but still less then bus.
# 1
One could be the growing popularity of ride share apps, like uber and lyft, with people taking ubers instead of the bus
or train to work or school.
# 2
Another reason could be people are fed up with the conditions of the CTA, or the wait times. It could be faster to walk
or ride a bike then take the train and during rush hour it can take forever to get a train that isnt full of people.
''' |
0cf020afb34a34f0adec19756624b0e061937413 | zhousihan0126/zimpute | /zimpute/Select_r.py | 529 | 3.5625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 31 17:08:15 2019
@author: sihanzhou
"""
#the method about select r
import numpy as np
def select_r(Data_matrix_M):
u,sigma_list,v_T=np.linalg.svd(Data_matrix_M,full_matrices=False)
sigma_sum=0
for i in range(0,len(sigma_list)):
sigma_sum=sigma_sum+pow(sigma_list[i],2)
total=0
j=0
while 1:
total=total+pow(sigma_list[j],2)
j+=1
if total>0.9*sigma_sum:
break
r=j
return r
|
f44acbfd63bc7949a8bcafa524a0ac0b8d389b9d | rhanmiano/100days-coding-challenge | /py/day5-title-case.py | 1,049 | 4.0625 | 4 | ##
# 100 Days Coding Challenge
#
# @author Rhan Miano
# @since November 6, 2018
#
# Pushing myself to do this 100 Days Coding Challenge.
##
# Day 5 Title Case A Sentence
# Return the provided string with the first letter of each word capitalized.
# Make sure the rest of the word is in lower case.
# Initialize an empty string to handle the output.
# Loop through the provided string, and get each char
# by accessing its index. Check if the char is the
# first one in the string and if the char before it is
# a space ' ', if so make the char uppercase if it's in
# lowercase. For any other chars make it lowercase if
# it's in uppercase. Append each char to strOuput.
def titleCase(args):
strOutput = '';
for i in range(0, len(args)):
char = args[i]
if(args[i-1] == ' ' or i == 0):
if(char == char.lower()):
char = char.upper()
else:
if(char == char.upper()):
char = char.lower()
strOutput = strOutput + char
return strOutput
print(titleCase("say sOmethinG i'm giVing Up on yoU")) |
e266979ce618689e922486c756e973f5cee0886a | Bshel419/5303-DB-Shelton | /A09/A09.py | 13,184 | 3.921875 | 4 | #Benjamin Shelton and Garrett Morris
#A09
#Simple python program that generates users and has them send messages and times
#how long it took, by default it's 1000000 users, but can be paramaterized as well.
from random import randint
from time import time
from time import sleep
#startTime is universal
startTime = time()
choice = input("Generic or Paramaterized? (G or P)")
choice = choice.upper()
if choice == 'G':
for x in range(1000000):
#Generate percentage for age
age = randint(1, 100)
#13-17
if age <= 6:
age = 1
#18-24
elif age <= 31:
age = 2
#25-34
elif age <= 63:
age = 3
#35-44
elif age <= 78:
age = 4
#45-54
elif age <= 88:
age = 5
#55-64
elif age <= 94:
age = 6
#65+
else:
age = 7
#We just kind of eyeballed the number of messages sent by each age group
if age == 1:
messages = randint(50, 150)
elif age == 2:
messages = randint(25,100)
elif age == 3:
messages = randint(15, 75)
elif age == 4:
messages = randint(75, 140)
elif age == 5:
messages = randint(50, 75)
elif age == 6:
messages = randint(5, 15)
elif age == 7:
messages = randint(30, 80)
#Simple print statement so we know it's running
for y in range(messages):
print("Message " + str(y) + " Sent from User " + str(x))
elif choice == "P":
print("If you don't want to change the parameters just input 0")
users = input("Number of users: ")
users = int(users)
delay = input("Delay time per message: ")
delay = float(delay)
numMessages = input("Number of messages sent: ")
numMessages = int(numMessages)
runTime = input("Run time desired (Input Syntax: min, sec): ")
runTime = runTime.strip(",")
runTime = [int(runTime[0]), int(runTime[2])]
#if we want a certain number of users
if users > 0:
#if we want a certain time limit, also we assume if you want a time limit, you won't want to limit the number of messages
if runTime[1] > 0:
runTime = (runTime[0] * 60) + runTime[1]
while time()-startTime < runTime:
for x in range(users):
age = randint(1, 100)
#13-17
if age <= 6:
age = 1
#18-24
elif age <= 31:
age = 2
#25-34
elif age <= 63:
age = 3
#35-44
elif age <= 78:
age = 4
#45-54
elif age <= 88:
age = 5
#55-64
elif age <= 94:
age = 6
#65+
else:
age = 7
if age == 1:
messages = randint(50, 150)
elif age == 2:
messages = randint(25,100)
elif age == 3:
messages = randint(15, 75)
elif age == 4:
messages = randint(75, 140)
elif age == 5:
messages = randint(50, 75)
elif age == 6:
messages = randint(5, 15)
elif age == 7:
messages = randint(30, 80)
for y in range(messages):
print("Message " + str(y) + " Sent from User " + str(x))
#if there be a delay
if delay > 0:
sleep(delay)
#if we want a certain amount of messages
elif numMessages > 0:
totalMessages = 0
while totalMessages < numMessages:
for x in range(users):
age = randint(1, 100)
#13-17
if age <= 6:
age = 1
#18-24
elif age <= 31:
age = 2
#25-34
elif age <= 63:
age = 3
#35-44
elif age <= 78:
age = 4
#45-54
elif age <= 88:
age = 5
#55-64
elif age <= 94:
age = 6
#65+
else:
age = 7
if age == 1:
messages = randint(50, 150)
elif age == 2:
messages = randint(25,100)
elif age == 3:
messages = randint(15, 75)
elif age == 4:
messages = randint(75, 140)
elif age == 5:
messages = randint(50, 75)
elif age == 6:
messages = randint(5, 15)
elif age == 7:
messages = randint(30, 80)
for y in range(messages):
print("Message " + str(y) + " Sent from User " + str(x))
if delay > 0:
sleep(delay)
totalMessages += 1
#the way the for loop above works, it will send more messages even after we hit the totalMessage cap
if totalMessages >= numMessages:
break
#same idea as the other break, gets us to the while loop so we can stop, else it'll print out users-1 more messages
if totalMessages >= numMessages:
break
else:
for x in range(users):
age = randint(1, 100)
#13-17
if age <= 6:
age = 1
#18-24
elif age <= 31:
age = 2
#25-34
elif age <= 63:
age = 3
#35-44
elif age <= 78:
age = 4
#45-54
elif age <= 88:
age = 5
#55-64
elif age <= 94:
age = 6
#65+
else:
age = 7
if age == 1:
messages = randint(50, 150)
elif age == 2:
messages = randint(25,100)
elif age == 3:
messages = randint(15, 75)
elif age == 4:
messages = randint(75, 140)
elif age == 5:
messages = randint(50, 75)
elif age == 6:
messages = randint(5, 15)
elif age == 7:
messages = randint(30, 80)
for y in range(messages):
print("Message " + str(y) + " Sent from User " + str(x))
if delay > 0:
sleep(delay)
#if we want 1,000,000 users
else:
if runTime[1] > 0:
runTime = (runTime[0] * 60) + runTime[1]
while time()-startTime < runTime:
for x in range(1000000):
age = randint(1, 100)
#13-17
if age <= 6:
age = 1
#18-24
elif age <= 31:
age = 2
#25-34
elif age <= 63:
age = 3
#35-44
elif age <= 78:
age = 4
#45-54
elif age <= 88:
age = 5
#55-64
elif age <= 94:
age = 6
#65+
else:
age = 7
if age == 1:
messages = randint(50, 150)
elif age == 2:
messages = randint(25,100)
elif age == 3:
messages = randint(15, 75)
elif age == 4:
messages = randint(75, 140)
elif age == 5:
messages = randint(50, 75)
elif age == 6:
messages = randint(5, 15)
elif age == 7:
messages = randint(30, 80)
for y in range(messages):
print("Message " + str(y) + " Sent from User " + str(x))
#if there be a delay
if delay > 0:
sleep(delay)
#if we want a certain amount of messages
elif numMessages > 0:
totalMessages = 0
while totalMessages < numMessages:
for x in range(1000000):
age = randint(1, 100)
#13-17
if age <= 6:
age = 1
#18-24
elif age <= 31:
age = 2
#25-34
elif age <= 63:
age = 3
#35-44
elif age <= 78:
age = 4
#45-54
elif age <= 88:
age = 5
#55-64
elif age <= 94:
age = 6
#65+
else:
age = 7
if age == 1:
messages = randint(50, 150)
elif age == 2:
messages = randint(25,100)
elif age == 3:
messages = randint(15, 75)
elif age == 4:
messages = randint(75, 140)
elif age == 5:
messages = randint(50, 75)
elif age == 6:
messages = randint(5, 15)
elif age == 7:
messages = randint(30, 80)
for y in range(messages):
print("Message " + str(y) + " Sent from User " + str(x))
if delay > 0:
sleep(delay)
totalMessages += 1
#the way the for loop above works, it will send more messages even after we hit the totalMessage cap
if totalMessages >= numMessages:
break
#same idea as the other break, gets us to the while loop so we can stop, else it'll print out users-1 more messages
if totalMessages >= numMessages:
break
else:
for x in range(1000000):
age = randint(1, 100)
#13-17
if age <= 6:
age = 1
#18-24
elif age <= 31:
age = 2
#25-34
elif age <= 63:
age = 3
#35-44
elif age <= 78:
age = 4
#45-54
elif age <= 88:
age = 5
#55-64
elif age <= 94:
age = 6
#65+
else:
age = 7
if age == 1:
messages = randint(50, 150)
elif age == 2:
messages = randint(25,100)
elif age == 3:
messages = randint(15, 75)
elif age == 4:
messages = randint(75, 140)
elif age == 5:
messages = randint(50, 75)
elif age == 6:
messages = randint(5, 15)
elif age == 7:
messages = randint(30, 80)
for y in range(messages):
print("Message " + str(y) + " Sent from User " + str(x))
if delay > 0:
sleep(delay)
else:
print("Invalid choice (G or P, silly)")
#Final printout of the total time it took
endTime = time() - startTime
print("Total time spent sending messages: " + str(int(endTime / 60)) + " minutes and " + str(endTime % 60) + " seconds")
|
3c83b4ba12d8be6c8826f0f9f59922e2d2faa6ed | akhlaque-ak/pfun | /reference files/Reference Files/Lab 4/Exercise_4_2/Exercise_4_2.pyde | 508 | 4.125 | 4 | '''Exercise 4.2 Look up the pushMatrix() and popMatrix() function and understand their working.
Create a program and define a function named rec() which draws a series of 5 rectangles 100 units
high and 150 units wide whenever the mouse is pressed. hint: Use loops and transformations.
'''
def setup():
size(500, 500)
def draw():
if mousePressed:
for i in range(0, 5):
translate(20, 10)
fill(mouseX, mouseY, i)
rect(mouseX, mouseY, 100, 150) |
8180105bf40950d5d62f12e20b20636563760116 | python-yc/pycharm_script | /流畅的python/第1~2章节 序幕和数据结构/双向队列.py | 1,416 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
collections.deque类(双向队列)是一个线程安全、可以快速从两端添加或者删除元素的数据类型。
而且如果想要有一种数据类型来存放“最近用到的几个元素”,deque也是一个很好的选择。这是因为在
新建一个双向队列的时候,你可以指定这个队列的大小,如果这个队列满员了,还可以从反向端删除过
期的元素,然后在尾端添加新的元素
"""
from collections import deque
# maxlen是一个可选参数,代表这个队列可以容纳的元素的数量,一旦设定,这个属性就不能修改
dq = deque(range(10), maxlen=10)
print(dq)
# 队列的旋转操作接受一个参数n,当n>0时,队列的最右边的n个元素会被移动到队列的左边。
# 当n<0时,最左边的n个元素会被移动到右边
dq.rotate(3)
print(dq)
dq.rotate(-4)
print(dq)
# 当试图对一个已满(len(d)==d.maxlen)的队列做尾部添加操作的时候,它头部的元素会被删除掉。注意在下一行里,元素0被删除了
dq.appendleft(-1)
# dq.append(66)
print(dq)
# 在尾部添加3个元素的操作会挤掉-1、1和2
dq.extend([11, 22, 33])
print(dq)
# extendleft(iter)方法会把迭代器里的元素逐个添加到双向队列的左边,因此迭代器里的元素会逆序出现在队列里
dq.extendleft([10, 20, 30, 40])
print(dq)
print(dq[0])
|
789c7521b3406e5c4e05e2fb902c1e5168166034 | Siriapps/hackerrankPython | /strictSuperset.py | 377 | 3.65625 | 4 | # https://www.hackerrank.com/challenges/py-check-strict-superset/problem
bools = list()
setA = set(map(int, input().split()))
for _ in range(int(input())):
setN = set(map(int, input().split()))
bools.append(setA.issuperset(setN))
# loop for checking superset without using built-in function
# for i in setN:
# bools.append(i in setA)
print(all(bools))
|
5aef115e57520ca9ab2cf4911b8cf8d49efd5b40 | csjzhou/py-codes | /lists-stack.py | 350 | 4.125 | 4 | # Tutorial: http://www.idiotinside.com/2015/03/01/python-lists-as-fifo-lifo-queues-using-deque-collections
stack = ["a", "b", "c"]
# add an element to the end of the list
stack.append("e")
stack.append("f")
print stack
# pop operation
stack.pop()
print stack
# pop operation
stack.pop()
print stack
# push operation
stack.append("d")
print stack |
2232a3a688d1f57df8036a304543c16c884d72b6 | krl97/cool-compiler-2020 | /src/code_generation/variables.py | 1,073 | 3.6875 | 4 | class Variables:
def __init__(self):
self.stack = {}
self.vars = []
def add_var(self, name):
self.stack[name] = len(self.stack) + 1
self.vars.append(name)
def id(self, name):
if not name in self.stack:
self.add_var(name)
return int(len(self.stack) - self.stack[name] + 1)
def pop_var(self):
if not len(self.vars):
self.stack.pop(self.vars[-1])
self.vars.pop()
def add_temp(self):
name = len(self.stack) + 1
self.add_var(str(name))
return str(name)
def peek_last(self):
# print(self.vars)
return int(self.vars[-1])
def get_stack(self):
stack = '|'
for v in self.stack:
stack += 'id: ' + str(self.id(v) ) + 'name :' + v + '|'
return stack
def get_copy(self):
vars_copy = Variables()
vars_copy.stack = self.stack.copy()
vars_copy.vars = self.vars.copy()
# print('get copy')
# print(vars_copy.vars)
return vars_copy
|
b68e6863f0920a84eefa13e0cf8f5ec0b67dc668 | LastGunslinger/project_euler | /project_euler/problems/problem_019.py | 1,789 | 3.9375 | 4 | prompt = '''
You are given the following information, but you may prefer to do some research for yourself.
1 Jan 1900 was a Monday.
Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
'''
async def solve(logger):
logger.debug(prompt)
months = {
'01-January': 31,
'02-February': 28,
'03-March': 31,
'04-April': 30,
'05-May': 31,
'06-June': 30,
'07-July': 31,
'08-August': 31,
'09-September': 30,
'10-October': 31,
'11-November': 30,
'12-December': 31
}
days = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
]
first_sundays = 0
current_day = 2 # epoch day is a Monday
for year in range(1901, 2001):
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
months['02-February'] = 29
logger.debug(f'LEAP YEAR - {year}')
else:
months['02-February'] = 28
for month, days_in_month in sorted(months.items()):
for day in range(1, days_in_month + 1):
if days[current_day] == 'Sunday' and day == 1: # This is a Sunday
first_sundays += 1
logger.debug(f'Sunday, {month[3:]} {day}, {year}')
current_day = (current_day + 1) % len(days)
return first_sundays
|
d4b5c9d861caf2e7ce4002093b0ec62c4c34b987 | altonelli/interview-cake | /problems/python/second_largest_node.py | 576 | 3.984375 | 4 | from binary_tree_node import BinaryTreeNode
def find_second_largest_node(root):
if not root.left or not root.right:
return root.value
current_largest = root
second_largest = None
while current_largest.right:
second_largest = current_largest
current_largest = current_largest.right
if current_largest.left:
second_largest = current_largest.left
while second_largest.right:
second_largest = second_largest.right
return second_largest.value
def main():
pass
if __name__ == '__main__':
main()
|
8b8977d8d74a70f272c0139fcec6b08a0deb8692 | hebe3456/algorithm010 | /Week01/21.合并两个有序链表.py | 2,587 | 3.75 | 4 | #
# @lc app=leetcode.cn id=21 lang=python3
#
# [21] 合并两个有序链表
#
# @lc code=start
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
# iteratively 迭代
# recursively 递归
# time: O(m+n) 其中 m 和 m 分别为两个链表的长度。
# 因为每次循环迭代中,l1 和 l2 只有一个元素会被放进合并链表中,
# 因此 while 循环的次数不会超过两个链表的长度之和。
# 所有其他操作的时间复杂度都是常数级别的
# space:O(1) 只需要常数的空间存放若干变量
# 定义一个dummy
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = cur = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
# 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可
cur.next = l1 or l2
# cur.next = l1 if l1 is not None else l2
# cur is the last node,so must use dummy
return dummy.next
# recursively 递归
# time: O(m+n) 其中 m 和 m 分别为两个链表的长度。
# 因为每次调用递归都会去掉 l1 或者 l2 的头节点(直到至少有一个链表为空),
# 函数 mergeTwoList 至多只会递归调用每个节点一次。
# 因此,时间复杂度取决于合并后的链表长度
# space: O(m+n) 其中 m 和 m 分别为两个链表的长度。
# 递归调用 mergeTwoLists 函数时需要消耗栈空间,
# 栈空间的大小取决于递归调用的深度。
# 结束递归调用时 mergeTwoLists 函数最多调用 n+mn+m 次。
# 1130ms,40ms。。??
# def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# # if one is empty, return the non-empty one
# if not l1 or not l2:
# return l1 or l2
# # find the smaller one
# if l1.val < l2.val:
# l1.next = self.mergeTwoLists(l1.next, l2)
# return l1
# else:
# l2.next = self.mergeTwoLists(l1, l2.next)
# return l2
# s = Solution()
# l1 = ListNode(1)
# l1.next = ListNode(2)
# l1.next.next = ListNode(4)
# l2 = ListNode(1)
# l2.next = ListNode(3)
# l2.next.next = ListNode(4)
# print(s.mergeTwoLists(l1, l2))
# @lc code=end
|
3e55d65181ca9b5f1dfcf8706477d10e5f97fb2a | jaelzela/cracking_code | /running_median.py | 527 | 3.609375 | 4 | #!/bin/python
import sys
def insertElement(a, e):
if len(a) == 0:
a.append(e)
i = 0
while i < len(a):
if e < a[i]:
a.insert(i, e)
break
i += 1
n = int(raw_input().strip())
a = []
a_i = 0
for a_i in xrange(n):
a_t = int(raw_input().strip())
#insertElement(a, a_t)
a.append(a_t)
a.sort()
if len(a) % 2 == 0:
median = round(float(a[(len(a)/2)-1] + a[len(a)/2])/2, 1)
else:
median = round(float(a[len(a)/2]), 1)
print median |
4de10ea6b8cd6c2b471efd95734436a95622862f | mjavorka/adventofcode | /day20/day20.py | 2,082 | 3.609375 | 4 | # !/usr/bin/python3
"""
http://adventofcode.com/2017/day/20
author: Martin Javorka
"""
class Day20:
def __init__(self):
data = [line.rstrip().split(', ') for line in open("input", 'r')]
self.particles = []
for row in data:
position = list(map(int, row[0].strip('p=<>').split(',')))
velocity = list(map(int, row[1].strip('v=<>').split(',')))
acceleration = list(map(int, row[2].strip('a=<>').split(',')))
self.particles.append([position, velocity, acceleration])
positions = [x for x in range(len(self.particles))]
for i in range(2000):
for x, particle in enumerate(self.particles):
particle[1][0] += particle[2][0] # Increase the X velocity by the X acceleration.
particle[1][1] += particle[2][1] # Increase the Y velocity by the Y acceleration.
particle[1][2] += particle[2][2] # Increase the Z velocity by the Z acceleration.
particle[0][0] += particle[1][0] # Increase the X position by the X velocity.
particle[0][1] += particle[1][1] # Increase the Y position by the Y velocity.
particle[0][2] += particle[1][2] # Increase the Z position by the Z velocity.
# distance = abs(particle[0][0]) + abs(particle[0][1]) + abs(particle[0][2])
positions[x] = particle[0]
duplicates = self.get_duplicates(positions)
positions = self.remove_duplicates(positions, duplicates)
# print(distances.index(min(distances)))
print(len(self.particles))
@staticmethod
def get_duplicates(list_):
new = list()
for item in list_:
if list_.count(item) > 1 and item not in new:
new.append(item)
return new
def remove_duplicates(self, list_, duplicates):
for dupl in duplicates:
while dupl in list_:
idx = list_.index(dupl)
list_.pop(idx)
self.particles.pop(idx)
return list_
Day20()
|
1888900e9495baae1638fac60d597fdb8ffa1691 | instnadia/python-03-20 | /Week_1/Day_2/questions.py | 1,188 | 4.375 | 4 |
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
# def iteratedDictionary(some_list):
# for i in range(len(some_list)):
# for key in some_list[i]:
# print(key, '-', some_list[i][key])
# iteratedDictionary()
def id(arr):
for i in range(len(arr)):
print(f"first name: {arr[i]['first_name']}, last name: {arr[i]['last_name']}")
id(students)
# Reverse List - Create a function that takes a list and return that list with values reversed. Do this without creating a second list. (This challenge is known to appear during basic technical interviews.)
# Example: reverse_list([37,2,1,-9]) should return [-9,1,2,37]
def reverse_list(arr):
test = 0
for i in range(int(len(arr)/2)):
# while test < len(arr)/2:
last = arr[len(arr)-1-test]
arr[len(arr)-1-test] = arr[test]
arr[test] = last
test+=1
return arr
print(reverse_list([37,2,1,-9]))
balance = 100
print("balance is ${}".format(balance))
|
34b5671c27432ad4ec879e7f45708e1646e58f53 | Lohit9/python_algorithms | /legacy/linked_list/rerverse_llist.py | 343 | 4 | 4 | # //Reverse a linked list
// 2 --> 4 --> 5 --> 6
def revllist(node):
if not node: return None
elemList = []
while(node.next not None):
elemList.append(node)
node = node.next
node = None
for each in elemList.reverse():
node = each
node.next = None
node = node.next
return node
|
876302556703c060fe3240dd6535f43c97e8da45 | fdanmon/times | /countdown.py | 731 | 3.859375 | 4 | #! /usr/bin/env python3
import time
from datetime import datetime
import helpers
print("Time data must be in 24 hrs format!")
end = input("Type ending time (hh:mm:ss dd-mm-yyyy) -> ").strip()
if helpers.is_datetime(end):
try:
end_dt = helpers.to_datetime(end)
now = datetime.now().strftime('%H:%M:%S %d-%m-%Y')
now = helpers.to_datetime(now)
try:
while now <= end_dt:
lacks = datetime.now().strftime('%H:%M:%S %d-%m-%Y')
lacks = helpers.to_datetime(lacks)
print(end_dt - lacks)
time.sleep(1)
except KeyboardInterrupt:
print("Bye!")
except ValueError:
print("Date is not correct.")
|
48c233e978584f023495009d0e271c9117365b60 | chetnachauhan12/hacktoberfest2021-2 | /Python program/stack.py | 718 | 3.953125 | 4 | st=[]
c='y'
while c=='y':
print("(1) Enter Employee details")
print("(2) Delete Employee details")
print("(3) Display Employee details")
ch=int(input("Enter function choice: "))
if (ch==1):
a=int(input("Enter employee_id : "))
b=input("Ener employee_name: ")
j=[]
j.append(a)
j.append(b)
st.append(j)
elif (ch==2):
if st==[]:
print("Record not found")
else:
print("Deleted eployee details are",st.pop())
elif (ch==3):
for i in range(len(st)-1,-1,-1):
print(st[i])
else:
print("Input not in menu.")
k=input("Continue? (y/n) ")
if (k=='n'):
break
|
fc607fe1de128e6cd8b622d650fb6ca8edd37e2e | mehularora8/Probability-simulators | /hundreds_game.py | 976 | 3.765625 | 4 | """
Problem: Two players play a game. The game starts with S = 0
Player 1 draws random numbers and adds it to S till S > 100, at which point
Player 1 notes their last number.
Player 2 continues to add numbers to S till S > 200, at which point Player
2 notes their last number.
Player 2 wins if lastNum(Player 2) > lastNum(Player 1)
Find P(Player 2 wins)
"""
def q14(seed: int = 37, ntrials: int = 100000) -> float:
np.random.seed(seed)
trails_completed = 0
p2_wins = 0
while trails_completed < ntrials:
P1 = 0
p1_last_num = 0
p2_last_num = 0
while not P1 > 100:
rand_num = np.random.randint(1, 101)
P1 += rand_num
p1_last_num = rand_num
# While P2 is still playing
while not P1 > 200:
rand_num = np.random.randint(1, 101)
P1 += rand_num
p2_last_num = rand_num
# Condition for player 2 winning
if p2_last_num > p1_last_num:
p2_wins += 1
trails_completed += 1
return p2_wins / ntrials
print(q14()) # Optional parameters |
9c00fc746ac4f768f9dedc2d44a3fe46deafa331 | amy58328/python | /pandas/hello pandas.py | 795 | 3.796875 | 4 | import pandas as pd
# 準備傳入 DataFrame 的資料
data_1 = {
'name': ['王小郭', '張小華', '廖丁丁', '丁小光'],
'email': ['min@gmail.com', 'hchang@gmail.com', 'laioding@gmail.com', 'hsulight@gmail.com'],
'grades': [60, 77, 92, 43]
}
data_2 = {
'name': ['王小郭', '張小華', '廖丁丁', '丁小光'],
'age': [19, 20, 32, 43]
}
# 建立 DataFrame 物件
student_df_1 = pd.DataFrame(data_1)
student_df_2 = pd.DataFrame(data_2)
print(student_df_1,end="\n=============\n\n")
print(student_df_2,end="\n=============\n\n")
student_fg_3 = pd.merge(student_df_1, student_df_2)
# merge結果
print(student_fg_3,end="\n=============\n\n")
# 輸出特定行列值
print(student_fg_3.loc[:,["name","age"]],end="\n=============\n\n")
print(student_fg_3.iloc[:,[0,2]],end="\n=============\n\n") |
9401d384a2d8d88129d3ffcc91590a0679d1081f | RembertoNunez/Parking-Spot-Detector | /mockLight/.~c9_invoke_cZFUyo.py | 3,264 | 3.5 | 4 | #Author: Daniel Ochoa
#last Modified: 04-19-17
#Description: This file connects the project together. Its main purpose is to read the scores and deside if the parking spot is open or not.
#futher improvements: 1. Connect the results of this file into the notification services.
#2. make the system calls into a function
from cropImage import cropImage #this file takes a picture of an image
#and crops it to 16 different images.
import time
import cv2
import os
import numpy as np
from PIL import Image
from textMessage import sendMessage
#from image import blackAndWhite
def textPerson():
#labels of the parking spots
labels = ['a1','a2','a3','a4','a5','a6','b1','b2','b3','b4','b5','b6']
version = 1 #this variable is used to cycle through the different picutes of the parking spot. This far there is only 10 pictures
stop = 2
while(version != stop):
#gets the file path
imgFilePath = "car/car" + str(version) + ".jpg"
#inputs the file path and the functions outputs the images of each parking spot.
cropImage(imgFilePath)
version = version + 1
#this is not needed it's just nice to see what picture it is currently processing
im = Image.open(imgFilePath)
im.show()
#**************************************************************
#this opens up the text file the scores are entered.
#opening and closing it with the write mode erases everything in the file. I do this to get rid of previous scores
file = open("parkingScores.txt","w")
file.close()
#I used system calls because it was the only way my processor would handel the amount of information.
#label_image.py runs with an image and then writes the score of that spot into parkingScores.txt
os.system("python label_image.py a1.jpg")
os.system("python label_image.py a2.jpg")
os.system("python label_image.py a3.jpg")
os.system("python label_image.py a4.jpg")
os.system("python label_image.py a5.jpg")
os.system("python label_image.py a6.jpg")
os.system("python label_image.py b1.jpg")
os.system("python label_image.py b2.jpg")
os.system("python label_image.py b3.jpg")
os.system("python label_image.py b4.jpg")
os.system("python label_image.py b5.jpg")
os.system("python label_image.py b6.jpg")
#os.system("python label_image.py c1.jpg")
#os.system("python label_image.py c2.jpg")
#os.system("python label_image.py c3.jpg")
#os.system("python label_image.py c4.jpg")
#****************************************************************
#Reads the data from parkingScores.txt and puts it into an array.
file = open("parkingScores.txt","r")
score = file.readlines()
print (score)
parking_avilable = ""
for i in range(12):
temp = score[i]
#here I decide if the parking spot is avilable or not the lowest score I accept is a 60%
if(temp[:3] == '0.8' or temp[:3] == '0.9' or temp[:3] == '0.7' or temp[:3] == '0.6' or temp[:3] == '0.5'):
score[i] = 0
print (labels[i] + " is open")
parking_avilable = parking_avilable + labels[i] + " "
else:
score[i] = 1
print (labels[i] + " is taken")
if(version > 14):
version = version + 1
print (score)
print (parking_avilable)
sendMessage(parking_avilable)
parking_avilable = ""
stop = stop + 1
|
717ce73fca2bd28ca5f31309f0f3c2f11c79cdfa | jdiodati20/hangman | /Book/chap4.py | 461 | 3.84375 | 4 | def square (var):
"""
returns var squared.
:parameter var: int.
"""
return(var ** 2)
print(square(5))
def printing (string):
print(string)
printing("hello")
def optional (str0, str1, str2, str3 = 2, str4 = 1):
print("nice")
print(str3)
print(str4)
optional(0, 1, 2, 10)
def division2 (integer):
return integer / 2
result = division2(31)
def multiply4 (integer):
return integer * 4
print(multiply4(result))
|
e26b023954e2f6329062d8d36203afb4b0dd7f58 | mayurshetty/Python-Assignment-from-HighSchool | /Lab4.01-de_vowel/Lab 4.01-de_vowel.py | 571 | 4.125 | 4 | vowel_list = ["a","e","i","o","u","A","E","I","O","U"]
def de_vowel(a_string):
global vowel_list
de_vowel_string = []
for list_letter in a_string:
if list_letter not in vowel_list:
de_vowel_string.append(list_letter)
return("".join(de_vowel_string))
def count_vowels(a_string):
global vowel_list
vowel_letter_num = 0
for list_letter in a_string:
if list_letter in vowel_list:
vowel_letter_num += 1
print(vowel_letter_num)
no_vowels = de_vowel("This sentence has no vowels")
count_vowels("This sentence has no vowels")
print(no_vowels)
|
83d71778cb0ad3383239338bd6bdc9029c9e509e | PrakashChanchal1998/pyathonproject | /gu.py | 187 | 3.859375 | 4 | for n in range(1,3):
from random import randint
d=randint(1,20)
print(d)
if d<15:
print("try again")
elif d==15:
print("you score it")
break
elif d>15:
print("try again")
|
d94b368c1851021f0005ed0e8df3677182b8589f | kriti-ixix/ml-130 | /python/reverse star pattern.py | 237 | 4.09375 | 4 | # for row in range(5, 0, -1):
# for col in range(1, row+1):
# print("* ", end='')
# print("")
stars = 5
for row in range(1, 6):
for col in range(1, stars+1):
print("* ", end='')
print("")
stars -= 1
|
3fa5566438d0c0649bdc357c225d6bd800d7369e | fortelg/python | /eje38.py | 502 | 3.90625 | 4 | #!/usr/bin/python
#!encoding: UTF-8
print "Introduzca el valor para n:"
n = int (raw_input())
print "Introduzca el valor para m:"
m = int (raw_input())
numeros = []
for i in range(n, m+1):
numeros.append(i)
print "Los numeros almacenados son:"
for i in range(m-n+1):
print numeros[i]
suma = 0
for i in range(m-n+1):
suma += numeros[i]
print "La suma de los numeros es", suma
#Otra forma de hacerlo
suma = 0
for i in range(n, m+1):
suma += i
print "La suma de los numeros es", suma
print "\n"
|
c3e92c963e4f5a27b60e66f1e151063590474d1f | Adit-COCO-Garg/rit-cscI141-recitation | /Replace.py | 492 | 3.96875 | 4 | # Tigran Hakobyan
# week4 recitation class
#strReplace(’test’, ’t’, ’x’) => 'xesx'
# replace x with y in st.
def strReplace(st, x, y):
if len(st) < 1:
return st
else:
if st[0] == x:
return y + strReplace(st[1:],x,y)
else:
return st[0] + strReplace(st[1:],x,y)
def strReplaceIter(st, x, y):
result = ""
for i in range(len(st)):
if st[i] == x:
result += y
else:
result += st[i]
return result
def main():
print(strReplaceIter('test', 't', 'x'))
main() |
19dcd36a4698fc21ff17961ef99a5084b26c2512 | signalwolf/Leetcode_by_type | /MS Leetcode喜提/店面准备MS/面经/微软电面2.py | 271 | 3.796875 | 4 | # coding=utf-8
# 给俩没sorted 的array, 每个array和俩array之间都有可能出现重复数字。要求merge这俩array 做到sort 和去重
def merge(A1, A2):
return sorted(list(set(A1).union(set(A2))))
print merge([1,23,4423,55,1,2], [1,3,4,6,7,8,12,3,6]) |
0068f095d2d14896c11bab46707b264ace0f1dd6 | srishilesh/Data-Structure-and-Algorithms | /HackerRank/Practice/candies.py | 6,921 | 4.25 | 4 | # https://www.hackerrank.com/challenges/candies/problem
'''
Alice is a kindergarten teacher. She wants to give some candies to the children in her class. All the children sit in a line and each of them has a rating score according to his or her performance in the class. Alice wants to give at least 1 candy to each child. If two children sit next to each other, then the one with the higher rating must get more candies. Alice wants to minimize the total number of candies she must buy.
For example, assume her students' ratings are [4, 6, 4, 5, 6, 2]. She gives the students candy in the following minimal amounts: [1, 2, 1, 2, 3, 1]. She must buy a minimum of 10 candies.
Function Description
Complete the candies function in the editor below. It must return the minimum number of candies Alice must buy.
candies has the following parameter(s):
n: an integer, the number of children in the class
arr: an array of integers representing the ratings of each student
Input Format
The first line contains an integer, , the size of .
Each of the next lines contains an integer indicating the rating of the student at position .
Constraints
Output Format
Output a single line containing the minimum number of candies Alice must buy.
Sample Input 0
3
1
2
2
Sample Output 0
4
Explanation 0
Here 1, 2, 2 is the rating. Note that when two children have equal rating, they are allowed to have different number of candies. Hence optimal distribution will be 1, 2, 1.
Sample Input 1
10
2
4
2
6
1
7
8
9
2
1
Sample Output 1
19
Explanation 1
Optimal distribution will be
Sample Input 2
8
2
4
3
5
2
6
4
5
Sample Output 2
12
Explanation 2
Optimal distribution will be .
'''
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the candies function below.
def candies(n, arr):
arr = [10**9] + arr + [10**9]
fin = [0]*(n+1)
for i in range(1,n+1):
if arr[i-1]>=arr[i]<=arr[i+1]:
fin[i] = 1
for i in range(1,n+1):
if arr[i-1]<arr[i]<=arr[i+1]:
fin[i] = fin[i-1]+1
for i in range(n,0,-1):
if arr[i-1]>=arr[i]>arr[i+1]:
fin[i] = fin[i+1]+1
for i in range(1,n+1):
if arr[i-1]<arr[i]>arr[i+1]:
fin[i] = max(fin[i-1],fin[i+1])+1
print(sum(fin))
return sum(fin)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
arr = []
for _ in range(n):
arr_item = int(input())
arr.append(arr_item)
result = candies(n, arr)
fptr.write(str(result) + '\n')
fptr.close()
'''
This problem can be solved with a greedy technique.
We denote by the number of candies given to the child.
Let's classify the children into four kinds, depending on the comparisons of their ratings with their neighbors.
If , we say Child is a valley.
If , we say Child is a rise.
If , we say Child is a fall.
If , we say Child is a peak.
For the leftmost and rightmost child, assume they each have a neighbor with an infinite rating, so they can also be classified according to this scheme. (In particular, the leftmost child cannot be a rise or a peak, and the rightmost child cannot be a fall or a peak.)
Given this classification, we can intuitively distribute the candies this way:
For each valley child, give him/her candy.
For each rise child, give him/her candies.
For each fall child, give him/her candies.
For each peak child, give him/her candies.
Observe that this gives a valid distribution of candies. But does it give the minimum total number of candies?
Amazingly, it does! But only as long as you distribute the candies in the right order. Here's one good order:
Distribute the candies to the valleys.
Distribute the candies to the rises from left to right.
Distribute the candies to the falls from right to left.
Distribute the candies to the peaks.
Note that the order in which we distribute candies to rises and falls is pretty important!
Here's a Python implementation:
INF = 10**9 # a number larger than all ratings
n = input()
a = [input() for i in xrange(n)]
# add sentinels
a = [INF] + a + [INF]
candies = [0]*(n+1)
# populate 'valleys'
for i in xrange(1,n+1):
if a[i-1] >= a[i] <= a[i+1]:
candies[i] = 1
# populate 'rises'
for i in xrange(1,n+1):
if a[i-1] < a[i] <= a[i+1]:
candies[i] = candies[i-1] + 1
# populate 'falls'
for i in xrange(n,0,-1):
if a[i-1] >= a[i] > a[i+1]:
candies[i] = candies[i+1] + 1
# populate 'peaks'
for i in xrange(1,n+1):
if a[i-1] < a[i] > a[i+1]:
candies[i] = max(candies[i-1], candies[i+1]) + 1
# print the total number of candies
print sum(candies)
Of course, we need to prove why this assignment works. We will prove two things:
It gives a valid distribution of candies.
It gives a the distribution with the minimum sum.
Is it valid?
The first thing to notice is that: All children are assigned a positive number of candies. We just have to show that for every two neighbors with different ratings, the one with the higher rating is given more candies.
Consider two neighboring children and with different ratings. There are two cases:
Case 1: .
In this case, the only possible cases are:
Child is a valley and Child is a peak.
Child is a valley and Child is a rise.
Child is a rise and Child is a peak.
Child is a rise and Child is a rise.
In the first three cases, we can see that Child is given candies earlier than Child (due to the order we're giving out candies), and indeed, we see that . But actually, the same holds as well in the last case, since we're giving candies to rises from left to right.
Case 2: .
This is similar. In this case, the only possible cases are:
Child is a peak and Child is a valley.
Child is a fall and Child is a valley.
Child is a peak and Child is a fall.
Child is a fall and Child is a fall.
In the first three cases, we can see that Child is given candies earlier than Child , and indeed, we see that . But actually, the same holds as well in the last case, since we're giving candies to falls from right to left.
This shows that the candy distribution is valid for every pair of neighbors, hence the overall distribution is valid as well!
Is it the minimum?
Proving that this gives the minimum total candies is a little easier. We just have to notice that these inequalities hold:
For each valley child , .
For each rise child , .
For each fall child , .
For each peak child , .
This easily follows from the constraints of the problem. Since the algorithm above satisfies each inequality in the tightest possible way, this means the overall number of candies is minimized.
The time complexity is , which is optimal.
Note that there are many other solutions as well, some requiring more advanced techniques, and some requiring even fewer passes through the array. This editorial just describes one.
'''
|
2aa894799300cbffa2081730e2902d5d2e37a80a | shurawz/BasicPython | /Comprehension/listcomp.py | 451 | 4.375 | 4 | numbers = [1, 2, 3, 4, 5, 6]
number = int(input("Please enter a number. I'll tell you its square value: "))
squares = [number ** 2 for number in numbers] # Using Comprehension which is list comprehension
# cubes = {number ** 3 for number in numbers} # Using Comprehension which is set comprehension
# 'number ** 2' is a expression
# 'for number in numbers' is a iteration
indx = numbers.index(number)
print(squares[indx])
# print(sorted(cubes))
|
d22b68f91776b53c37f232e5c6790e551b3d21f7 | J-TKim/Effective_Python_2nd | /Ch3/Better_way20.py | 1,902 | 3.65625 | 4 | # 0으로 수를 나누려는 경우 None을 반환하는 함수
def careful_divide(a, b):
try:
return a / b
except ZeroDivisionError:
return None
# 이함수를 사용하는 코드는 반환 값을 적절히 해석하면 된다.
x, y = 1, 0
result = careful_divide(x, y)
if result is None:
print('잘못된 입력')
# 피제수가 0인 경우 0이 return되어 잘못된 코드가 실행된다.
x, y = 0, 5
result = careful_divide(x, y)
if not result:
print('잘못된 입력')
# 위와 같은 실수를 줄이기 위한 방안들
# 방안1, 반환 값을 2튜플로 분리
def careful_divide(a, b):
try:
return True, a / b
except ZeroDivisionError:
return False, None # 첫 번째 부분은 연산이 성공인지 실패인지를 표시, 두 번째 부분은 계산에 성공한 경우 실제 결괏값을 저장
success, result = careful_divide(x, y)
if not success:
print('잘못된 입력')
# 아래와 같이 실수할 경우가 있음
_, result = careful_divide(x, y)
if not success:
print('잘못된 입력')
# 방안2, 결코 None을 반환하지 않는다.
def careful_divide(a, b):
try:
return a / b
except ZeroDivisionError as e:
raise ValueError('잘못된 입력')
# 방안2를 사용하면 반환 값에 대한 조건문을 사용하지 않아도 된다. 반환된 값을 else에서 이용하자
x, y = 5, 2
try:
result = careful_divide(x, y)
except ValueError:
print('잘못된 입력')
else:
print(f'결과는 {result:.1f} 입니다.')
# 타입 애너테이션을 사용하는 코드에 적용해보기
def careful_divide(a: float, b: float) -> float:
"""a를 b로 나눈다.
Raises:
ValueError: b가 0이어서 나눗셈을 할 수 없을 때
"""
try:
return a/b
except ZeroDivisionError as e:
raise ValueError('잘못된 입력') |
ad2f2987898e888752369a1f058485c8cf258c64 | zofiagrodecka/ASD | /Grafy/malejace_krawedzie_najkrotsza.py | 1,966 | 3.53125 | 4 | def parent(i):
return i // 2
def left(i):
return i * 2
def right(i):
return 2 * i + 1
def empty(k):
if k[0] == 0:
return True
else:
return False
def heapify(k, i):
l = left(i)
r = right(i)
mini = i
size = k[0]
if l <= size and k[l][1] < k[mini][1]:
mini = l
if r <= size and k[r][1] < k[mini][1]:
mini = r
if mini != i:
k[i], k[mini] = k[mini], k[i]
heapify(k, mini)
def getmin(k):
res = k[1]
size = k[0]
k[1] = k[size]
k[0] -= 1
heapify(k, 1)
return res
def insert(k, x):
k[0] += 1
size = k[0]
k[size] = x
i = size
while i > 1 and k[i][1] < k[parent(i)][1]:
k[i], k[parent(i)] = k[parent(i)], k[i]
i = parent(i)
inf = 100000
def dijkstra(G, s):
n = len(G)
global inf
dist = [inf] * n
visited = [False] * n
parent = [None] * n
Queue = [0] * 50
dist[s] = 0
insert(Queue, (s, 0, 0)) # wstawiam: (numer wierzcholka, odleglosc dojscia, min waga krawedzi by tu dojsc)
while not empty(Queue):
u, cost, mini = getmin(Queue)
if not visited[u]:
visited[u] = True
for v in range(n):
if (G[u][v] > mini and dist[v] > dist[u] + G[u][v]) or (dist[v] < dist[u] + G[u][v] and G[u][v] < mini):
dist[v] = dist[u] + G[u][v]
parent[v] = u
if G[u][v] < mini:
mini = G[u][v]
insert(Queue, (v, dist[v], mini))
return dist, parent
def decreasing_edges(G, x, y):
dist, parent = dijkstra(G, y)
return dist[x]
G = [[ 0 for i in range(8)] for j in range(8)]
G[0][1] = 6
G[1][0] = 6
G[1][2] = 5
G[2][1] = 5
G[2][5] = 2
G[5][2] = 2
G[5][7] = 1
G[7][5] = 1
G[0][3] = 6
G[3][0] = 6
G[3][4] = 3
G[4][3] = 3
G[4][2] = 2
G[2][4] = 2
G[2][6] = 1
G[6][2] = 1
G[6][7] = 5
G[7][6] = 5
print(decreasing_edges(G, 0, 7)) |
6ac853fe84ea0e3c21d877cbd9488262388ea9be | Hairidin-99/quiz | /quiz2.py | 2,772 | 3.609375 | 4 | print "welcome in our game"
random import
chislo1 = int(input("vyberite chislo ot 0 do 6"))
comp = random.randint(1,6)
if chislo > 6:
print "vyberite chislo ot 1 do 6"
elif comp < 0:
print "vyberite chislo ot 1 do 6"
elif comp == chiclo1:
x = kh - chislo1
ball = 6
print "Tvoi kolichetvo ballov:"
print ball
elif comp > chislo1:
x = comp - chislo1
if x == 1 :
ball = ball + 5
print "Tvoi kolichetvo ballov:"
print ball
elif x == 2 :
ball = ball + 4
print "Tvoi kolichetvo ballov:"
print ball
elif x == 3 :
ball = ball + 3
print "Tvoi kolichetvo ballov:"
print ball
elif x == 4 :
ball = ball + 2
print "Tvoi kolichetvo ballov:"
elif x == 5 :
ball = ball + 1
print "Tvoi kolichetvo ballov:"
print ball
elif comp < chislo2 :
x = comp - chislo1
if x == 1 :
ball = ball + 5
print "Tvoi kolichetvo ballov:"
print ball
elif x == 2 :
ball = ball + 4
print "Tvoi kolichetvo ballov:"
print ball
elif x == 3 :
ball = ball + 3
print "Tvoi kolichetvo ballov:"
print ball
elif x == 4 :
ball = ball + 2
print "Tvoi kolichetvo ballov:"
elif x == 5 :
ball = ball + 1
print "Tvoi kolichetvo ballov:"
print ball
elif comp > chislo3:
x = comp - chislo1
if x == 1 :
ball = ball + 5
print "Tvoi kolichetvo ballov:"
print ball
elif x == 2 :
ball = ball + 4
print "Tvoi kolichetvo ballov:"
print ball
elif x == 3 :
ball = ball + 3
print "Tvoi kolichetvo ballov:"
print ball
elif x == 4 :
ball = ball + 2
print "Tvoi kolichetvo ballov:"
elif x == 5 :
ball = ball + 1
print "Tvoi kolichetvo ballov:"
print ball
elif comp > chislo4:
x = comp - chislo1
if x == 1 :
ball = ball + 5
print "Tvoi kolichetvo ballov:"
print ball
elif x == 2 :
ball = ball + 4
print "Tvoi kolichetvo ballov:"
print ball
elif x == 3 :
ball = ball + 3
print "Tvoi kolichetvo ballov:"
print ball
elif x == 4 :
ball = ball + 2
print "Tvoi kolichetvo ballov:"
elif x == 5 :
ball = ball + 1
print "Tvoi kolichetvo ballov:"
print ball
elif comp > chislo5:
x = comp - chislo1
if x == 1 :
ball = ball + 5
print "Tvoi kolichetvo ballov:"
print ball
elif x == 2 :
ball = ball + 4
print "Tvoi kolichetvo ballov:"
print ball
elif x == 3 :
ball = ball + 3
print "Tvoi kolichetvo ballov:"
print ball
elif x == 4 :
ball = ball + 2
print "Tvoi kolichetvo ballov:"
elif x == 5 :
ball = ball + 1
print "Tvoi kolichetvo ballov:"
print ball
|
d059326bf2e1b55306d08a5513ddde76530cfbf2 | geetanjalisawant16/GS_WINE | /Clustering.py | 12,684 | 3.53125 | 4 | # This code is to implement Clustering methods.
# Importing all Libraries
from sklearn.cluster import KMeans, AgglomerativeClustering, MeanShift, Birch # Our clustering algorithm
from sklearn.mixture import GaussianMixture # To implement GaussianMixture model clustering
from sklearn.decomposition import PCA # Needed for dimension reduction
from sklearn.datasets import load_wine # Dataset that I will be using
import matplotlib.pyplot as plt # Plotting
import pandas as pd # Storing data convenieniently
from sklearn.metrics import adjusted_rand_score, homogeneity_score, v_measure_score, completeness_score, \
adjusted_mutual_info_score, accuracy_score
from sklearn.model_selection import train_test_split, KFold, cross_val_score
from sklearn.preprocessing import StandardScaler # To preprocessing
import scipy.cluster.hierarchy as sch
from sklearn import metrics
# Loading wine dataset
wine = load_wine()
X = wine.data # assigning the features
Y = wine.target # assigning the target variable
# Split the data into training (70%) and testing (30%)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3, random_state=0)
print(X_train.shape)
print(X_test.shape)
labels_true = Y
# Code reference link for finding score in all clustering methods: https://ogrisel.github.io/scikit-learn.org/sklearn-tutorial/modules/clustering.html
# Code reference link for K-means with PCA: https://andrewmourcos.github.io/blog/2019/06/06/PCA.html
# Code reference link for showing iteration with k-means: https://sweetcode.io/k-means-clustering-python/
# Preprocessing data
df_wine = pd.DataFrame(wine.data, columns=wine.feature_names) # Creating dataframe
std_wine = StandardScaler().fit_transform(df_wine) # normalizing the data
# 1st Clustering Method (K-means)
print("\n1st Clustering Method: K-means")
print("---------------------------------------------------")
model_kmeans = KMeans(n_clusters=3)# Build the model
model_kmeans.fit(X)# Fit the model on the dataset
labels_kmeans = model_kmeans.labels_
print("Adjusted Random Score: ", adjusted_rand_score(labels_true, labels_kmeans))
print("Homogeneity Score: ", homogeneity_score(labels_true, labels_kmeans))
print("V-Measure Score: ", v_measure_score(labels_true, labels_kmeans))
print("Completeness: ", completeness_score(labels_true, labels_kmeans))
print("Adjusted Mutual Information: ", adjusted_mutual_info_score(labels_true, labels_kmeans))
plt.scatter(X[:,0],X[:,12], c=labels_kmeans, cmap='plasma')
plt.title('Kmeans Clustering for Wine Dataset', fontsize=20)
plt.xlabel('alchohol', fontsize=15)
plt.ylabel('proline', fontsize=15)
plt.show()
# Kmeans with Dimentionality Reduction using PCA
pca_wine = PCA(n_components=13)
principalComponents = pca_wine.fit_transform(std_wine)
PCA_components = pd.DataFrame(principalComponents) # Putting components in a dataframe for later
array_pca=[]
for i in range(1, 5):
model_kmeans_pca = KMeans(n_clusters = i, init = 'k-means++', max_iter = 1, n_init = 10, random_state = 5)
model_kmeans_pca.fit(PCA_components.iloc[:, :2])
labels = model_kmeans_pca.predict(PCA_components.iloc[:, :2])
centroids = model_kmeans_pca.cluster_centers_
array_pca.append(model_kmeans_pca.inertia_)
plt.scatter(PCA_components[0], PCA_components[1], c=labels)
plt.scatter(centroids[:, 0], centroids[:, 1], s=200, marker='*',color='r')
plt.title("Wine Dataset with " + str(i) + " Clusters", fontsize=20)
plt.show()
# Comparing 'alcohol' and 'od280/od315_of_diluted_wines' of wine dataset with Kmeans for showing iteration
df_wine.plot.scatter(x = 'alcohol', y = 'od280/od315_of_diluted_wines', figsize=(12,8), colormap='jet') # Plot scatter plot of proline and proline
plt.title('Wine Dataset with no Iteration performed', fontsize=26)
plt.show()
# 1st iteration
model_kmeans_iter = KMeans(n_clusters=3, init = 'random', max_iter = 300, random_state = 5).fit(df_wine.iloc[:,[11,0]])
centroids_df = pd.DataFrame(model_kmeans_iter.cluster_centers_, columns = list(df_wine.iloc[:,[11,0]].columns.values))
fig, ax = plt.subplots(1, 1)
df_wine.plot.scatter(x = 'alcohol', y = 'od280/od315_of_diluted_wines', c= model_kmeans_iter.labels_, figsize=(12,8), colormap='jet', ax=ax, mark_right=False)
centroids_df.plot.scatter(x = 'alcohol', y = 'od280/od315_of_diluted_wines', ax = ax, s = 200, marker='*', c='m', mark_right=False)
plt.title('1st Iteration performed on Wine Dataset', fontsize=26)
plt.show()
# 2nd iteration
model_kmeans_iter = KMeans(n_clusters=3, init = 'random', max_iter = 1, random_state = 5).fit(df_wine.iloc[:,[11,0]])
centroids_df = pd.DataFrame(model_kmeans_iter.cluster_centers_, columns = list(df_wine.iloc[:,[11,0]].columns.values))
fig, ax = plt.subplots(1, 1)
df_wine.plot.scatter(x = 'alcohol', y = 'od280/od315_of_diluted_wines', c= model_kmeans_iter.labels_, figsize=(12,8), colormap='jet', ax=ax, mark_right=False)
centroids_df.plot.scatter(x = 'alcohol', y = 'od280/od315_of_diluted_wines', ax = ax, s = 200, marker='*', c='m',mark_right=False)
plt.title('2nd Iteration performed on Wine Dataset', fontsize=26)
plt.show()
# Count accuracy after last iteration
X_train_iter, X_test_iter, Y_train_iter, Y_test_iter = train_test_split(df_wine.iloc[:,[11,0]], Y, test_size=0.3, random_state=0)
y_pred_iter = model_kmeans_iter.predict(X_test_iter)
model_kmeans_iter_acc = metrics.accuracy_score(Y_test_iter,y_pred_iter)
print('Accuracy after iteration performed: {0:f}'.format(model_kmeans_iter_acc))
# Code reference link for Hierarchical dendogram and agglomerative clustering: https://github.com/Ayantika22/Kmeans-and-HCA-clustering-Visualization-for-WINE-dataset/blob/master/Mtech_Wine_kmeans%20and%20HCA.py
# 2nd Clustering Method (Hierarchical Clustering & Agglomerative Hierarchical clustering)
# Plotting Hierarchical Dendrogram for Wine dataset
# Decide the number of clusters by using this dendrogram
model_hcl = sch.linkage(X, method = 'median')
plt.figure(figsize=(12,8))
den = sch.dendrogram(model_hcl)
plt.title('Dendrogram for the Clustering of the Wine Dataset', fontsize=26)
plt.xlabel('Type', fontsize=18)
plt.ylabel('Euclidean distance in the space with other variables', fontsize=18)
plt.show()
# Hierarchical Agglomerative Clustering
print("\n2nd Clustering Method: Hierarchical Agglomerative")
print("---------------------------------------------------")
model_agg = AgglomerativeClustering(n_clusters=3) # Build the Model
model_agg.fit(X) # Fit the model on the dataset
labels_agg = model_agg.labels_
print("Adjusted Random Score: ", adjusted_rand_score(labels_true, labels_agg))
print("Homogeneity Score: ", homogeneity_score(labels_true, labels_agg))
print("V-Measure Score: ", v_measure_score(labels_true, labels_agg))
print ("Completeness: ", completeness_score(labels_true, labels_agg))
print ("Adjusted Mutual Information: ", adjusted_mutual_info_score(labels_true, labels_agg))
plt.scatter(X[:,0],X[:,12], c=labels_agg, cmap='rainbow')
plt.title('Agglomerative Clustering for Wine Dataset', fontsize=20)
plt.xlabel('alchohol', fontsize=15)
plt.ylabel('proline', fontsize=15)
plt.show()
# Code reference link for GausianMixtureModel: https://jakevdp.github.io/PythonDataScienceHandbook/05.12-gaussian-mixtures.html
# 3rd Clustering Method (GausianMixtureModel Clustering)
print("\n3rd Clustering Method: GausianMixtureModel")
print("---------------------------------------------------")
model_gmm = GaussianMixture(n_components=2, covariance_type='full', random_state=0)# Build the model
model_gmm.fit(X)# Fit the model on the dataset
labels_gmm = model_gmm.predict(X)
print("Adjusted Random Score: ", adjusted_rand_score(labels_true, labels_gmm))
print("Homogeneity Score: ", homogeneity_score(labels_true, labels_gmm))
print("V-Measure Score: ", v_measure_score(labels_true, labels_gmm))
print("Completeness: ", completeness_score(labels_true, labels_gmm))
print("Adjusted Mutual Information: ", adjusted_mutual_info_score(labels_true, labels_gmm))
plt.scatter(X[:, 0], X[:, 12], c=labels_gmm)
plt.title('GausianMixtureModel for Wine Dataset', fontsize=20)
plt.xlabel('alchohol', fontsize=15)
plt.ylabel('proline', fontsize=15)
plt.show()
# Code reference link for MeanShift: https://www.geeksforgeeks.org/ml-mean-shift-clustering/
# 4th Clustering Method (MeanShift Clustering)
print("\n4th Clustering Method: MeanShift Clustering")
print("---------------------------------------------------")
model_ms = MeanShift()# Build the model
model_ms.fit(X)# Fit the model on the dataset
cluster_centers = model_ms.cluster_centers_
labels_ms = model_ms.labels_
print("Adjusted Random Score: ", adjusted_rand_score(labels_true, labels_ms))
print("Homogeneity Score: ", homogeneity_score(labels_true, labels_ms))
print("V-Measure Score: ", v_measure_score(labels_true, labels_ms))
print ("Completeness: ", completeness_score(labels_true, labels_ms))
print ("Adjusted Mutual Information: ", adjusted_mutual_info_score(labels_true, labels_ms))
plt.scatter(X[:,0], X[:,12],c=labels_ms, marker='o')
plt.scatter(cluster_centers[:,0], cluster_centers[:,12], marker='x', color='red', linewidth=2)
plt.title('MeanShift Clustering for Wine Dataset', fontsize=20)
plt.xlabel('alchohol', fontsize=15)
plt.ylabel('proline', fontsize=15)
plt.show()
# Code reference link for Birch Clustering: https://www.kaggle.com/ninjacoding/clustering-mall-customers#Birch
# 5th Clustering Method (Birch Clustering)
print("\n5th Clustering Method: Birch Clustering")
print("---------------------------------------------------")
model_birch=Birch(n_clusters=3)# Build the model
model_birch.fit(X)# Fit the model on the dataset
labels_birch = model_birch.labels_
print("Adjusted Random Score: ", adjusted_rand_score(labels_true, labels_birch))
print("Homogeneity Score: ", homogeneity_score(labels_true, labels_birch))
print("V-Measure Score: ", v_measure_score(labels_true, labels_birch))
print ("Completeness: ", completeness_score(labels_true, labels_birch))
print ("Adjusted Mutual Information: ", adjusted_mutual_info_score(labels_true, labels_birch))
plt.scatter(X[:,0],X[:,12],c=labels_birch,cmap='coolwarm')
plt.title('Birch Clustering for Wine Dataset', fontsize=20)
plt.xlabel('alchohol', fontsize=15)
plt.ylabel('proline', fontsize=15)
plt.show()
# Results of all the algorithms
clu_models = []
clu_models.append(("Kmeans Clustering: ", KMeans(n_clusters=1)))
clu_models.append(("Gaussian Mixture Model: ", GaussianMixture(n_components=2, covariance_type='full', random_state=0)))
clu_models.append(("MeanShift Clustering: ", MeanShift()))
clu_models.append(("Birch Clustering:",Birch(n_clusters=1)))
print('\nClustering models results are...')
results = []
names = []
for name, model in clu_models:
kfold = KFold(n_splits=10, random_state=0, shuffle=True)
cv_result_chang_para = cross_val_score(model,X,Y, cv = kfold, scoring = "accuracy")
names.append(name)
results.append(cv_result_chang_para)
for i in range(len(names)):
print(names[i],results[i].mean()*100)
model_agg = AgglomerativeClustering(n_clusters=1,linkage='complete')
model_agg.fit(X)
labels_agg = model_agg.labels_
print("Agglomerative Clustering: ", accuracy_score(labels_true, labels_agg).mean()*100)
# Configuration of the parameters
clf_models_chang_para = []
clf_models_chang_para.append(("Kmeans Clustering: ", KMeans(n_clusters=1, max_iter=20, random_state=20, init='random')))
clf_models_chang_para.append(("Gaussian Mixture Model: ", GaussianMixture(n_components=2, covariance_type='tied', random_state=0)))
clf_models_chang_para.append(("MeanShift Clustering: ", MeanShift(max_iter=1)))
clf_models_chang_para.append(("Birch Clustering:", Birch(n_clusters=3)))
print('\nClustering models results after changing parameters are...')
results_chang_para = []
names_chang_para = []
for name_chang_para,model_change_para in clf_models_chang_para:
kfold_chang_para = KFold(n_splits=10, random_state=0, shuffle=True)
cv_result_chang_para = cross_val_score(model_change_para,X,Y, cv = kfold_chang_para, scoring = "accuracy")
names_chang_para.append(name_chang_para)
results_chang_para.append(cv_result_chang_para)
for i in range(len(names_chang_para)):
print(names_chang_para[i],results_chang_para[i].mean()*100)
model_agg = AgglomerativeClustering(n_clusters=3,linkage='ward')
model_agg.fit(X)
labels_agg = model_agg.labels_
print("Agglomerative Clustering: ", accuracy_score(labels_true, labels_agg).mean()*100)
|
100b3472314334813a10184af3347445db3e70d5 | lucasguerra91/some-python | /Trabajos_Practicos/TP3/entrega/pluma.py | 999 | 3.8125 | 4 | class Pluma:
'''Crea una Pluma para ser utilizada por la clase Tortuga.'''
def __init__(self, ancho=1, color="black"):
self.ancho = ancho
self.color = color
self.abajo = True
def esta_abajo(self):
'''Devuelve la posición de la Pluma:
True si está abajo, False si está arriba.'''
return self.abajo
def pluma_arriba(self):
'''Cambia la posición de la Pluma a "arriba".'''
self.abajo = False
def pluma_abajo(self):
'''Cambia la posición de la Pluma a "abajo".'''
self.abajo = True
def cambiar_ancho(self, ancho):
'''Cambia el ancho de la Pluma.'''
self.ancho = ancho
def cambiar_color(self, color):
'''Cambia el color de la Pluma.'''
self.color = color
def obtener_ancho(self):
'''Devuelve el ancho de la Pluma.'''
return self.ancho
def obtener_color(self):
'''Devuelve el color de la Pluma.'''
return self.color
def copiar(self):
'''Crea una nueva instancia de Pluma, con los mismos atributos.'''
return Pluma(self.ancho, self.color)
|
2b587eb5292af3261309413e7cd9436add8b72ef | dilesh111/Python | /20thApril2018.py | 904 | 4.625 | 5 | ''' Python program to find the
multiplication table (from 1 to 10)'''
num = 12
# To take input from the user
# num = int(input("Display multiplication table of? "))
# use for loop to iterate 10 times
for i in range(1, 11):
print(num,'x',i,'=',num*i)
# Python program to find the largest number among the three input numbers
# change the values of num1, num2 and num3
# for a different result
num1 = 10
num2 = 14
num3 = 12
# uncomment following lines to take three numbers from user
# num1 = float(input("Enter first number: "))
# num2 = float(input("Enter second number: "))
# num3 = float(input("Enter third number: "))
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number between", num1, ",", num2, "and", num3, "is", largest) |
4836686b3106701382e3b85859b177d09353a308 | spaingmzdaeg/MetodosBusqueda_Python | /Busqueda.py | 2,179 | 3.65625 | 4 | import random
class Busqueda:
def busquedaSecuencial(self,unaLista,datoBuscar):
pos=0
encontrado=False
while pos < len(unaLista) and not encontrado:
if unaLista[pos]==datoBuscar:
encontrado=True
else:
pos=pos+1
return encontrado
def busquedaBinaria(self,unaLista,elemento):
primero = 0
ultimo = len(unaLista)-1
while(primero <= ultimo):
centro = int((primero + ultimo)/2)
valorCentro = unaLista[centro]
print ("Comparando "+str(elemento)+" Con "+str(unaLista[centro]))
if elemento == valorCentro:
return centro
elif elemento < valorCentro:
ultimo = centro - 1 #con el fin de desplazarnos hacia la izquierda
else:
primero = centro + 1 #con el fin de desplazarnos hacia la derecha
return -1
def llenarLista(n):
lista = [0] * n
for i in range(n):
lista[i] = random.randint(0, 100)
return lista
#modulo principal
opc=""
obj = Busqueda()
lista=llenarLista(100)
while(opc!="C"):
print("----------MENU----------------------")
opc=input("A)Busqueda Secuencial\nB)Busqueda binaria\nC) SALIR ").upper()
if opc == "A":
listaAux=lista
print(listaAux)
elementoBuscado = int(input("Ingrese elemento a buscar....."))
indice = obj.busquedaSecuencial(listaAux, elementoBuscado)
if indice != -1:
print("Elemento " + str(elementoBuscado) + " se encuentra en la lista.")
else:
print("Elemento " + str(elementoBuscado) + " NO encontrado")
elif opc == "B":
lista.sort()#ordenamos lista previamente
listaAux = lista
print("lista ya ordenada")
print(listaAux)
elementoBuscado = int(input("Ingrese elemento a buscar....."))
indice = obj.busquedaBinaria(listaAux,elementoBuscado)
if indice != -1:
print("Elemento "+str(elementoBuscado)+" se encuentra en el indice:"+str(indice))
else:
print("Elemento "+str(elementoBuscado)+" NO encontrado")
|
44d92f19f6e734ea3b8eb6de47804fa0bf6d7948 | quanee/Note | /Python/Python/Python19.py | 778 | 3.609375 | 4 | from time import ctime, sleep
import threading
'''
线程实例
计算密集型 c
IO密集型 多线程
'''
def music(func):
for i in range(2):
print("Begin listening to %s. %s" % (func, ctime()))
sleep(1)
print("end listening %s" % ctime())
def movie(func):
for i in range(2):
print("Begin watching at the %s! %s" % (func, ctime()))
sleep(5)
print("end watching %s" % ctime())
threads = []
t1 = threading.Thread(target=music, args=('七里香',))
threads.append(t1)
t2 = threading.Thread(target=movie, args=('阿甘正传',))
threads.append(t2)
if __name__ == '__main__':
# music(u'七里香')
# movie(u'世界末路')
for t in threads:
t.setDaemon(True) # 并行不阻塞 不等待t结束 |
a7a76e60dcac10eb0484d546b767349df6487036 | mubaskid/new | /DAY4/List.py | 325 | 4.09375 | 4 | NUMBERS = 6
numbers = []
sum = 0
for i in range(NUMBERS):
value = int(input("Enter a number: "))
numbers.append(value)
sum += value
average = sum / NUMBERS
count = 0
for i in range(NUMBERS):
if numbers[i] > average:
count += 1
print("average is", average)
print("number above average is", count) |
b9beb71069f47b5003aba3ea400e582f83ca8a7d | bellagrin10/GeekBrains_PythonBasics | /HomeWork3/task_3_4_variant2.py | 1,248 | 3.765625 | 4 | def thesaurus_adv(*args):
"""
The function takes strings in the format "First Name Last Name" as arguments and returns a dictionary,
in which the keys are the first letters of the surnames, and the values are dictionaries,
in which the keys are the first letters of the names, and the values are lists,
containing full names starting with the corresponding letter.
"""
usernames = {}
full_names = list(map(str.split, args))
list(
map(
lambda x: usernames.setdefault(x[1][0], {}),
full_names
)
)
print(usernames)
list(
map(
lambda x: usernames[x[1][0]].update({x[0][0]: []}),
full_names
)
)
print(usernames)
list(
map(
lambda x: usernames[x[1][0]][x[0][0]].append(' '.join(x)),
full_names
)
)
return usernames
result = thesaurus_adv("Иван Сергеев", "Инна Серова", "Петр Алексеев", "Илья Иванов", "Анна Савельева")
print(result)
# Sorting the dictionary by foreign keys: first letters of surnames and by internal keys: first letters of names
print(sorted(result.items()))
print(
*map(
lambda x: {x[0]: dict(sorted(x[1].items()))},
sorted(result.items())
)
)
|
3e611d51973056a745287c7fd60781990a791d71 | WarrenJames/LPTHWExercises | /exl20.py | 2,777 | 4.40625 | 4 | # Exercise 20: Functions and Files
#
# from system folder, import argument variable
from sys import argv
# script, input_file = argv
# it will look like in terminal: python exl20.py (file of choice as input_file)
script, input_file = argv
# define(function) print_all(with f as an expression): <-- consists of
# prints f.read() what is read from f(f means file) without perameters
def print_all(f):
print f.read()
# define rewind function(with f as an expression): <-- consists of
# f with seek command with 0 as an expression (0)
# seeks the very start of the file seeks byte 0 which is at the start of file.
def rewind(f):
f.seek(0)
# define function print_a_line with line_count and f(file) as expressions
# consists of printing line_count, and f.readline() reads line of file without
# parameteres
def print_a_line(line_count, f):
print line_count, f.readline()
# variable current_file is equal to open(input_file) input_file is the second
# argument variable entered in terminal (test.txt)
current_file = open(input_file)
# prints "First let's print the whole file:\n" \n means new line
print "First let's print the whole file:\n"
# calls print_all function with current_file as an expression
print_all(current_file)
# print "Now let's rewind, kind of like a tape."
print "Now let's rewind, kind of like a tape."
# calls rewind function with current_file as an expression
rewind(current_file)
# prints "Let's print three lines:" into the terminal
print "Let's print three lines:"
# variable current_line is equal to 1
# calls print_a_line function with current_line and current_file as expressions
# (1, test.txt) print_a_line prints line count as 1 while reading test.txt
current_line = 1
print_a_line(current_line, current_file)
# variable current_line is equal to current_line + 1 OR 1 + 1 OR 2
# calls function print_a_line with current_line, and current_file as expressions
# OR print_a_line(2, test.txt)
current_line = current_line + 1
print_a_line(current_line, current_file)
# variable current_line is equal to current_line + 1 OR 2 + 1 OR 3
# calls function print_a_line with current_line, and current_file as expressions
# OR print_a_line(3, test.txt)
current_line = current_line + 1
print_a_line(current_line, current_file)
# variable current_line is equal to current_line + 1 OR 3 + 1 OR 4
# calls function print_a_line with current_line, and current_file as expressions
# OR print_a_line(4, test.txt)
current_line = current_line + 1
print_a_line(current_line, current_file)
# TIL
# current_line variable is used more for user to keep note to know what line
# file is on. the file does not care what current_line says and will continue
## regardless. file.tell() will tell where the file head is postitioned
|
9a4094089475fb4786aefd7901241311aeae95ef | mennanov/hackerrank | /warmup/lonely_integer.py | 394 | 3.65625 | 4 | """
There are N integers in an array A. All but one integer occur in pairs. Your task is to find the number that occurs only once.
We can use XOR to solve this problem in linear time: x ^ x = 0, so the only number which will remain is a lonely number.
"""
if __name__ == '__main__':
_ = input()
ints = map(int, raw_input().strip().split(" "))
print reduce(lambda x, y: x ^ y, ints) |
3357aa457d6d82af7d85ffd319884640a99087bc | France-ioi/taskgrader | /examples/taskRunner/tests/gen/sol-bad-py.py | 411 | 3.515625 | 4 | #!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
# Example bad solution for this task
# Defines the function min3nombres which is then used by the runner
def min3nombres(a, b, c):
# Bad solution: we return the max instead of the min
if a < b:
if b < c:
return c
else:
return b
else:
if a < c:
return c
else:
return a
|
42a35149f94ba560b93d86e676ac88560caa8e73 | DajuanM/DHPythonDemo | /02_高级用法/04_高级函数补充.py | 905 | 3.625 | 4 | # zip
l1 = [1,2,3,4]
l2 = [10,20,30,40]
z = zip(l1,l2)
print([i for i in z])
# enumerate
l = [10,20,30,40]
em = enumerate(l)
l2 = [i for i in em]
print(l2)
em = enumerate(l, start=100)
l2 = [i for i in em]
print(l2)
# collections模块
# - nametuple
# - deque 解决了频繁删除插入的效率问题
import collections
Point = collections.namedtuple("Point", ["x", "y"])
p = Point(10, 20)
print(p.x, p.y, p[0], p[1])
print(isinstance(p, tuple))
from collections import deque
q = deque([1,2,3,4])
print(q)
q.append(5)
print(q)
q.appendleft(0)
print(q)
# defaultdict
from collections import defaultdict
d = {"a": 1, "b": 2, "c": 3}
print(d["a"])
func = lambda: "默认值"
d = defaultdict(func)
print(d["a"])
# Counter 统计字符串个数
from collections import Counter
c = Counter("as;mdoqwoingqwoiepoqwmdoqwnokwqndqw")
print(c)
s = ["1", "2", "2", "3", "3", "3"]
c = Counter(s)
print(c)
|
febfcc3e1daf6945994c6387d2ca881f8ed15c10 | eternalseptember/CtCI | /05_bit_manipulation/03_flip_bit_to_win/flip_bit_to_win_sol_1.py | 1,713 | 3.6875 | 4 | # Brute force solution
# Integer.BYTES = 32?
# O(b) time and O(b) memory, where b is the length of the sequence.
def longest_sequence_of_ones(num):
if num == -1:
# -1 in binary is a string of all ones.
# This is already the longest sequence.
return "No bits are flipped."
sequences = get_alternating_sequences(num)
return find_longest_sequence(sequences)
def get_alternating_sequences(num):
# Returns a list of the sixes of the sequences. The sequence starts
# off with the number of 0's (which might be 0) and then the
# alternates with the counts of each value.
seq_list = []
searching_for = 0
counter = 0
# i in range Integer.BYTES
for i in range(32 * 8):
if ((num & 1) != searching_for):
seq_list.append(counter)
searching_for = num & 1 # Flip [1 to 0] or [0 to 1].
counter = 0
counter += 1
# num >>>= 1; >>> is zero-fill right shift
num = num >> 1
seq_list.append(counter)
return seq_list
def find_longest_sequence(seq_list):
# Given the lengths of alternating sequence of 0's and 1's,
# find the longest one we can build.
max_seq = 1
for i in range(0, len(seq_list), 2):
zeros_seq = seq_list[i]
if (i - 1) >= 0:
ones_seq_right = seq_list[i - 1]
else:
ones_seq_right = 0
if (i + 1) < len(seq_list):
ones_seq_left = seq_list[i + 1]
else:
ones_seq_left = 0
this_seq = 0
if zeros_seq == 1:
# can merge
this_seq = ones_seq_left + 1 + ones_seq_right
elif zeros_seq > 1:
# just add a zero to either side
this_seq = 1 + max(ones_seq_right, ones_seq_left)
elif zeros_seq == 0:
# no zero, but take either side
this_seq = max(ones_seq_right, ones_seq_left)
max_seq = max(this_seq, max_seq)
return max_seq
|
6cb6ca4d7eaee6ec5d2930b39e45ac58b6a8b7c0 | panchyni/PseudogenePipeline | /_pipeline_scripts/1_3_getUniqesFromCol.py | 409 | 3.625 | 4 | #This script is designed to simply print the number of unique items in a given
#column
#Created by David E. Hufnagel on June 13, 2012
import sys
inp = open(sys.argv[1]) #input file to check for unique items
col = int(sys.argv[2]) - 1 #the column to check for unique items
theSet = set()
for line in inp:
lineLst = line.split("\t")
theSet.add(lineLst[col])
#print theSet
print len(theSet)
inp.close()
|
cb9926b4eb1ae20e9bac19751a3f55460f0ccf6b | LingChenBill/lc_pandas | /ch03/4_find_max_by_sorted.py | 1,118 | 3.59375 | 4 | #! /usr/bin/python3
# -*- coding:utf-8 -*-
# @Time: 2020/6/27
# @Author: Lingchen
# @Prescription: 通过排序选取每组中的最大值
import pandas as pd
movie = pd.read_csv('../data/movie.csv')
movie2 = movie[['movie_title', 'title_year', 'imdb_score']]
print('movie2按照title_year降序排列: ')
print(movie2.sort_values('title_year', ascending=False).head())
print('用列表同时对两列进行排序: ')
print(movie2.sort_values(['title_year', 'imdb_score'], ascending=False).head())
print('运用drop_duplicates去重,只保留每一年的第一条数据:')
movie3 = movie2.sort_values(['title_year', 'imdb_score'], ascending=False)
print(movie3.drop_duplicates(subset='title_year').head())
print('可以对ascending设置列表,可以同时一列降序排列,一列升序排列:')
movie4 = movie[['movie_title', 'title_year', 'content_rating', 'budget']]
movie4_sorted = movie4.sort_values(['title_year', 'content_rating', 'budget'],
ascending=[False, False, True])
print(movie4_sorted.drop_duplicates(subset=['title_year', 'content_rating']).head(10))
|
8e1eaca2c534ab590ef058f10c521bcab1b4c678 | xiaochenchen-PITT/CC150_Python | /Leetcode/Unique Binary Search Trees.py | 866 | 3.703125 | 4 | # Unique Binary Search Trees
class Solution:
# @return an integer
def numTrees(n):
# DP
mp = {0: 1, 1: 1} # key: n, value: number of different structures
if n in mp:
return mp[n]
for i in range(2, n+1): # i nodes
res = 0
sm = 0
for j in range(0, i):# j nodes can be put either on the left or on the right. j in [0,i-1]
sm += mp[j] * mp[i-1-j]
res += sm
mp[i] = res
return mp[n]
# recursive method
# if n == 0 or n == 1:
# return 1
# res = 0
# for i in xrange(0, n):
# # assign i nodes on the left and (n-1-i) on the right
# # because left side is independent of right side, so multiply them
# res += self.numTrees(i) * self.numTrees(n - 1 -i)
# return res |
1a2c878c2a7417c4258a3e75e36e1e1f6dad15af | SandboxGTASA/Python-1 | /Jogo da forca/jogo_da_forca.py | 1,663 | 3.78125 | 4 | import random
import time
palavras = ('casa', 'abelha', 'cachueira', 'porta', 'mesa', 'lixeira', 'cadeado', 'guarda')
sorteio_palavras = random.choice(palavras) # Pegando palavras aleatorias
letras = []
tentantiva = 5
acertou = False
print('='*20 + ' JOGO DA FORCA ' + '='*20 + '\n')
print('Sorteando um palavra...')
time.sleep(1.5) # Criando um pequeno cronometro
print(f'A palavra sorteada possui {len(sorteio_palavras)} letras\n')
# Fazendo um for para substiruir as letras sortiadas por traços
for i in range(0, len(sorteio_palavras)):
letras.append('-')
# Laço de repetição que executara enquanto
while acertou == False:
enter_letras = str(input('Entre com uma letra: '))
# Pecorre a palavra sorteada e inserir a letra acertada
for i in range(0, len(sorteio_palavras)):
if enter_letras == sorteio_palavras[i]:
letras[i] = enter_letras
print(letras[i])
acertou = True
# Pecorre a palavra sorteada e conpara se ainda existe algum taço
# Caso tenha contunua o laço
for x in range(0, len(sorteio_palavras)):
if letras[x] == '-':
acertou = False
# OBS -> Ao entra nessas linhas do codigo a intenção é que a cada letra errada o numero de
# tentativas seja - 1, o que realmente acontece, porem tambem as tentativas estão sendo subtraidas
# caso a letra estejam certas.
if enter_letras == sorteio_palavras:
tentantiva = tentantiva
else:
print(f'Você possui {tentantiva} Tentativas.')
tentantiva -= 1
# Comparando as tentativas
if tentantiva <= 0:
print('enforcado')
print(letras)
break
|
6de3ec1cfef71a8e50c8f6b69bf6e3a6dccc6b3a | jeysonrgxd/python | /nociones_basicas/operadores_expresiones/operadores_logicos.py | 546 | 4.1875 | 4 | # OPERADOR not
# not true = false
# dos formas de expresion logicas por conjuncio(AND) y disyuncion(OR)
'''
>> True and True
True
>> not True
False
>> True or False
True
>> False or False
False
>> not True == False
True
>> False and False
False
'''
print("CONJUNCION and\n")
a=13
b = a > 10 and a < 20
print(b) #salida -> True
c = "Hola Mundo"
d = len(c) >= 5 and c[0] == "H"
print(d)
print("\nDISYUNCION or\n")
e = "SALIDA"
f = (e == "EXIT") or (e == "FIN") or (e == "SALIDA")
print(f)
g = "Lector"
i = g[0] == "H" or g[0] == "h"
print(i)
|
873fad90d0b61790b78434d7786c2a1d9aabc05c | NagiReddyPadala/python_programs | /Python_Scripting/Pycharm_projects/DataStructures/LinkedList/DoublyLinkedList.py | 2,866 | 3.59375 | 4 | class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
else:
cur = self.head
while cur.next:
cur = cur.next
cur.next = new_node
new_node.next = None
new_node.prev = cur
def prepend(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
else:
new_node.next = self.head
self.head.prev = new_node
self.head = new_node
def add_after(self, key, data):
new_node = Node(data)
cur = self.head
if cur.data == key and not cur.next:
self.append(data)
# self.head.next = new_node
# new_node.prev = self.head
else:
while cur.next:
if cur.data == key:
break
cur = cur.next
new_node.prev = cur
new_node.next = cur.next
cur.next = new_node
def add_before(self, key, data):
new_node = Node(data)
cur = self.head
prev = Node
if cur.data == key and not cur.prev:
self.prepend(data)
# self.head.next = new_node
# new_node.prev = self.head
else:
while cur.next:
if cur.data == key:
break
prev = cur
cur = cur.next
prev.next = new_node
new_node.prev = prev
new_node.next = cur
cur.prev = new_node
def delete(self, key):
cur = self.head
prev = None
if cur.data == key and not cur.prev:
cur.next.prev = None
self.head = cur.next
return
while cur:
if cur.data == key:
break
prev = cur
cur = cur.next
if not cur.next:
prev.next = None
else:
prev.next = cur.next
cur.next.prev = prev
def reverse(self):
temp = None
cur = self.head
while cur:
temp = cur.prev
cur.prev = cur.next
cur.next = temp
cur = cur.prev
if temp:
self.head = temp.prev
def print_list(self):
cur = self.head
while cur:
print(cur.data)
cur = cur.next
dlist = DoublyLinkedList()
dlist.append("A")
dlist.append("B")
dlist.append("C")
dlist.append("D")
#dlist.prepend("E")
#dlist.add_after("D", "E")
#dlist.add_before("D", "E")
#dlist.delete("D")
dlist.reverse()
dlist.print_list()
|
9f4a8310cf7402cfb4418db7cf2c3ab2c10aa2a5 | seoket1/BootCamp2017 | /Homeworks/Math/Week6/Some_Codes_for_Chapter_8.py | 1,574 | 3.5625 | 4 | import numpy as np
from matplotlib import pyplot as plt
# 8.1
x = np.linspace(-10, 10, 1000)
y = np.linspace(-10, 10, 1000)
f = 5*x - 4*y
y1 = (1/3) * (2*x + 4)
y2 = (1/6) * (x-1)
y3 = 6 - x
plt.plot(x, y1, label = "y1")
plt.plot(x, y2, label = "y2")
plt.plot(x, y3, label = "y3")
plt.plot(x, np.zeros(x.size), label = "x=0")
plt.plot(np.zeros(y.size), y, label = "y=0")
plt.legend()
plt.text(0,3, 'feasible set')
plt.show()
# 8.2
#(i)
x = np.linspace(0, 10, 1000)
y = np.linspace(0, 10, 1000)
f = 3*x + y
y1 = (1/3) * (15 - x)
y2 = (1/3) * (-2*x + 18)
y3 = x - 4
plt.plot(x, y1, label = "y1")
plt.plot(x, y2, label = "y2")
plt.plot(x, y3, label = "y3")
plt.plot(x, np.zeros(x.size), label = "x=0")
plt.plot(np.zeros(y.size), y, label = "y=0")
plt.legend()
plt.text(0,3, 'feasible set')
plt.show()
#(ii)
x = np.linspace(0, 30, 1000)
y = np.linspace(0, 30, 1000)
f = 4*x + 6*y
y1 = x + 11
y2 = -x + 27
y3 = (1/5)*(-2*x + 90)
plt.plot(x, y1, label = "y1")
plt.plot(x, y2, label = "y2")
plt.plot(x, y3, label = "y3")
plt.plot(x, np.zeros(x.size), label = "x=0")
plt.plot(np.zeros(y.size), y, label = "y=0")
plt.legend()
plt.text(0,3, 'feasible set')
plt.show()
# 8.7
#(ii)
x = np.linspace(0, 5, 1000)
y = np.linspace(0, 5, 1000)
f = 5*x + 2*y
y1 = (1/3)*(15 - 5*x)
y2 = (1/5)*(15-3*x)
y3 = (1/3)*(4*x + 12)
plt.plot(x, y1, label = "y1")
plt.plot(x, y2, label = "y2")
plt.plot(x, y3, label = "y3")
plt.plot(x, np.zeros(x.size), label = "x=0")
plt.plot(np.zeros(y.size), y, label = "y=0")
plt.legend()
plt.text(4,3, 'infeasible')
plt.show()
|
3047affa42aa289118bdcf5c8ecfd192ebe6b7c7 | highjump000/DNNEXMP | /ReinforcementLearningEXP/ENVIRONMENT.py | 1,421 | 3.5625 | 4 | #created by bohuai jiang
# on 2/10/2017 09:47
# create agent environment
import numpy as np
class ENVIRONMENT:
def __init__(self,width,height):
self.width = width
self.height = height
self.I = [0,0] # initial state
self.O = [width-1,height-1] # end state
self.NUMBER_OF_ACTION = 4
# show environment
def show(self):
for i in range(self.height):
line = ''
for j in range(self.width):
if i == self.I[0] and j == self.I[1]:
line += '[I]'
else:
if i == self.O[0] and j == self.O[1]:
line += '[O]'
else:
line += '[ ]'
print line
def get
def getNextState(self,state,a):
if a == 0: #go up
if state[0] < self.height-1:
state[0] += 1
if a == 1: #go down
if state[0] > 0:
state[0] -= 1
if a == 2: #go left
if state[1] < self.width-1:
state[1] += 1
if a == 3: #go right
if state[1] > 0:
state[0] -= 1
return state
def Reward(self,state):
if state == self.O:
return 100
else:
return 0
def zero_init_Q(self):
Q = np.zeros([self.height,self.width,self.NUMBER_OF_ACTION])
return Q |
7cd01906f57c1bcbcef26ffd2ebdb78aba0080ed | Suganya108/guvi | /looping/swap_first_and_last_digits_of_a_number.py | 178 | 3.875 | 4 |
# Write a program to swap first and last digits of a number.
def fun(n):
c=str(n)
c[0],c[-1]=c[-1],c[0]
print(c)
return 0
n=int(input("Enter no. : "))
fun(n)
|
416be965774c5c1ef85adc8c576a0948af2289df | JishnuRamesh/Algorithms-and-datastructures | /Hashmap/hashmap.py | 2,240 | 3.546875 | 4 |
class map:
def __init__(self, size):
self.size = size
self.keys = [None] * self.size
self.value = [None] * self.size
def put(self,key,value):
probeIndex = 0
hashValue = self.hash_function(key,len(self.keys), probeIndex)
if self.keys[hashValue] == None or \
self.keys[hashValue] == "X":
self.keys[hashValue] = key
self.value[hashValue] = value
elif self.keys[hashValue] == key:
self.value[hashValue] = value
else:
positionFound = False
while not positionFound:
probeIndex += 1
rehash = self.hash_function(key,len(self.keys),probeIndex)
if self.keys[hashValue] == None or \
self.keys[hashValue] == "X":
self.keys[hashValue] = key
self.value[hashValue] = value
positionFound = True
elif self.keys[hashValue] == key:
self.value[hashValue] = value
positionFound = True
def get(self,key):
probeIndex = -1
found = False
while found != True and probeIndex < self.size:
probeIndex += 1
hashValue = self.hash_function(key, len(self.keys), probeIndex)
if self.keys[hashValue] == None:
return False
elif self.keys[hashValue] == key:
return self.value[hashValue]
else:
continue
def delete(self,key):
probeIndex = 0
hashValue = self.hash_function(key,self.size,probeIndex)
found = False
stop = False
inital = hashValue
while self.keys[hashValue] != None and not found and not stop:
if self.keys[hashValue] == key:
self.keys[hashValue] = "X"
found = True
else:
probeIndex += 1
hashValue = self.hash_function(key,self.size,probeIndex)
if hashValue == inital:
stop = True
return found
def hash_function(self,key,size, probeIndex):
return ( (key % size) + probeIndex )
|
62ab47d114423cb039bc16b2859758d62dde2ca3 | CocoaBrew/General | /Python/PokerGame.py | 3,825 | 4.03125 | 4 | # This program will let user play a simple Poker game,
# then report user's score and thank him for playing at end
# Dan Coleman
# 12/04/13
# Program 6
# provides information for Dice class
import random
class Dice:
def __init__(self):
# create empty dice, then roll to set them
self.dice = [0] * 5
self.rollAll()
def roll(self, positions):
# update the values for all positions in the positions list
for pos in positions:
self.dice[pos] = random.randint(1,6)
def rollAll(self):
# update values for all five positions
self.roll(range(5))
def values(self):
# return a copy of the list of dice values
return self.dice[:]
def score(self):
# Return the poker description and score for the current set
# of dice values. This is what you need to implement.
# create dictionary for tallying occurrences
d = {}
for i in self.values():
if i in d:
d[i] += 1
else:
d[i] = 1
sD = sorted(d) #sort dictionary keys
pD = list(d.keys()) #list of dictionary keys
# Overall, use length of dict and whether values equal each other
# to determine what response to return
# "Five of a Kind", 30
if len(pD) == 1:
return "Five of a Kind", 30
# "Four of a Kind", 15
elif len(pD) == 2 and (d[pD[0]] == 4 or d[pD[1]] == 4):
return "Four of a Kind", 15
# "Full House", 12 (3 and 2 of two different kinds)
elif len(pD) == 2:
return "Full House", 12
# "Three of a Kind", 8
elif (len(pD) == 2 or len(pD) == 3) and (d[pD[0]] == 3 or d[pD[1]] == 3 or d[pD[2]] == 3):
return "Three of a Kind", 8
# "Straight", 20 (one of each from 1-5 or 2-6)
elif len(pD) == 5 and ((sD[0]) == (sD[1]-1) == (sD[2]-2) == (sD[3]-3) == (sD[4]-4)):
return "Straight", 20
# "Two Pairs", 5
elif len(pD) == 3:
return "Two Pairs", 5
# "Garbage", 0
else:
return "Garbage", 0
# provides information for Poker class
class Poker:
# initiates money and instance of dice class
def __init__(self):
self.d = Dice()
self.money = 100
def run(self):
while (self.money >= 10):
play = input("Would you like to play/continue (Y/N)? ")
if play == 'Y':
self.playRound()
print(self.d.score()) #print score
self.money += self.d.score()[1] #add money amt from score
print("Money is at", self.money, ". ")
else:
break
print("Your money's final balance is", self.money, ". ")
print("Thank you for playing. ")
# plays a round of the Poker game
def playRound(self):
self.money -= 10 #mark money down for a round of play
self.d.rollAll()
for i in range(2): #give user two optional rerolls
print(self.d.values())
again = input("Would you like to roll again (Y/N)? ")
# rolls again based on entered indices
if again == 'Y':
where = input("Enter indices of dice for re-roll: ")
whereList = []
for i in where: #eliminate unnecessary characters from input string
if (i != '[') and (i != ']') and (i != ',') and (i != ' '):
whereList.append(int(i))
#print(where)
self.d.roll(whereList)
else:
break
# actually run the created class
def main():
s = Poker() #instantiate the object
s.run()
main()
|
91f61ca12407633ddfb7692f61e9e4c6b783c55a | Silvio622/pands-problems-2020 | /Lab 03 Variable and State/lab03.03-div.py | 327 | 4.21875 | 4 | # program that reads in two numbers and
# outputs the integer answer and remainder
x = int(input("Enter first number: "))
y = int(input("Enter the number you want to divide by: "))
answer = int(x/y)
remainder = x%y # remainder is percent sign %
print("{} divided {} is {} with remainder {}".format(x, y, answer, remainder))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.