blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
64d4488f81af7543a6906991af8d564992b89e5d
|
XuyingLiu/crabs
|
/craps.py
| 1,367 | 4.1875 | 4 |
"""This is the main module of our craps game
usage: python3 craps.py number_of_gmaes
"""
import sys
from random import randint
print("craps game")
# num_of_games = int(sys.argv[1])
num_of_games = int(input("How many times do you want to play craps? "))
print(f"Playing {num_of_games} games...")
def craps():
"""run a round of the craps and return win or loss.
returns: 1 or 0"""
#print("Game Running")
d1=randint(1,6)
d2=randint(1,6)
dpoint=d1+d2
#print(f"Dice: {d1}+{d2}={dpoint}")
if dpoint in (2,3,12):
return 0
elif dpoint in (7,11):
return 1
else:
return trial(dpoint)
def trial(point):
"""run the trials to solve the more complex craps.
return: 1 or 0"""
while True:
d1=randint(1,6)
d2=randint(1,6)
dtot=d1+d2
#print(f"Dice: {d1}+{d2}={dtot}")
if dtot==7:
return 0
elif dtot==point:
return 1
else:
pass
def multicraps(times):
"""run the craps game multiple times and return the number of wins.
returns: int"""
wins=0
for _ in range(times):
result=craps()
#print(result)
wins+=result
return wins
win_count=multicraps(num_of_games)
win_rate=win_count/num_of_games*100
print(f"Result: {win_count} wins. {win_rate:.2f}% win rate")
|
3866e07a8721b67ff44fb2ee0aa2ffacef53c192
|
amit19-meet/meet2017y1lab6
|
/funturtle.py
| 1,624 | 4.65625 | 5 |
import turtle #python needs this to use all the turtle functions
#turtle.shape("turtle") #changes the shape to a turtle
#square = turtle.clone() #creates new turtle and saves it in square
#square.shape("square") # changes the shape of the second turtle to a square
#square.goto(100, 100) # moves square to ( x= 100, y= 100)
#square.goto(100,0)
#square.goto(100,100)
#square.goto(0,100)
#square.goto(0,0)
#triangle = turtle.clone() #creates new turtle and saves it in triangle
#triangle.shape("triangle") #changes the shape of the third turtle to a triangle
#triangle.goto(100,0)
#triangle.goto(50,25)
#triangle.goto(0,0)
#square.penup()
#square.goto(200,200)
#square.stamp()
#square.goto(100,50)
#triangle.penup()
#triangle.goto(200,200)
#triangle.stamp()
#triangle.goto(100,50)
UP_ARROW = "Up" #these are the codes that correspond to the keys
LEFT_ARROW = "Left"
DOWN_ARROW = "Down"
RIGHT_ARROW = "Right"
SPACEBAR = "space"
UP = 0
LEFT = 1
DOWN = 2
RIGHT = 3
direction = UP
def up():
global direction
print("you pressed Up!")
def down():
global direction
direction = DOWN
print("you pressed Down!")
def left():
global direction
direction = LEFT
print("you pressed Left!")
def right():
global direction
direction = RIGHT
print("you pressed Right!")
#these lines of code calls the right functions when you press keys
turtle.onkeypress(up, UP_ARROW) #move up when you press up
turtle.onkeypress(down, DOWN_ARROW)
turtle.onkeypress(left, LEFT_ARROW)
turtle.onkeypress(right, RIGHT_ARROW)
turtle.listen()
turtle.mainloop() #makes this the last line in ypur turtle code
|
77ba709d8947b89c6fecae29aa39c1fa5ddf6fce
|
samli6479/PythonLearn
|
/BinaryTree.py
| 1,728 | 4.21875 | 4 |
# Binary Tree
# A Binary Tree is a tree that has a left branch and a right branch
# Fill the missing with an empty tree # An instance of tree must have two branches
# Binanry Search Tree
# Each entry larger than all entries on left and smaller than the rights
class Tree:
def __init__(self, entry, branches = ()):
self.entry = entry
for branch in branches:
assert isinstance(branch, Tree)
self.branches = list(branches)
def __repr__(self):
if self.branches:
branches_repr = ", " +repr(self.branches)
else:
branches_repr = ""
return "Tree({0}{1})".format(self.entry,branches_repr)
class BinaryTree(Tree):
empty = Tree(None)
empty.is_empty = True
def __init__(self, entry, left = empty, right = empty):
Tree.__init__(self,entry,(left,right))
self.is_empty = False
@property
def left(self):
return self.branches[0]
@property
def right(self):
return self.branches[1]
Bin = BinaryTree
Bin(3, Bin(1),Bin(7,Bin(5),Bin(9,Bin.empty,Bin(11))))
'''set_contains travels the tree
-If the element is not the entry, it can only be either left or right
- Focusing on one branch, reduce the set about half the recursive call'''
def set_contains(s,v):
'Check if the Bin contains the element v'
# Most Theata(hight of tree) on average
# Theata(log n) on average for balanced tree
# Order of growth
if s.is_empty:
return False
elif s.entry == v:
return True
elif s.entry < v:
return set_contains(s.right,v)
elif s.entry > v:
return set_contains(s.left, v)
|
e54ab71102a107a7110e0f7dcb246389216fb3aa
|
xzjia/lifeline-scraper
|
/Movies/main.py
| 4,414 | 3.640625 | 4 |
#!/usr/bin/env python3
import argparse
import datetime
import json
from requests_html import HTMLSession
def parse_args():
"""Parse and return the command-line arguments.
"""
parser = argparse.ArgumentParser(
description='Retrieve movie box office sales figures for fridays within the given range.')
parser.add_argument(
'start_date', help='the start date for the data scraping (inclusive).')
parser.add_argument(
'end_date', help='the end date for the data scraping (exclusive).')
return parser.parse_args()
def get_chart(raw_html):
"""Return all the charting movies that appear in the given raw_html.
Args:
raw_html: A raw_html object that is returned by requests_html.find()
Returns:
An array of objects. Each object represents a single movie that is on the chart.
"""
table = raw_html.html.find("#page_filling_chart table", first=True)
# Ignore the first row because it is the table's headings
rows = table.find("tr")[1:]
keys = ["current_week_rank", "previous_week_rank", "movie", "distributor",
"gross", "change", "num_theaters", "per_theater", "total_gross", "days"]
results = []
for row in rows:
this_row = dict()
cells = row.find("td")
for i in range(len(cells)):
this_row[keys[i]] = cells[i].text
results.append(this_row)
return results
def get_weekend_chart(year, month, date):
"""Return an array of movies that were on the charts for the weekend of the given date.
Args:
year: target year
month: target month
date: target date
Returns:
An array of objects. Each object represents a single movie that is on the chart.
"""
session = HTMLSession()
raw_html = session.get(
"https://www.the-numbers.com/box-office-chart/weekend/{}/{}/{}".format(year, month, date))
return get_chart(raw_html)
def get_weekly_chart(year, month, date):
"""Return an array of movies that were on the charts for the week of the given date.
Args:
year: target year
month: target month
date: target date
Returns:
An array of objects. Each object represents a single movie that is on the chart.
"""
session = HTMLSession()
raw_html = session.get(
"https://www.the-numbers.com/box-office-chart/weekly/{}/{}/{}".format(year, month, date))
return get_chart(raw_html)
def get_movies_for_day(date):
"""Return an array of movies that were on the charts for the given date.
If there is data for the weekly chart, use it.
Else if there is data for the weekend chart, use it.
Else, return None.
Args:
date: target date
Returns:
An array of objects. Each object represents a single movie that is on the chart.
"""
chart = get_weekly_chart(date.year, date.month, date.day)
if len(chart) < 1:
chart = get_weekend_chart(date.year, date.month, date.day)
if len(chart) < 1:
return None
return chart
def write_json_for_movies(date):
"""Write a file that contains all the movies that were on the charts for the given day.
The resulting file will be created in the "the-numbers/archive" folder.
The filename will be "YYYY-MM-DD.json"
Args:
date: target date
"""
movies = get_movies_for_day(date)
if movies is not None:
with open('{}/{}.json'.format("the-numbers/archive", date.isoformat()), 'w') as outfile:
json.dump(movies, outfile, indent=2)
print('Successfully finished {}'.format(date))
else:
print("{} -> no data".format(date))
def main():
args = parse_args()
start_date_split = args.start_date.split("-")
end_date_split = args.end_date.split("-")
start_date = datetime.date(int(start_date_split[0]),
int(start_date_split[1]), int(start_date_split[2]))
end_date = datetime.date(int(end_date_split[0]),
int(end_date_split[1]), int(end_date_split[2]))
# Normalize start_date to be closest preceding Friday
days_after_friday = (start_date.weekday()-4 + 7) % 7
date = start_date + datetime.timedelta(days=-days_after_friday)
while date < end_date:
write_json_for_movies(date)
date = date + datetime.timedelta(days=7)
if __name__ == '__main__':
main()
|
2372c2e8a3fe69f23ef31cb231d3b56af4e7fa6f
|
pjot/world-clock
|
/world-clock.py
| 700 | 3.765625 | 4 |
import sys
import pytz
import re
from datetime import datetime
DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
def get_timezones(partial):
regex = re.compile(re.escape(partial.lower()))
for timezone in pytz.all_timezones:
if re.search(regex, timezone.lower()):
yield timezone
def run(partial):
for timezone in get_timezones(partial):
tz = pytz.timezone(timezone)
print (datetime.now(tz).strftime(DATE_FORMAT), timezone)
if len(sys.argv) == 1:
print ("Usage: world-clock <timezone>")
print()
print ("world-clock matches the entered timezone against ")
#a list of all timezones and prints the local time \
#in all of them"
else:
run(sys.argv[1])
|
5f97043e4534bc4149b071e92f41fc06247a4eeb
|
kragniz/WindRunner
|
/Together-versions/Forebrain.py
| 7,433 | 3.546875 | 4 |
import math
import bank #delete when final
class Forebrain:
## sail setting!
def setSails(self):
# '''Sets the sails to the correct location for the wind data coming in. '''
currentWindHeading=bank.bank('currentWindHeading')
currentHeading=bank.bank('currentHeading')
print 'current wind heading is: ', currentWindHeading
print 'Current bot heading is: ', currentHeading
windAngle=math.fabs(currentWindHeading-currentHeading)
if windAngle>180:
windAngle=math.fabs(windAngle-360)
print 'calculated wind angle is:', windAngle
if windAngle<0:
print 'Error: negative wind angle!'
sailDesired=40
if windAngle<45:
print 'Bot is in irons!'
#outOfIrons()
if (windAngle<180) & (windAngle>45):
sailDesired=(.75*windAngle)-30
if windAngle>180:
sailDesired=90
print 'Error: wind angle over 180 degrees'
print 'Desired sail angle is: ', sailDesired
return sailDesired
## Going to ppoints!
def slope(self,p2,p1):
# '''gives the slope of the line to be followed
#tested to work 12:45 PM, 6/11/14 '''
m=float(p2[1]-p1[1])/float(p2[0]-p1[0])
#print 'Slope is: ' + str(m)
return m
def headingToPoint(self):
#'''gives the heading (angle in degrees from the +x axis) of the line to be followed'''
posCurrent=bank.bank('posCurrent') #robot's current position
posDesired=bank.bank('posDesired') #waypoint going toward
m=self.slope(posDesired,posCurrent)
angle=math.degrees(math.atan(m/1))
xcheck=(posDesired[0]-posCurrent[0])>0#if true, in I or IV
ycheck=(posDesired[1]-posCurrent[1])>0#if true, in I or II
#print 'x check: ' +str(xcheck) + '. y check:' +str(ycheck)+'.'
if (ycheck==True) & (xcheck==False): #quadrent 2
angle=90+math.fabs(angle)
#print 'Boat should be traveling into quadrent 2!'
if (xcheck==True) & (ycheck==False): #quadrent 4
angle=270+math.fabs(angle)
#print 'Boat should be heading into quadrent 4!'
if (xcheck==False) & (ycheck==False): #quadrent 3
angle =180+math.fabs(angle)
#print 'Boat should be heading into quadrent 3!'
#if quadrent 1, the angle doesn't need to be parsed.
return angle
def goToPoint(self):
# '''outputs the necessary, global heading in order to go toward a point'''
currentHeading=bank.bank('currentHeading')
headingtoPoint=headingToPoint()
print 'currentHeading' +str(currentHeading)
print 'headingtoPoint' +str(headingtoPoint)
desiredHeading=float(currentHeading+headingtoPoint)/2
print 'the desire heading is:'+str(desiredHeading)
return desiredHeading
## Following lines!
#def slope(self,posDesired,linstart):
# '''gives the slope of the line to be followed
#tested to work 12:45 PM, 6/11/14'''
# m=float(posDesired[1]-linstart[1])/float(posDesired[0]-linstart[0])
#print 'Slope is: ' + str(m)
# return m
def heading_line(self):
#'''gives the heading (angle in degrees from the +x axis) of the line to be followed'''
linstart=bank.bank('linstart')
posDesired=bank.bank('posDesired')
m=self.slope(posDesired,linstart)
angle=math.degrees(math.atan(m/1))
xcheck=(posDesired[0]-linstart[0])>0#if true, in I or IV
ycheck=(posDesired[1]-linstart[1])>0#if true, in I or II
#print 'x check: ' +str(xcheck) + '. y check:' +str(ycheck)+'.'
if (ycheck==True) & (xcheck==False): #quadrent 2
angle=90+math.fabs(angle)
#print 'Boat should be traveling into quadrent 2!'
if (xcheck==True) & (ycheck==False): #quadrent 4
angle=270+math.fabs(angle)
#print 'Boat should be heading into quadrent 4!'
if (xcheck==False) & (ycheck==False): #quadrent 3
angle =180+math.fabs(angle)
#print 'Boat should be heading into quadrent 3!'
#if quadrent 1, the angle doesn't need to be parsed.
return angle
def above_below_on_line(self):
# '''gives whether the bot is above, below, or on the line it should be following.
#tested to work at 13:14 on 6/11/14
# Based on: http://math.stackexchange.com/questions/324589/detecting-whether-a-point-is-above-or-below-a-slope'''
posCurrent=bank.bank('posCurrent')
posDesired=bank.bank('posDesired')
linstart=bank.bank('linstart')
m=self.slope(posDesired, linstart)
b=posDesired[1]-(m*posDesired[0])
check=m*posCurrent[0]+b
if check<posCurrent[1]:
print 'Bot is above the line'
return 'above'
if check>posCurrent[1]:
print 'Bot is below the line'
return 'below'
if check == posCurrent[1]:
print 'Bot is on the line!'
return 'on'
def followLine(self):
# '''Outputs the necessary, global heading for the robot to follow a line with specified endpoints'''
bot_posVlin=self.above_below_on_line()
lineheading=self.heading_line()
botheading=bank.bank('currentHeading')
print 'Line heading: '+str(lineheading)
print 'Bot heading: '+str(botheading)
#check through possible cases and assign the correct, desired, global heading accordingly
if (bot_posVlin=='above') & (botheading>lineheading): #above line and heading away from it.
print 'Bot above and heading away from line to be followed'
headDesired=((lineheading-botheading)/2)+lineheading
if (bot_posVlin=='below') & (botheading>lineheading): #below line and heading toward it.
print 'Bot below and heading away from line to be followed'
headDesired=((lineheading-botheading)/2)+lineheading
if (bot_posVlin=='below') & (botheading<lineheading): #below line and heading away from it.
print 'Bot below and heading toward from line to be followed'
headDesired=lineheading-math.fabs((lineheading-botheading)/2)
if (bot_posVlin=='above') & (botheading<lineheading): #above line and heading toward it.
print 'Bot above and heading toward from line to be followed'
headDesired=lineheading-math.fabs((lineheading-botheading)/2)
if bot_posVlin=='on': #on line! :)
print 'Bot is on the line to be followed!'
headDesired=lineheading
print 'The desired heading for the bot is:' + str(headDesired)
return headDesired
## Maintaining heading!
def mtnHeading(self):
# '''Keeps the robot on a desired heading. Output: desired, global heading'''
currentHeading=bank.bank('currentHeading')
desiredHeading=bank.bank('desiredHeading')
print 'Current heading: ' + str(currentHeading)
print 'Desired heading:' +str(desiredHeading)
delta=abs((currentHeading-desiredHeading)/2)
print 'Delta: '+ str(delta)
if currentHeading > desiredHeading:
desiredStearing=currentHeading-delta
print 'desired greater than current'
if currentHeading<desiredHeading:
desiredStearing=currentHeading+delta
print 'current greater than desired'
print 'the desired stearing angle is: ' + str(desiredStearing)
return desiredStearing
## Avoid obstacles!
def obsAvoid(self):
# '''works with IR sensor to avoid obstacles. Essentially integral control.'''
dist_to_object=bank.bank('dist_to_object') #distance to object from PIR/Sharp sensor
if dist_to_object >50:
print "Servo moving necessary so I don't hit a rock!"
stearingDesired = 30*dist_to_object/256;
#sailDesired = bank.bank('sailDesired') + 1
sailDesired=bank.sailDesiredF()
print 'desired stearing is: ' + str(stearingDesired) + ' degrees'
print 'desired sail is: ' + str(sailDesired) + ' degrees'
return (stearingDesired, sailDesired)
if __name__=='__main__':
FB=Forebrain()
FB.obsAvoid()
FB.mtnHeading()
FB.followLine()
FB.above_below_on_line()
FB.heading_line()
FB.headingToPoint()
FB.setSails()
|
58fa91e7dbe03df272358568ec50a4d9b4e832ab
|
pnads/advent-of-code-2020
|
/day_08.py
| 5,888 | 3.671875 | 4 |
"""--- Day 8: Handheld Halting ---
Your flight to the major airline hub reaches cruising altitude without incident.
While you consider checking the in-flight menu for one of those drinks that come
with a little umbrella, you are interrupted by the kid sitting next to you.
Their handheld game console won't turn on! They ask if you can take a look.
You narrow the problem down to a strange infinite loop in the boot code (your
puzzle input) of the device. You should be able to fix it, but first you need
to be able to run the code in isolation.
The boot code is represented as a text file with one instruction per line of
text. Each instruction consists of an operation (acc, jmp, or nop) and an
argument (a signed number like +4 or -20).
acc increases or decreases a single global value called the accumulator by the
value given in the argument. For example, acc +7 would increase the accumulator
by 7. The accumulator starts at 0. After an acc instruction, the instruction
immediately below it is executed next.
jmp jumps to a new instruction relative to itself. The next instruction to
execute is found using the argument as an offset from the jmp instruction; for
example, jmp +2 would skip the next instruction, jmp +1 would continue to the
instruction immediately below it, and jmp -20 would cause the instruction 20
lines above to be executed next.
nop stands for No OPeration - it does nothing. The instruction immediately
below it is executed next.
For example, consider the following program:
nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6
These instructions are visited in this order:
nop +0 | 1
acc +1 | 2, 8(!)
jmp +4 | 3
acc +3 | 6
jmp -3 | 7
acc -99 |
acc +1 | 4
jmp -4 | 5
acc +6 |
First, the nop +0 does nothing. Then, the accumulator is increased from 0 to 1
(acc +1) and jmp +4 sets the next instruction to the other acc +1 near the
bottom. After it increases the accumulator from 1 to 2, jmp -4 executes,
setting the next instruction to the only acc +3. It sets the accumulator to 5,
and jmp -3 causes the program to continue back at the first acc +1.
This is an infinite loop: with this sequence of jumps, the program will run
forever. The moment the program tries to run any instruction a second time, you
know it will never terminate.
Immediately before the program would run an instruction a second time, the
value in the accumulator is 5.
Run your copy of the boot code. Immediately before any instruction is executed
a second time, what value is in the accumulator?
"""
import pandas as pd
with open('input_files/input_day_08.txt', 'r') as f:
boot_code = [code.rstrip("\n").split(' ') for code in f.readlines()]
boot_code = [[code[0], int(code[1])] for code in boot_code]
df = pd.DataFrame(boot_code, columns=['command', 'value'])
df['times_visited'] = 0
df['order'] = 0
def run(df):
df_test = df.copy(deep=True)
accumulator = 0
index_to_go_to = 0
visited_twice = False
visit_order = 0
while not visited_twice and visit_order < df_test.shape[0]:
df_test.loc[index_to_go_to, 'order'] = visit_order
cmd = df_test.loc[index_to_go_to, 'command']
val = df_test.loc[index_to_go_to, 'value']
df_test.loc[index_to_go_to, 'times_visited'] += 1
if df_test.loc[index_to_go_to, 'times_visited'] == 2:
visited_twice = True
break
if cmd == 'acc':
accumulator += val
index_to_go_to += 1
elif cmd == 'jmp':
index_to_go_to += val
elif cmd == 'nop':
index_to_go_to += 1
visit_order += 1
return visited_twice, accumulator
def part1():
_, accumulator = run(df)
print(f'Part 1 | Accumulator: {accumulator}')
"""--- Part Two ---
After some careful analysis, you believe that exactly one instruction is
corrupted.
Somewhere in the program, either a jmp is supposed to be a nop, or a nop is
supposed to be a jmp. (No acc instructions were harmed in the corruption of
this boot code.)
The program is supposed to terminate by attempting to execute an instruction
immediately after the last instruction in the file. By changing exactly one jmp
or nop, you can repair the boot code and make it terminate correctly.
For example, consider the same program from above:
nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6
If you change the first instruction from nop +0 to jmp +0, it would create a
single-instruction infinite loop, never leaving that instruction. If you change
almost any of the jmp instructions, the program will still eventually find
another jmp instruction and loop forever.
However, if you change the second-to-last instruction (from jmp -4 to nop -4),
the program terminates! The instructions are visited in this order:
nop +0 | 1
acc +1 | 2
jmp +4 | 3
acc +3 |
jmp -3 |
acc -99 |
acc +1 | 4
nop -4 | 5
acc +6 | 6
After the last instruction (acc +6), the program terminates by attempting to
run the instruction below the last instruction in the file. With this change,
after the program terminates, the accumulator contains the value 8 (acc +1,
acc +1, acc +6).
Fix the program so that it terminates normally by changing exactly one jmp (to
nop) or nop (to jmp). What is the value of the accumulator after the program
terminates?
"""
def part2():
df_subset = df.loc[df.command.isin(['nop', 'jmp'])].copy(deep=True)
for row in df_subset.itertuples():
df_test = df.copy(deep=True)
if row.command == 'nop':
df_test.at[row.Index, 'command'] = 'jmp'
elif row.command == 'jmp':
df_test.at[row.Index, 'command'] = 'nop'
visited_twice, accumulator = run(df_test)
if not visited_twice:
print(f'Part 2 | Accumulator: {accumulator}')
break
part1() #1594
part2() #758
|
3c076f7848ffa0bcd5446e4c329e636947d9b825
|
munishdeora/python_training_2019
|
/Day 4/centered.py
| 1,014 | 4.09375 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 8 18:52:28 2019
@author: de
"""
"""
Code Challenge
Name:
Centered Average
Filename:
centered.py
Problem Statement:
Return the "centered" average of an array of integers, which we'll say is the
mean average of the values, except ignoring the largest and smallest values in the array.
If there are multiple copies of the smallest value, ignore just one copy,
and likewise for the largest value. Use int division to produce the final average.
You may assume that the array is length 3 or more.
Take input from user
Input:
1, 2, 3, 4, 100
Output:
3
"""
usr_ip=input("Enter the input : ")
list1=usr_ip.split(',')
listf=[]
for char in list1:
x=int(char)
listf.append(x)
#
list2=[]
for char in listf:
if char not in list2:
x=int(char)
list2.append(x)
list2.sort()
list2.pop()
del list2[0]
le=len(list2)
x=0
for item in list2:
x=x+item
avg=x/le
print(int(avg))
|
56900ec1db4cb878628d4567e6f2874614ef6978
|
Artur-Aghajanyan/VSU_ITC
|
/Lusine_Shahbazyan/python/fibonacci.py
| 406 | 3.9375 | 4 |
n = int(input("n = "))
FibonacciArray = [0,1]
def findFibonacciNumber(n):
if n < 0:
print("Incorrect input")
elif n == 1:
return FibonacciArray[0]
elif n == 2:
return FibonacciArray[1]
else:
fibNumber = findFibonacciNumber(n-1)+findFibonacciNumber(n-2)
FibonacciArray.append(fibNumber)
return fibNumber
print(findFibonacciNumber(n))
|
44ccb8a3cf11a39b326454e0a1cecfa453c4e732
|
Leziak/Leetcode
|
/Python/PalindromeLinkedList.py
| 682 | 3.9375 | 4 |
# Used a list because I wasn't explicitly asked to reverse the linked list (which I did in another problem, only to verify if the linked list is a palindrome or not.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
nodes_list = []
if not head:
return True
while head:
nodes_list.append(head.val)
head = head.next
return nodes_list == nodes_list[::-1]
|
a7612079570049eeb7e6004b7ac0755421696913
|
janellecueto/HackerRank
|
/Python/Strings/StringValidators.py
| 323 | 3.734375 | 4 |
import re
if __name__ == '__main__':
s = input()
print(bool(re.search(r'\w', s))) #alphanumeric
print(bool(re.search("[A-Za-z]", s))) #has letters
print(bool(re.search(r'\d', s))) #has numbers
print(bool(re.search("[a-z]", s))) #has lowercase
print(bool(re.search("[A-Z]", s))) #has uppercase
|
103faacdfdf8238ec3b83556953f0fcf2db8af60
|
grzegorz-rogalski/pythonGrogal
|
/zaj1/script6.py
| 302 | 3.96875 | 4 |
'''
listy(edytownalne) i krotki[tuple](niezmienne)
'''
l=[1,2,'element',3.14]
'''print l
k=(1,2,'element', 3.14)
print k
print l[1]
print k[1]
print l[1:3]
print k[:-2]
'''
print 3 in l #sprawdza czy istnieje
l[0]=3
print l
#k[0]=3 NIE MOZNA ZMIENIAC WARTOSCI
#print k
l[1:3]=['a', 'b']
print l
|
cb447f084119f5c16b99f7e54a9fd1990c1af90b
|
manjot-baj/My_Python_Django
|
/Python Programs/oop_inheritance_3.py
| 2,738 | 3.8125 | 4 |
# method overriding
class Phone: # base / parent class
def __init__(self,brand,model,price):
self.brand = brand
self.model = model
self.price = max(price,0)
@property
def specification(self):
return f"{self.brand} {self.model} {self.price}"
def make_call(self,phone_no):
print(f"Calling...{phone_no}")
@property
def full_name(self):
return f"{self.brand} {self.model}"
class Smartphones(Phone): # derived / child class
def __init__(self,brand,model,price,ram,internal_memory,rear_camera):
super().__init__(brand,model,price)
self.ram = ram
self.internal_memory = internal_memory
self.rear_camera = rear_camera
@property
def full_name(self):
return f"Brand : {self.brand}, Model : {self.model}, Ram : {self.ram}, Internal Space : {self.internal_memory}, Camera : {self.rear_camera} "
class Gaming_smartphones(Smartphones): # Another derived / child class
def __init__(self,brand,model,price,processor,ram,internal_memory,rear_camera,front_camera):
super().__init__(brand,model,price,ram,internal_memory,rear_camera)
self.rear_camera = rear_camera
self.front_camera = front_camera
self.processor = processor
# @property
# def full_name(self):
# return f"Brand : {self.brand}, Model : {self.model}, Processor : {self.processor}, Ram : {self.ram}, Internal Space : {self.internal_memory}, Rear Camera : {self.rear_camera}, front camera : {self.front_camera} "
Phone1 = Phone("Nokia","3310",500)
Phone2 = Smartphones("Samsung","j2",7500,"1gb","8gb","5mp")
Phone3 = Gaming_smartphones("Asus","ZenPro",25000,"Hellios-930","12gb","128gb","25mp","15mp")
print(Phone3.full_name)
# Method resolution
# In Python to see methd resolution of a class
# type help(classname)
# ex :
# print(help(Gaming_smartphones))
# method resolution for Gaming_smartphones
# | Method resolution order:
# | Gaming_smartphones
# | Smartphones
# | Phone
# | builtins.object
# if your object of class gaming smartphones calls any method
# then python will search for method according to that class
# method resolution order
# means python will search for method first in that class if
# its not available then next class in method resolution order
# of Gamingsmartphone
# builtinsobject is a class in python
# if you create a class in python
# you by default inherit that class from bultinsobject
# isinstance() and issubclass() methods
print(isinstance(Phone3,Gaming_smartphones))
# this method tells that whether this object is of this class
print(issubclass(Gaming_smartphones,Phone))
# this method tells that whether this class is a subclass of this class
|
50c5887593d61baa9342ff4b493735d1e974ba9c
|
MrHamdulay/csc3-capstone
|
/examples/data/Assignment_5/tsnvho001/question3.py
| 756 | 4.09375 | 4 |
#Program to calculate permutations
#Tsanwani Vhonani
#15 APRIL 2014
import mymath
def fact():
#get number 'n' from user
n=input("Enter n: \n")
while not n.isdigit():
n=input("Enter n: \n")
n=eval(n)
#findng the factorial of n
n_fact=1
for factor in range(n,1,-1):
n_fact=n_fact*factor
#get number 'k' from user
k=input("Enter k:\n")
while not k.isdigit():
k=input("Enter k:\n")
k=eval(k)
#finding the factorial of n-k
k_fact=1
l=n-k
for factor in range(l,1,-1):
k_fact=k_fact*factor
print("Number of permutations:",n_fact//k_fact)
fact()
|
f68758607c2448e334b351caf17664b7988bf8bf
|
meliezer124/pythonWorkbook
|
/E1-E33/E5.py
| 529 | 3.859375 | 4 |
## Bottle Deposits ##
# Get amount of each type
liter_or_less = float(input("How many containers do you have that hold a liter or less?"))
more_than_liter = float(input("How many containers do you have that hold more than a liter?"))
#Calculate invididual typed deposits
amt_less = liter_or_less * 0.10
amt_more = more_than_liter * 0.25
# Calculate total deposit
deposit = amt_less + amt_more
# return deposit
print("Your refund for these bottles is : ${0:.2f}".format(deposit)) #{0:.2f} is what limits the float to 2 places!
|
79dbf87cc7f5563cf24ef0ceeded6be5a27317c4
|
renchao7060/studynotebook
|
/基础学习/p26.py
| 2,803 | 3.890625 | 4 |
#_*_coding:UTF-8_*_
# 形参 def test(x,y)
# 实参test(1,2)
# 位置参数def test(x,y)
# 关键字参数 def test(x,y=1) or test(x,y=1)
# 默认参数 def test(x,y=1)
# 可选参数 def (x,y,*args,**kwargs)
def test1():
print('in the test1')
def test2():
print('in the test2')
return 0
x=test1()
y=test2()
print(x,y)
print('*'*60)
# in the test1
# in the test2
# None 0
def test3(x,y):
print(x,y)
test3(1,2)
test3(2,1)
test3(x=1,y=2)
test3(y=2,x=1)
test3(1,y=2)
#test3(y=2,1)#SyntaxError: positional argument follows keyword argument#关键值参数一定要放在位置参数之后
print('*'*60)
# def test4(x=1,y):#关键值参数一定要放在位置参数之后
# print(x,y)
def test5(x,y=2):##默认参数
print(x,y)
test5(2)#调用的时候针对默认参数可以不添加
test5(2,3)
test5(x=2)
print('*'*60)
def test6(x,y,*args,**kwargs):#可选参数*args接收位置参数以元组形式输出,*kwargs接收关键字参数以字典的方式输出
print(x,y,args,kwargs)
test6(1,2)
test6(1,2,3,4,5)
test6(1,2,3,4,5,name='renchao',gender='M',age=30)
test6(1,2,name='renchao',gender='M',age=30)
test6(1,2,**{'name':'renchao','gender':'M','age':30})
print('*'*60)
# 1 2 () {}
# 1 2 (3, 4, 5) {}
# 1 2 (3, 4, 5) {'name': 'renchao', 'age': 30, 'gender': 'M'}
# 1 2 () {'name': 'renchao', 'age': 30, 'gender': 'M'}
# 1 2 () {'name': 'renchao', 'age': 30, 'gender': 'M'}
name='renchao'#全局变量
def test7():
name='zhenzhen'#局部变量
print(name)#zhenzhen
# name='zhenzhen'
# print(name)
test7()
print(name)#renchao
print('*'*60)
name='A'#全局变量为字符串或是数字的时候不建议使用此种方式进行修改
def test8():
global name#指定在函数内部调用全局变量
name='B'#在函数内部修改全局变量
print(name)#B
test8()
print(name)#B
print('*'*60)
def test8():
global name#指定在函数内部调用全局变量,而全局变量未在全局显是建立,这种方法杜绝使用
name='B'#在函数内部修改全局变量
print(name)#B
test8()
print(name)#B
print('*'*60)
#通过函数可修改全局变量为字典,列表,集合等数据
dict1={'name':'renchao','gender':'man'}
list1=[1,2,3,4,5]
set1={1,2,3,5}
def test9():
print(dict1['name'])#renchao
print(list1[0])#1
print(set1.pop())#1
dict1['name']='zhenzhen'
list1[0]=10
set1.add(10)
print(dict1)
print(list1)
print(set1)
test9()
print(dict1)
print(list1)
print(set1)
# renchao
# 1
# 1
# {'name': 'zhenzhen', 'gender': 'man'}
# [10, 2, 3, 4, 5]
# {10, 2, 3, 5}
# {'name': 'zhenzhen', 'gender': 'man'}
# [10, 2, 3, 4, 5]
# {10, 2, 3, 5}
# 局部变量是字符串或是数字形式的,修改局部变量不能自动改全局变量
# 局部变量是字典,集合,列表形式的,修改局部变量能自动改全局变量
|
0ef181fc65ef4d9507291281727156896440e8d7
|
antaramunshi/GUIwithTkinter
|
/script1.py
| 764 | 3.90625 | 4 |
from tkinter import *
window = Tk()
def km_to_miles():
miles = float(e1_value.get())*.6
t1.insert(END, miles)
def kg_conversion():
grams = float(e1_value.get())*1000
t1.insert(END, grams)
pounds = float(e1_value.get())*2.20462
t2.insert(END,pounds)
ounces = float(e1_value.get())*35.274
t3.insert(END, ounces)
b1 = Button(window, text='Execute',command=kg_conversion)
b1.grid(row=0,column=3)
label = Label(window, text='Kg')
label.grid(row=0,column=1)
e1_value=StringVar()
e1=Entry(window,textvariable=e1_value)
e1.grid(row=0,column=2)
t1=Text(window,height=1,width=20)
t1.grid(row=1,column=1)
t2=Text(window,height=1,width=20)
t2.grid(row=1,column=2)
t3=Text(window,height=1,width=20)
t3.grid(row=1,column=3)
window.mainloop()
()
|
d29289c3ca31ce6d5ffc28140dca4c0f27577ab3
|
waltlrutherfordgmailcom/CTI110
|
/P4T1C_Rutherford.py
| 566 | 3.796875 | 4 |
# This program draws a snowflake using a nested loop.
# 3/14/2019
# CTI-110 Bonus Lab:P4T1C - Snowflake
# Walter Rutherford
import turtle
t = turtle.Turtle()
def stick ():
for x in range (3):
for x in range (1):
t.forward (30)
t.right(45)
t.forward(30)
t.backward(30)
t.left(45)
t.left(45)
t.forward (30)
t.backward (30)
t.right (45)
for x in range (8):
t.backward (90)
t.right (45)
stick ()
|
19ebac2f2c38ccfa9750249519cfdcd4916deec8
|
jpog99/ITE_1014
|
/190327_w4/190327_w4_1-2.py
| 118 | 3.796875 | 4 |
print('Input a number: ')
num=input()
n=1
while (n<int(num)+1):
if (n%2!=0)or(n%4==0):
print(n)
n+=1
|
77298c4216549654c7306e6b0905fa508aea4388
|
acbarnett/advent-of-code-2020
|
/02/a.py
| 261 | 3.625 | 4 |
from lib import count_valid
filename = "input-a.txt"
def check_validity(low, high, character, password):
c = password.count(character)
return c >= low and c <= high
count_of_valid_rules = count_valid(filename, check_validity)
print(count_of_valid_rules)
|
25974294dcda1fbf5035e609cb1455c83831b534
|
yuannan/python
|
/yuannan/pizzashop/start.py
| 22,223 | 3.671875 | 4 |
#!/usr/bin/env python
#
# V0.1.0 Alpha, Functional, but missing some value checking ext.
# "fully functional"
#
# Importing modules and defining essentails
import csv
import operator
import sys
from time import gmtime, strftime, sleep
#debug=True
# Defining all the functions
def start():
print("Welcome to Big Rod's Pizza!")
import_files()
if "debug" in globals():
dev_menu()
cli(False)
def dev_menu():
# Print out the menu in pure python "list" or array form
for i in range(0,len(menu)):
print("\n")
for b in menu[i]:
print(b)
def import_files():
global menu
global customerOrder
menu = [[],[],[],[],[]]
customerOrder = []
submenus=["starters", "pizzas", "drinks", "desserts", "extras"]
for i in range(0,len(submenus)):
for item in csv.reader(open("etc/"+submenus[i]+".csv")):
menu[i].append(item)
def cli(prompt):
if prompt:
#allows the user to read the previouse text easier
pause=input("\n\n\nPress [ENTER] to return")
print("\n\n\nWhat would you like to do?\n")
print("1) Print Menu")
print("2) Start Ordering/Change your order")
print("3) Check Order")
print("4) Checkout and Print")
print("9) Help with this app")
print("0) EXIT")
menuTemp=input("")
try:
menuOption=int(menuTemp)
except ValueError:
print("Thats's not even a number!")
cli(False)
if menuOption in range(0,5) or menuOption == 9:
menuOption=str(menuOption)
if menuOption == "0":
print("Goodbye!")
sys.exit()
elif menuOption == "1":
print_prompt()
elif menuOption == "2":
order()
elif menuOption == "3":
print_Order(False)
elif menuOption == "4":
checkout()
elif menuOption == "9":
print_help()
else:
print("Error, please check the cli menu")
else:
print("There is no option {}...".format(menuOption))
cli(False)
def print_help():
print("\nThis is \"Big Rod's Pizza\" ordering app")
print("It's made for python 3.X")
print("The pizzas are made fresh in:")
print("Small - 9 Inches")
print("Medium - 11 Inches")
print("Large - 13 Inches")
print("Monster - 15 Inches")
print("\nAnd the drinks are avalaiable in:")
print("Cans - 330ml")
print("Bottles - 500ml")
print("2Liters - 2000ml")
print("The rest is only avaliable in one size")
def print_prompt():
print("\n\n\nWhat do you want print?\n")
print("0) For all of the menu")
print("1) Starters")
print("2) Pizzas")
print("3) Drinks")
print("4) Desserts")
print("5) Extras")
areaTemp=input("")
try:
area=int(areaTemp)
except ValueError:
print("Thats's not even a number!")
print_prompt()
if area in range(0,6):
print("in area 0-5")
if area == 0:
for submenu in range(0,5):
print_menu(submenu)
else:
print_menu(area-1)
else:
print("There is no submenu section {}...".format(area))
print_prompt()
def print_menu(menuIndex):
menuIndexStr=str(menuIndex)
simpleMenu=["0","3","4"]
if menuIndexStr in simpleMenu:
if "debug" in globals():
print("menuIndex is {} and it should print out: Starters, Desserts and Extras".format(menuIndex))
banner(menuIndex)
for item in range(0,len(menu[menuIndex])):
print(menu[menuIndex][item][0])
print("{:>5}>{}".format("",menu[menuIndex][item][1])) # Description for the item
print(" Price:",currency(menu[menuIndex][item][2]))
elif menuIndexStr == "1":
banner(menuIndex)
if "debug" in globals():
print("menuIndex is {} and It should be printing out ONLY pizzas".format(menuIndex))
for item in range(0,len(menu[menuIndex])):
print(menu[menuIndex][item][0])
print("{:>5}>{}".format("",menu[menuIndex][item][1]))
print("{:>20}: {:>6}".format("Small",currency(menu[menuIndex][item][2])))
print("{:>20}: {:>6}".format("Medium",currency(menu[menuIndex][item][3])))
print("{:>20}: {:>6}".format("Large",currency(menu[menuIndex][item][4])))
print("{:>20}: {:>6}".format("Monster",currency(menu[menuIndex][item][5])))
elif menuIndexStr == "2":
banner(menuIndex)
if "debug" in globals():
print("menuIndex is {} and It should be printing out ONLY drinks".format(menuIndex))
for item in range(0,len(menu[menuIndex])):
print(menu[menuIndex][item][0])
print("{:>5}>{}".format("",menu[menuIndex][item][1]))
print("{:>20}: {:>6}".format("Cans",currency(menu[menuIndex][item][2])))
print("{:>20}: {:>6}".format("Bottles",currency(menu[menuIndex][item][3])))
print("{:>20}: {:>6}".format("2Liters",currency(menu[menuIndex][item][4])))
else:
print("This should have never happened!\nCheck function \"print_menu()\"")
def banner(subMenu):
print("\n==============================")
if subMenu == 0:
print("======== STARTERS ========")
elif subMenu == 1:
print("======== PIZZAS ========")
elif subMenu == 2:
print("======== DRINKS ========")
elif subMenu == 3:
print("======== DESSERTS ========")
elif subMenu == 4:
print("======== EXTRAS ========")
else:
print("ERROR!!! Check the function \"print_menu()\" line 3+")
print("==============================\n")
def currency(money):
money=str(money) # Converts to a string for later handeling
whole=money[:-2]
units=money[-2:]
if len(whole) < 1:
whole="0"
while len(units) < 2:
units="0"+units
return("£"+whole+"."+units)
def order():
print("\n\n\nWhat would you like to order?")
print("1) Starters")
print("2) Pizzas")
print("3) Drinks")
print("4) Desserts")
print("5) Extras")
print("7) Print menu")
print("8) Print current items")
print("9) Remove an item")
print("0) Return")
menuTemp = input("")
try:
menuOption=int(menuTemp)
except ValueError:
orderError("That's not even a number!",order,False)
if menuOption in range(1,6) or menuOption in range(8,10) or menuOption == 0:
menuOption=str(menuOption)
if menuOption == "0":
cli(False)
elif menuOption == "9":
removeItem()
elif menuOption == "8":
print_Order(False)
elif menuOption == "7":
print_prompt()
elif menuOption == "1" or menuOption == "4" or menuOption == "5":
orderBasics(menuOption)
elif menuOption == "2":
orderPizzas(menuOption)
elif menuOption == "3":
orderDrinks(menuOption)
else:
print("Error, this should not have happened, Error in function \"order()\"")
else:
print("There is no option {}...".format(menuOption))
order()
def orderError(errorName,command,menuOption):
print("Error!!!\n"+errorName)
if command == "cli":
cli(False)
elif command == "order":
order()
elif command == "orderBasics":
orderBasics(menuOption)
elif command == "orderPizzas":
orderPizzas(menuOption)
elif command == "orderDrinks":
orderDrinks(menuOption)
else:
cli(False)
def orderBasics(menuOption):
# Ordering for item that have a set value e.g. Starters,
menuOption=int(menuOption)
print("\n")
print("{:<5}{:<30}{:>10}".format("#Num","Item Name","Price"))
print("="*60)
for item in range(len(menu[menuOption-1])):
print("{:<5}{:<30}{:>10}".format(
str(item+1)+")",menu[menuOption-1][item][0],currency(menu[menuOption-1][item][2])))
currentItemTemp=input("\nItem number: ")
try:
currentItem=int(currentItemTemp)-1
except ValueError:
orderError("Item not a number","orderBasics",menuOption)
if currentItem < 0:
orderError("Item number less than 1",'orderBasics',menuOption)
elif currentItem >= len(menu[menuOption-1]):
orderError("Item number higher total items",'orderBasics',menuOption)
amount=input("Amount: ")
try:
amount=int(amount)
except ValueError:
orderError("Amount of item is not a number!",'orderBasics',menuOption)
if amount <= 0:
orderError("Amount of item is 0 or lower!",'orderBasics',menuOption)
else:
comment=str(input("Enter a comment, type in \"C\" to cancel or leave blank to confirm\n"))
if comment.lower() == "c":
print("Cancelling item...")
orderBasics(menuOption)
else:
currentItemList=[amount,menuOption-1,currentItem,"\n"+comment,menu[menuOption-1][currentItem][2]]
customerOrder.append(currentItemList)
if 'debug' in globals():
print(customerOrder)
def orderPizzas(menuOption):
# Ordering for Pizzas only, due to it's funky multi-sized formatting
menuOption=int(menuOption)
print("\n")
print("{0:<5}{1:<30}{2:>10}{3:>10}{4:>10}{5:>10}".format("#Num","Pizza Flavours","Small","Medium","Large","Monster"))
print("="*95)
for item in range(len(menu[menuOption-1])):
print("{:<5}{:<30}{:>10}{:>10}{:>10}{:>10}".format(
str(item+1)+")",
menu[menuOption-1][item][0],
currency(menu[menuOption-1][item][2]),
currency(menu[menuOption-1][item][3]),
currency(menu[menuOption-1][item][4]),
currency(menu[menuOption-1][item][5])))
currentItemTemp=input("\nItem number: ")
try:
currentItem=int(currentItemTemp)-1
except ValueError:
orderError("Item not a number",'orderPizzas',menuOption)
if currentItem < 0:
orderError("Item number less than 1",'orderPizzas',menuOption)
elif currentItem >= len(menu[menuOption-1]):
orderError("Item number higher total items",'orderPizzas',menuOption)
# Size selection and verification system
print("What size would you like?")
print("1) Small")
print("2) Medium")
print("3) Large")
print("4) Monster")
size=input("Size: ")
try:
size=int(size)
except ValueError:
orderError("The size was not a number!",'orderPizzas',menuOption)
if size in range(1,5):
if size == 1:
sizeComment="Small"
elif size == 2:
sizeComment="Medium"
elif size == 3:
sizeComment="Large"
elif size == 4:
sizeComment="Monster"
else:
orderError("Critical error in size checking, line ~321",'orderPizzas',menuOption)
else:
if size <= 0:
orderError("Size was 0 or smaller",'orderPizzas',menuOption)
elif size >4:
orderError("Size was larger than 4(Maximum size)",'orderPizzas',menuOption)
else:
orderError("Critical error in size checking, line ~315",'orderPizzas',menuOption)
# Amount selection system
amount=input("Amount: ")
try:
amount=int(amount)
except ValueError:
orderError("Amount of item is not a number!",'orderPizzas',menuOption)
if amount <= 0:
orderError("Amount of item is 0 or lower!",'orderPizzas',menuOption)
else:
comment=str(input("Enter a comment, type in \"C\" to cancel or leave blank to confirm\n"))
if comment.lower() == "c":
print("Cancelling item...")
orderPizzas(menuOption)
else:
if comment == "":
currentItemList =[amount,menuOption-1,currentItem,sizeComment,menu[menuOption-1][currentItem][size+1]]
else:
currentItemList =[amount,menuOption-1,currentItem,sizeComment+"\n"+comment,menu[menuOption-1][currentItem][size+1]]
customerOrder.append(currentItemList)
if 'debug' in globals():
print(customerOrder)
def orderDrinks(menuOption):
# Ordering for Drinks only, due to it's funky size formatting
menuOption=int(menuOption)
orderError=False
print("\n")
print("{0:<5}{1:<30}{2:>10}{3:>10}{4:>10}".format("#Num","Item Name","Can","Bottle","2Liters"))
print("="*85)
for item in range(len(menu[menuOption-1])):
print("{0:<5}{1:<30}{2:>10}{3:>10}{4:>10}".format(
str(item+1)+")",
menu[menuOption-1][item][0],
currency(menu[menuOption-1][item][2]),
currency(menu[menuOption-1][item][3]),
currency(menu[menuOption-1][item][3])))
currentItemTemp=input("\nItem number: ")
try:
currentItem=int(currentItemTemp)-1
except ValueError:
orderError("Item not a number",'orderDrinks',menuOption)
if currentItem < 0:
orderError("Item number less than 1",'orderDrinks',menuOption)
elif currentItem >= len(menu[menuOption-1]):
orderError("Item number higher total items",'orderDrinks',menuOption)
# Size selection and verification system
print("What size would you like?")
print("1) Can")
print("2) Bottle")
print("3) 2Liters")
size=input("Size: ")
try:
size=int(size)
except ValueError:
orderError("The size was not a number!",'orderDrinks',menuOption)
if size in range(1,4):
if size == 1:
sizeComment="Can"
elif size == 2:
sizeComment="Bottle"
elif size == 3:
sizeComment="2Liters"
else:
orderError("Critical error in size checking, line ~381",'orderDrinks',menuOption)
else:
if size <= 0:
orderError("Size was 0 or smaller",'orderDrinks',menuOption)
elif size >3:
orderError("Size was larger than 3(Maximum size)",'orderDrinks',menuOption)
else:
orderError("Critical error in size checking, line ~388",'orderDrinks',menuOption)
amount=input("Amount: ")
try:
amount=int(amount)
except ValueError:
orderError("Amount of item is not a number!",'orderDrinks',menuOption)
if amount <= 0:
orderError("Amount of item is 0 or lower!",'orderDrinks',menuOption)
if orderError != False:
print("orderError: {}".format(orderError))
order()
else:
comment=str(input("Enter a comment, type in \"C\" to cancel or leave blank to confirm\n"))
if comment.lower() == "c":
print("Cancelling item...")
orderDrinks(menuOption)
else:
if comment == "":
currentItemList =[amount,menuOption-1,currentItem,sizeComment,menu[menuOption-1][currentItem][size+1]]
else:
currentItemList =[amount,menuOption-1,currentItem,sizeComment+"\n"+comment,menu[menuOption-1][currentItem][size+1]]
customerOrder.append(currentItemList)
if 'debug' in globals():
print(customerOrder)
def print_Order(numbers):
totalCost=0
if "debug" in globals():
print(customerOrder)
for i in range(len(customerOrder)):
print(customerOrder[i])
for orderedItem in range(len(customerOrder)):
if numbers:
print("{0}) {1} {2}".format(
orderedItem+1, #Item number for identification
menu[customerOrder[orderedItem][1]][customerOrder[orderedItem][2]][0], # name
customerOrder[orderedItem][3])) # size (built into the comment)
else:
print("{0} {1}".format(
menu[customerOrder[orderedItem][1]][customerOrder[orderedItem][2]][0],
customerOrder[orderedItem][3]))
print("{0:<3}X {1:>5}{2:>50}".format(
customerOrder[orderedItem][0], # amount of items
currency(customerOrder[orderedItem][4]), # Single item cost
currency((int(customerOrder[orderedItem][0])*int(customerOrder[orderedItem][4])))))
totalCost+=int(customerOrder[orderedItem][0])*int(customerOrder[orderedItem][4])
if numbers:
print("Pick an item to remove")
else:
print("\nTotal: {}".format(currency(totalCost)))
def removeItem():
print_Order(True)
itemToRemove=input("Item to remove: ")
try:
itemToRemove=int(itemToRemove)
except ValueError:
print("It's not a number!")
removeItem()
if itemToRemove in range(1,(len(customerOrder)+1)):
del customerOrder[itemToRemove-1]
print("Item deleted.\nHere is your current order")
print_Order(False)
else:
if itemToRemove <= 0:
print("There is no item 0 or below...")
removeItem()
else:
print("There is not item {}, it only goes up to {}!".format(str(itemToRemove),str(len(customerOrder+1))))
removeItem()
def checkout():
global checkoutTime
checkoutTime=strftime("%H%M%S", gmtime())
print("Are you sure you want to place this order? After you do so you cannot change it!")
confirm=input("\"Y\" for yes and \"N\" for no\n")
if confirm.lower() == "y":
sortByIndex(customerOrder,1)
print_Order(False)
orderToTxt()
print("Your order will arive in:")
countdown(20*60)
elif confirm.lower() == "n":
print("Okay.")
cli(False)
else:
print("Sorry \"Y\" or \"N\" only")
checkout()
def countdown(t):
while t > 0:
mins, secs = divmod(t, 60)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
print(timeformat, end='\r')
sleep (1)
t -= 1
print('Times Up!!!\nYour Delivery should be here now!\nIf not call \"Big Rod\'s Pizza Directly at 999\"')
def orderToTxt():
# A modded version of "print order"
outputFile=open("orderOutput.txt","w")
totalCost=0
for orderedItem in range(len(customerOrder)):
outputFile.write("\n") # gives a cushion so the outlook is easier it read
outputFile.write("{0} {1}\n".format(
menu[customerOrder[orderedItem][1]][customerOrder[orderedItem][2]][0],
customerOrder[orderedItem][3]))
outputFile.write("{0:<3}X {1:>5}{2:>30}\n".format(
customerOrder[orderedItem][0], # amount of items
currency(customerOrder[orderedItem][4]), # Single item cost
currency((int(customerOrder[orderedItem][0])*int(customerOrder[orderedItem][4])))))
totalCost=totalCost+(int(customerOrder[orderedItem][0])*int(customerOrder[orderedItem][4]))
outputFile.write("\nTotal: {}".format(currency(totalCost)))
outputFile.close()
def sortByIndex(inputList, index):
inputList.sort(key=operator.itemgetter(index))
#Starts the "start" function and actully boots the program
start()
|
2b9ae74fa9aef8c558ddfc1f657082d85103fec8
|
shreyakapadia10/PythonProjects
|
/Python to Exe/print_n_numbers.py
| 83 | 3.890625 | 4 |
n = int(input("Enter any number: "))
for i in range(1, n+1):
print(i, end=' ')
|
aa4729309fe3422ae317da824401e296a441cfb0
|
nickradford/advent-of-code
|
/03/03-toboggan-trajectory.py
| 842 | 4.21875 | 4 |
#!/usr/bin/env python3
# https://adventofcode.com/2020/day/3
# With the map repeating to the right infinitely, calculate the number of trees encountered for a given slope (3, 1) (right, down)
import math
def calculate_trees_for_slope(slope, grid):
x, y = slope
width = len(grid[0]) - 1
posX, posY = 0, 0
tree_encounters = 0
for i in range(0, len(grid), y):
obj = grid[i][posX % width]
if obj == "#":
tree_encounters += 1
posX += x
posY += y
return tree_encounters
with open("03-input.txt") as f:
grid = f.readlines()
slopes = [
[1, 1],
[3, 1],
[5, 1],
[7, 1],
[1, 2]
]
trees_in_slopes = [calculate_trees_for_slope(slope, grid) for slope in slopes]
tree_encounters = math.prod(trees_in_slopes)
print("No. of Trees Encountered: {}".format(tree_encounters))
|
4177b3ca3ecc39a028d92a67688a31b0fd27fd3a
|
zncepup/web2
|
/tttttttt.py
| 426 | 3.8125 | 4 |
def month2year(string):
strnyr=''
m=float(string)
year=m//12.0
print(year)
if year!=0:
strnyr=str(int(year))+'年'
month=m%12.0
if int(month)!=0:
strnyr = strnyr + str(int(month)) + '个月'
day=month-int(month)
day=day*30
day=round(day)
if day!=0:
strnyr=strnyr+str(day)+'天'
return strnyr
if __name__ == '__main__':
a=month2year('7')
print(a)
|
fc8374e69809d637f80de4068bd8194ef775d5ed
|
abmish/pyprograms
|
/100Py/Ex7.py
| 663 | 4.15625 | 4 |
"""
Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th
row and j-th column of the array should be i*j.
Note: i=0,1.., X-1; j=0,1..,Y-1.
Example
Suppose the following inputs are given to the program:
3,5
Then, the output of the program should be:
[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]
"""
user_in = raw_input("Input two digits separated by comma: ").split(",")
rows = int(user_in[0])
columns = int(user_in[1])
matrix = [[0 for col in range(columns)] for row in range(rows)]
for row in range(rows):
for col in range(columns):
matrix[row][col] = row * col
print matrix
|
bd7defe02ca713c351cb45058ca3294f0dcbef69
|
goblinbat/CodeWars_comp
|
/02.py
| 3,001 | 4.125 | 4 |
def tribonacci(signature, n):
'''
input: set of starting numbers, how many numbers you want returned\n
output: the original sequence (unless n < len(signature)),
plus continuation in which the last 3 numbers in sequence
are added together and added to sequence (repeat until
len(sequence) = n)
'''
seq = []
if n == 0:
return seq
else:
for num in signature:
if len(seq) != n:
seq.append(num)
while len(seq) < n:
x = sum(seq[-3:])
seq.append(x)
return seq
def find_uniq(arr):
'''
given list of repeating numbers, returns the one number that
is not repeated
'''
x = arr[0]
y = arr[1]
z = arr [2]
if x != y and y == z:
return x
elif x == y and x != z:
return z
elif x != y and y != z:
return y
else:
for num in arr:
if num != x:
return num
def likes(names):
'''
given a list of names, returns up to the first 3
names
'''
if len(names) == 0:
return 'no one likes this'
elif len(names) == 1:
return f"{names[0]} likes this"
elif len(names) == 2:
return f"{names[0]} and {names[1]} like this"
elif len(names) == 3:
return f"{names[0]}, {names[1]} and {names[2]} like this"
else:
return f"{names[0]}, {names[1]} and {len(names) - 2} others like this"
def persistence(n):
'''
given a number, multiplies its digits together,
then multiplies the digits of the product until a
single digit product is produced. \n
Returns the number of times it was multiplied
'''
m = str(n)
inst = 0
if len(m) == 1:
return 0
while len(m) > 1:
product = 1
for num in m:
num = int(num)
product *= num
inst += 1
m = str(product)
return inst
def fizzbuzz_solution_ex(number):
'''
given a number, returns the sum of all multiples of
3 or 5 less than that number (not inclusive)
ex: 15 => 3 + 5 + 6 + 9 + 10 + 12 => 45
'''
add = []
for num in range(number):
if num % 3 == 0 or num % 5 == 0:
add.append(num)
return sum(add)
def fizzbuzz_solution_inc(number):
'''
given a number, returns the sum of all multiples of
3 or 5 less than or equal to that number (inclusive)
ex: 15 => 3 + 5 + 6 + 9 + 10 + 12 + 15 => 60
'''
add = []
for num in range(number+1):
if num % 3 == 0 or num % 5 == 0:
add.append(num)
return sum(add)
def comp_DNA_strand(dna):
'''
returns complementary dna strand
'''
comp = []
for base in dna:
if base == "A":
comp.append("T")
elif base == "C":
comp.append("G")
elif base == "G":
comp.append("C")
elif base == "T":
comp.append("A")
comp_strand = "".join(comp)
return comp_strand
|
55b53247b265b721e3ef845978ed1df679cc2278
|
Meimoorthi/Python_Basic
|
/sum_of_digits.py
| 196 | 3.90625 | 4 |
count = 0
def countdigit(n):
if n<10 :
return n;
else:
count=n%10+countdigit(n/10)
return count
a=input("Enter the number \t")
print "output is :\n",countdigit(a)
|
63ba567d8a5a46b96e6d18eb223285cb6ee48ec6
|
hansini-ruparel/learning.progress
|
/concept-inputs1.py
| 84 | 3.5 | 4 |
print("Hello World")
name = input("Enter your name ")
print ("Welcome " ,name)
|
dbeaa855ba4f0ce46d424206811e990358b5bec7
|
len1028/python
|
/long.py
| 324 | 3.578125 | 4 |
# _*_coding:utf-8_*_
# Author:len liu
name = ["zs","ls","we","mz"]
name.insert(1,"xx")
name[1] = "hh"
name2 = ["zz","yy","xx"]
#del name[1]
#name.remove("we")
#name.pop(0)
#print(name.index("ls"))
name.append("ls")
#print(name.count("ls"))
#name.extend(name2)
name.insert(2,name2)
print(name)
#print(name[name.index("hh")])
|
6abc4bc16105e4f9798e845b6bef12749dc19af4
|
lalapapauhuh/Python
|
/CursoEmVideo/pythonProject/ex064.py
| 407 | 3.765625 | 4 |
# tratamento de valores
numero = 0
cont = 0
resultado = 0
saida = False
while not saida:
if numero != 999:
numero = int(input('Digite um número [999 para parar]: '))
resultado += numero
cont += 1
saida = False
else:
cont -= 1
resultado -=999
saida = True
print('Você digitou {} números, e a soma deles é {}'.format((cont), (resultado)))
|
aaacd1d2d1e3cf1ad5392b95dda2ebf1bc8f9e6d
|
zerghua/leetcode-python
|
/N1957_DeleteCharacterstoMakeFancyString.py
| 2,148 | 4.03125 | 4 |
#
# Create by Hua on 3/21/22.
#
"""
A fancy string is a string where no three consecutive characters are equal.
Given a string s, delete the minimum possible number of characters from s
to make it fancy.
Return the final string after the deletion. It can be shown that the answer
will always be unique.
Example 1:
Input: s = "leeetcode"
Output: "leetcode"
Explanation:
Remove an 'e' from the first group of 'e's to create "leetcode".
No three consecutive characters are equal, so return "leetcode".
Example 2:
Input: s = "aaabaaaa"
Output: "aabaa"
Explanation:
Remove an 'a' from the first group of 'a's to create "aabaaaa".
Remove two 'a's from the second group of 'a's to create "aabaa".
No three consecutive characters are equal, so return "aabaa".
Example 3:
Input: s = "aab"
Output: "aab"
Explanation: No three consecutive characters are equal, so return "aab".
Constraints:
1 <= s.length <= 105
s consists only of lowercase English letters.
"""
class Solution(object):
def makeFancyString(self, s):
"""
:type s: str
:rtype: str
thought: go through the string, and construct a new string, when
encounter a third duplidate and skip it. need extra storage to check
duplicate and count.
03/21/2022 15:47 Accepted 648 ms 16.5 MB python
easy, 5min, however, wasted some time on the large test string,
so changed the direct "+" strings to append c to list and then join
them.
interesting solution from discussion:
class Solution:
def makeFancyString(self, s: str) -> str:
s = list(s)
for i in range(1,len(s)-1):
if (s[i-1] == s[i]) and (s[i+1] == s[i]):
s[i-1] = ""
return "".join(s)
"""
last = ""
count = 0
ret = list()
for c in s:
if c == last:
count +=1
if count < 2:
ret.append(c)
else:
ret.append(c)
last = c
count = 0
return "".join(ret)
|
3654ca976bf7228ab21d5b946f4a6bb7df5add72
|
liamcarroll/python-programming-2
|
/Lab_2.1/unique_count_021.py
| 464 | 3.796875 | 4 |
#!/usr/bin/env python3
import sys
def unique_words(l):
unique_words = []
for word in l:
if word not in unique_words:
unique_words.append(word)
return len(unique_words)
def main():
text = sys.stdin.read().strip().casefold()
for c in text:
if not c.isalnum() and not c.isspace():
text = text.replace(c, '')
words = text.split()
print(unique_words(words))
if __name__ == '__main__':
main()
|
7e18c9060956993080ee3ccd9c6442da61941ec2
|
HannanehGhanbarnejad/IntroductionToPythonProgramming
|
/ex2/prog2.py
| 741 | 4.25 | 4 |
a=int(input("Please enter the first number:"))
b=int(input("Please enter the second number:"))
def prog2(a, b):
""" (int, int)-> list
Return all the even numbers between two given values.
The function works even if the first given value is
bigger than the second one numerically .
>>> prog2(23, 3) #23 as a, 3 as b
[4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
>>> prog2(56, 67) #56 as a, 67 as b
[56, 58, 60, 62, 64, 66]
"""
if b>a:
L=[]
for i in range(a,b+1):
if i%2 == 0:
L.append(i)
print(L)
else:
L1=[]
for j in range(b,a+1):
if j%2 == 0:
L1.append(j)
print(L1)
prog2(a, b)
|
514f2084f12124104d8498a156a7d6c1e7a0fe75
|
mannerslee/leetcode
|
/138.py
| 2,051 | 3.734375 | 4 |
# Definition for a Node.
'''
思路:
两次两次遍历 目标表
第一次遍历: 会略random, 拷贝next和val。
字典 p_add2index 记录目标表p 指针->索引
字典 q_index2add 记录目标表q 索引->指针
第二次遍历:
从 p_add2index表知道 当前p.random->索引->q表指正,赋值给q.random
从而赋值random关系
注意点:
空指针的在 map中的处理
头结点 尾插法简历链表
'''
class Node:
def __init__(self, x: int, next=None, random=None):
self.val = int(x)
self.next = next
self.random = random
class Solution:
def copyRandomList(self, head):
p = head
q_head = Node(-1)
q = q_head
index = 0
q_index2add = {}
p_add2index = {}
while p:
q.next = Node(p.val)
p_add2index[p] = index
q_index2add[index] = q.next
q = q.next
p = p.next
index = index + 1
q = q_head.next
p = head
while p:
if p.random:
index = p_add2index[p.random]
q_random_point = q_index2add[index]
q.random = q_random_point
else:
q.random = None
p = p.next
q = q.next
return q_head.next
if __name__ == '__main__':
p1 = Node(7)
p2 = Node(13)
p3 = Node(11)
p4 = Node(10)
p5 = Node(1)
p1.next = p2
p1.random = None
p2.next = p3
p2.random = p1
p3.next = p4
p3.random = p5
p4.next = p5
p4.random = p3
p5.next = None
p5.random = p1
solution = Solution()
q = solution.copyRandomList(p1)
# q = p1
while q:
print("q.val = ", q.val)
if q.next:
print("q.next = ", q.next.val)
else:
print("q.next = null")
if q.random:
print("q.random = ", q.random.val)
else:
print("q.random = null")
print('-----------------')
q = q.next
|
ff0dec31ed8f37c33080c513acade032677032d8
|
VictorPuglieseManotas/DataScience
|
/HML_Chap03_01.py
| 13,234 | 3.5 | 4 |
from sklearn.datasets import fetch_mldata
mnist = fetch_mldata('MNIST original')
mnist
X,y=mnist['data'],mnist['target']
X.shape #Rows are intances, Columns are features (784 features=28x28pixeles). Each pixel (0:white -> 255:black)
y.shape #70,000 numbers between 0-9
import matplotlib
import matplotlib.pyplot as plt #Uses plt as alias for matplotlib.pyplot
some_digit=X[36000] #Select the instance 36000
some_digit_image=some_digit.reshape(28,28) #Reshape the vector to an array 28x28. The values have the information about the intesity of the color
plt.imshow(some_digit_image,cmap=matplotlib.cm.binary, #Display the image
interpolation='nearest')
plt.axis('off') #Do not show the axis
plt.show() #Only shows the image
#Splitting in Train and Test Set
X_train,X_test,y_train,y_test=X[:60000],X[60000:],y[:60000],y[60000:]
#The first 60,000 instances are for trainning, the remaining is for testing
import numpy as np #Uses np as alias of numpy
shuffle_index=np.random.permutation(60000) #Perform a random permutation of the number 0-60,000
X_train,y_train=X_train[shuffle_index],y_train[shuffle_index] #Shuffles the train_set to guarantee that all cross-validation fikds will be similar
#TRAINING A BINARY CLASSIFIER
#Example of a 5-classifier
y_train_5=(y_train==5) #True for all 5s, False for other digits.
y_test_5=(y_test==5)
from sklearn.linear_model import SGDClassifier
#Stochastic Gradient Descent classifier deals with training instances independetly, one at a time.
sgd_clf=SGDClassifier(random_state=42) #Create the classifier function, the 42 let us to obtain the same result everytime.
sgd_clf.fit(X_train,y_train_5) #fits a model using the train_set and the boolean desired result
sgd_clf.predict([some_digit]) #Evaluates the row[36,000]
#PERFORMANCE MEASURES
#Using Cross-Validation
from sklearn.model_selection import cross_val_score #Evaluates the model
cross_val_score(sgd_clf,X_train,y_train_5,cv=3,scoring='accuracy')
#sgd_clf has already the model to predict.
#cv is the number of fold
#'accuracy' is the ratio of goog predictions/total predictions
#Using a custom classifier for "not-5" images
from sklearn.base import BaseEstimator
class Never5Classifier(BaseEstimator):
def fit(self,X,y=None):
pass #Nothing happends, but a syntax is required
def predict(self,X):
return np.zeros((len(X),1),dtype=bool) #Classifies everything as non-5
#len() returns the length of X
#np.zeros((rows,columns),boolean type)
never_5_clf=Never5Classifier()
cross_val_score(never_5_clf,X_train,y_train_5,cv=3,scoring='accuracy') #This has a 90% percent of accuracy, but it is a whorthless function
#Evaluation using Confusion Matrix
from sklearn.model_selection import cross_val_predict
y_train_pred=cross_val_predict(sgd_clf,X_train,y_train_5,cv=3)
#Uses the sgd_clf classifier, and 3 fold
from sklearn.metrics import confusion_matrix
confusion_matrix(y_train_5,y_train_pred) #Compare the train_set results with the prediction
# Not-5 Predicted | 5 Predicted
# Not-5
# 5
#Precision=TP/(TP+FP)
#Recall=TP/(TP+FN)
#F1_Score=2/(1/precision+1/recall)
from sklearn.metrics import precision_score,recall_score,f1_score
precision_score(y_train_5,y_train_pred)
recall_score(y_train_5,y_train_pred)
f1_score(y_train_5,y_train_pred)
y_scores=cross_val_predict(sgd_clf,X_train,y_train_5,cv=3,method='decision_function') #Gets the score from all data
#Manually we can set a threshold
from sklearn.metrics import precision_recall_curve
precisions,recalls,thresholds=precision_recall_curve(y_train_5,y_scores) #Returns the corresponding precision and recall for each threshold
def plot_precision_recall_vs_threshold(precisions,recalls,thresholds): #Creates a plotting function
plt.plot(thresholds,precisions[:-1],'b--',label='Precision')
plt.plot(thresholds,recalls[:-1],'g-',label='Recall')
plt.xlabel('Threshold') #Label for x axis
plt.legend(loc='center left') #location for the legend
plt.ylim([0,1]) #Range for y axis
plot_precision_recall_vs_threshold(precisions,recalls,thresholds)
plt.show()
#ROC Curve
#Receiver Operating Characterictic Curve
#True Positive Rate vs False Positive Rate
#True Positive Rate = Recall
#False Positive = FP/(FP+TN)
from sklearn.metrics import roc_curve
fpr,tpr,thresholds=roc_curve(y_train_5,y_scores)
def plot_roc_curve(fpr,tpr,label=None):
plt.plot(fpr,tpr,linewidth=2,label=label)
plt.plot([0,1],[0,1],'k--')
plt.axis([0,1,0,1])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plot_roc_curve(fpr,tpr) #The dotted line represents a purely random classifier. A good classifier stay as far away from it.
plt.show()
from sklearn.metrics import roc_auc_score
roc_auc_score(y_train_5,y_scores) #Calculates the Area Under the ROC Curve. A good classifier has a score close to 1
#ROC Curve using a Random Classifier
from sklearn.ensemble import RandomForestClassifier
forest_clf=RandomForestClassifier(random_state=42)
y_probas_forest=cross_val_predict(forest_clf,X_train,y_train_5,cv=3,method='predict_proba') #Returns an array containing a row per instance and a column per clas.
#Each class contain the probability that the given instance belongs to the given class.
y_scores_forest=y_probas_forest[:,1] #score = proba of positive class
fpr_forest,tpr_forest,thresholds_forest=roc_curve(y_train_5,y_scores_forest) #Evaluates the performance of the RandomClassifier for different thresholds
plt.plot(fpr,tpr,'b:',label='SGD') #Plots the SGD performance
plot_roc_curve(fpr_forest,tpr_forest,'Random_Forest') #Plots the RandomForest Performance
plt.legend(loc='lower right')
#MULTICLASS CLASSIFICATION
#One-Versus-All (OvA)
#Uses a binary classifier for each digit (10), and uses the score from each one to decide the real number.
sgd_clf.fit(X_train,y_train) #y_train contains the numbers targeted
sgd_clf.predict([some_digit]) #Predict the class for [36,000] instance
some_digit_scores=sgd_clf.decision_function([some_digit]) #Gets the score for each class
some_digit_scores
np.argmax(some_digit_scores) #Gets the maximun argumen location
sgd_clf.classes_ #Classes
#One vs One (OvO) strategy
#Trains a binary classifier for every pair of digit: 0 vs 1, 0 vs 2, 1 vs 2, etc.
#Get the class that wins more duels
from sklearn.multiclass import OneVsOneClassifier
ovo_clf=OneVsOneClassifier(SGDClassifier(random_state=42))
ovo_clf.fit(X_train,y_train)
ovo_clf.predict([some_digit])
len(ovo_clf.estimators_)
#Multiclassification with RandomForestClassifier
forest_clf.fit(X_train,y_train)
forest_clf.predict([some_digit]) #Predict the class directly
forest_clf.predict_proba([some_digit]) #Get the probability for each class
cross_val_score(sgd_clf,X_train,y_train,cv=3,scoring='accuracy') #Evaluation of Multiclass using cross-validation score
#Scaling the data helps to improve the accuracy
from sklearn.preprocessing import StandardScaler
scaler=StandardScaler()
X_train_scaled=scaler.fit_transform(X_train.astype(np.float64)) #numpy.float64 requests using the double precision float type
cross_val_score(sgd_clf,X_train_scaled,y_train,cv=3,scoring='accuracy') #Evaluation of Multiclass using cross-validation score
#ERROR ANALYSIS
#Confusin matrix for multiclassification
y_train_pred=cross_val_predict(sgd_clf,X_train_scaled,y_train,cv=3)
conf_mx=confusion_matrix(y_train,y_train_pred)
conf_mx
plt.matshow(conf_mx,cmap=plt.cm.gray)
plt.show()
row_sums=conf_mx.sum(axis=1,keepdims=True) #Sums each row of the confusion matrix, gets a array (10,1)
norm_conf_mx=conf_mx/row_sums #Divides each cell by the corresponding total along the row
np.fill_diagonal(norm_conf_mx,0) #Fills the diagonal with 0
plt.matshow(norm_conf_mx,cmap=plt.cm.gray)
plt.show()
#Multilabel classification system
#Classification system that outputs multiple binary labels
from sklearn.neighbors import KNeighborsClassifier #Supports multilabel classification
y_train_large=(y_train>=7) #True for 7,8,9
y_train_odd=(y_train%2==1) #True for odd numbers
y_multilabel=np.c_[y_train_large,y_train_odd] #Assign the 2 conditions as attribute for y_multilabel
knn_clf=KNeighborsClassifier()
knn_clf.fit(X_train,y_multilabel) #Trains the classfier
knn_clf.predict([some_digit]) #Predicts for the [36,000] instance
#Evaluation of multilabel classification system
y_train_knn_pred=cross_val_predict(knn_clf,X_train,y_multilabel,cv=3)
f1_score(y_multilabel,y_train_knn_pred,average='macro')
#EXERCISE 01
knn_clf.fit(X_train,y_train)
y_train_digit_predict=knn_clf.predict(X_train)
from sklearn.metrics import accuracy_score
accuracy_score(y_train, y_train_digit_predict)
from sklearn.model_selection import GridSearchCV #Finds the best combination of hyperparameters using cross-vaidation
#In this exercise KNeighborsClassifier is Used
param_grid=[{'weights':['uniform','distance'],'n_neighbors':[3,5,10]}] #Run KNeighbors for each combination of weight and n_neighbor
grid_search=GridSearchCV(knn_clf,param_grid,cv=3, #Creates the function to find the best model for KNeighbors using 3 folds
scoring='accuracy',n_jobs=-1) #n_jobs=-1: the number of jobs is set to the number of CPU cores
grid_search.fit(X_train,y_train) #Runs GridSearch
y_pred = grid_search.predict(X_test)
accuracy_score(y_test, y_pred)
#Exercise 02
from scipy.ndimage.interpolation import shift #Function to move the array
def shift_image(image, dx, dy): #image is a vector shape with the information of the pixels
image = image.reshape((28, 28)) #Reshape the vector to array (28x28)
shifted_image = shift(image, [dy, dx], cval=0, mode="constant") #function execution. Points outside the array are filled with the "constant=0"
return shifted_image.reshape([-1]) #Reshape in a row with unknown size
image = X_train[1000] #Image in location 10,000
shifted_image_down = shift_image(image, 0, 5) #Image shifted down 5 pixels
shifted_image_left = shift_image(image, -5, 0) #Image shifted left 5 pixels
plt.figure(figsize=(12,3))
plt.subplot(131)
plt.title("Original", fontsize=14)
plt.imshow(image.reshape(28, 28), interpolation="nearest", cmap="Greys")
plt.subplot(132)
plt.title("Shifted down", fontsize=14)
plt.imshow(shifted_image_down.reshape(28, 28), interpolation="nearest", cmap="Greys")
plt.subplot(133)
plt.title("Shifted left", fontsize=14)
plt.imshow(shifted_image_left.reshape(28, 28), interpolation="nearest", cmap="Greys")
plt.show()
X_train_augmented = [image for image in X_train] #Initial data, prior to be augmented
y_train_augmented = [label for label in y_train]
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)): #Loop to shift the images
for image, label in zip(X_train, y_train): #Run in every image and label data
X_train_augmented.append(shift_image(image, dx, dy)) #The shifted image is added to the original data collection
y_train_augmented.append(label) #A copy of the label added.
X_train_augmented = np.array(X_train_augmented) #Convert data to array structure
y_train_augmented = np.array(y_train_augmented)
shuffle_idx = np.random.permutation(len(X_train_augmented)) #Shuffle the new augmented data randomly
X_train_augmented = X_train_augmented[shuffle_idx]
y_train_augmented = y_train_augmented[shuffle_idx]
knn_clf = KNeighborsClassifier(**grid_search.best_params_) #Using the best parameters,the classifier is trained with the new augmented data
knn_clf.fit(X_train_augmented, y_train_augmented)
y_pred = knn_clf.predict(X_test) #New prediction
accuracy_score(y_test, y_pred) #Accuracy of the model
|
2a4df919817a9888dcd686a8e780601418efd73e
|
RickyUC/Probando
|
/Tareas/Tarea 1/operaciones.py
| 3,417 | 3.59375 | 4 |
def negativo (numero):
resultado = ""
for digito in numero:
if digito == "1":
resultado += "0"
elif digito == "0":
resultado += "1"
return resultado
def rotar_izq (numero):
inicial = numero[:1]
resultado = numero[1:] + inicial
return resultado
def rotar_der (numero):
final = numero[-1]
resultado = final + numero[:-1]
return resultado
def desp_izq (numero):
resultado = numero[1:] + "0"
return resultado
def desp_der (numero):
resultado = "0" + numero[:-1]
return resultado
def sumar_int (a, b):
carry = "0"
a = a[::-1]
b = b[::-1]
resultado = ""
for i in range(len(a)):
if carry == "1":
if a[i] == "1" and b[i] == "1":
resultado += "1"
elif a[i] == "0" and b[i] == "0":
resultado += "1"
carry = "0"
else:
resultado += "0"
else:
if a[i] == "1" and b[i] == "1":
resultado += "0"
carry = "1"
elif a[i] == "0" and b[i] == "0":
resultado += "0"
else:
resultado += "1"
resultado += carry
return resultado[::-1]
def sumar_restar_float (a, b, operacion):
cero = "0"
if a[1:6] == "00000":
return b
elif b[1:6] == "00000":
return a
a_mant = "1" + a[6:16]
b_mant = "1" + b[6:16]
if menor(a[1:6], b[1:6]):
exp = b[1:6]
mover = bin_to_dec(restar_int(b[1:6], a[1:6])[1:])
for i in range(mover):
a_mant = desp_der(a_mant)
else:
exp = a[1:6]
mover = bin_to_dec(restar_int(a[1:6], b[1:6])[1:])
for i in range(mover):
b_mant = desp_der(b_mant)
if operacion == "sumar":
res = sumar_int(a_mant, b_mant)
else:
res = restar_int(a_mant, b_mant)
if menor(a[1:6], b[1:6]):
cero = "1"
while len(res) > 11:
if res[0] == "1":
exp = restar_int(exp, "00001")[1:]
if res[11] == "1":
res = sumar_int(res, "0"* 11 + "1")[:12]
else:
res = res[1:12]
if res[0] == "0":
res = res[1:]
if len(res) == 10:
res += "0"
return cero + exp + res[1:]
def restar_int (a, b):
b = negativo(b)
uno = "0" * (len(a) - 1) + "1"
b = sumar_int(b, uno)[1:]
return sumar_int(a, b)
def AND (a, b):
resultado = ""
for i in range(len(a)):
if a[i] == "1" and b[i] == "1":
resultado += "1"
else:
resultado += "0"
return resultado
def OR (a, b):
resultado = ""
for i in range(len(a)):
if a[i] == "0" and b[i] == "0":
resultado += "0"
else:
resultado += "1"
return resultado
def XOR (a, b):
resultado = ""
for i in range(len(a)):
if a[i] == b[i]:
resultado += "0"
else:
resultado += "1"
return resultado
def menor(a, b):
for i in range(len(a)):
if a[i] == "1" and b[i] == "0":
return False
elif a[i] == "0" and b[i] == "1":
return True
return False
def bin_to_dec(binario):
binario = binario[::-1]
numero = 0
for i in range(len(binario)):
if binario[i] == "1":
numero += 2**(i)
return numero
|
42a76b40be3ff54e8f449ed6eb64ee6adbe70896
|
klimova00/Python_4_les
|
/4_les/4_les_2_ex.py
| 229 | 3.78125 | 4 |
my_list = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]
print(f"my_list: {my_list}")
new_list = []
el1 = my_list[0]
for el in my_list:
if (el1 < el):
new_list.append(el)
el1 = el
print(f"new_list: {new_list}")
|
8f8e9e41172d9f3cb8c886216c3ef9d065b476a1
|
suryansh2020/chapter_codes
|
/codes_ch4/chap4_code_2.py
| 239 | 3.609375 | 4 |
class Example:
pass
x = Example()
print(hasattr(x, 'attr'))
Example.attr = 33
y = Example()
print(y.attr)
Example.attr2 = 54
print(y.attr2)
Example.method = lambda self: "Calling Method..."
print(y.method())
print(hasattr(x, 'attr'))
|
c147403fb4c3bdd2f3f64d508cffa16939b81307
|
sung3r/ctfcode
|
/exp/2017/tmctf/ao200.py
| 946 | 3.765625 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def is_prime(n):
i = 2
while i < n:
if n % i == 0:
return False
i += 1
return True
def odd_sum(n):
i = 1
while True:
n -= i
if n == 0:
return True
elif n < 0:
return False
i += 2
def flag_sum(code):
s = 0
for d in str(code):
s += ord(d)
return s
with open('primes', 'r') as f:
tmp = f.read()
primes = [int(p) for p in tmp.split(',')]
a = []
for p in primes:
x1 = p / 10000 % 100
x2 = p / 100 % 100
x3 = p % 100
if not is_prime(x1):
continue
if not is_prime(x2):
continue
if not odd_sum(x3):
continue
if (x3 * x3 ^ (p / 100 % 10000)) >> 8 != 0:
continue
if not is_prime(flag_sum(p) - 288):
continue
a.append(p)
with open('xd', 'w') as f:
for p in a:
f.write(str(p) + '\n')
|
fb576d70f8f3cae4ab4e3a001db708fec010035f
|
chloeward00/CA117-Computer-Programming-2
|
/labs/geometry_072.py
| 1,304 | 4 | 4 |
class Point(object):
def __init__(self, x=0, y=0):
self.x = int(x)
self.y = int(y)
def distance(self, other):
x = self.x - other.x
y = self.y - other.y
d = (x ** 2 + y ** 2) ** 0.5
return d
def __str__(self):
return "({:.1f}, {:.1f})".format(self.x, self.y)
class Segment(object):
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def midpoint(self):
low = self.p1
high = self.p2
x_dist = (low.x + high.x) / 2
y_dist = (low.y + high.y) / 2
return "({:.1f}, {:.1f})".format(x_dist, y_dist)
def length(self):
return ((self.p1).distance(self.p2))
class Circle(object):
def __init__(self, point, radius):
self.rad = int(radius)
self.cen = point
def overlaps(self, other):
totalradius = self.rad + other.rad
d = ((self.cen).distance(other.cen))
return (totalradius > d)
def main():
p1 = Point()
p2 = Point(5, 5)
s1 = Segment(p1, p2)
s2 = Segment(p2, p1)
c1 = Circle(p1, 5)
c2 = Circle(p2, 2)
c3 = Circle(p1, 2)
print(p1)
print(p2)
print(s1.midpoint())
print(s2.midpoint())
print(c1.overlaps(c2))
print(c2.overlaps(c1))
print(c1.overlaps(c3))
print(c3.overlaps(c2))
if __name__ == '__main__':
main()
|
8dd75042260c47d01e8cf808c7e5b072739be2f7
|
mohamma548/python_API
|
/url_XML.py
| 440 | 3.84375 | 4 |
#!/usr/bin/python
# retriving XML data using python from the web
import urllib
import xml.etree.ElementTree as ET
url = raw_input("Please enter the url:")
total=0
xml_data=urllib.urlopen(url).read()
tree= ET.fromstring(xml_data)
lst=tree.findall('comments/comment')
# retriving all the numbers inside count tag
for item in lst:
total= total + int(item.find('count').text)
print "The sum of the numbers inside the count tag are:",total
|
0f1cb86327c542fec46fceedbd1af17dae2a1651
|
apoorvaanwekar/python-challenge
|
/PyPoll/main.py
| 2,479 | 3.921875 | 4 |
##################################################################################
# Author: Apoorva Anwekar
# Solution for Homework #3 PyPoll.
##################################################################################
import csv
#creating an empty dictionary
mydict = {}
#initializing a counter for counting total votes
count = 0
#initializing a counter for storing maximum number of votes per candidate
max_votes = 0
#open a file
with open('election_data_2.csv', newline='') as csvfile:
#read the file with csv
election_data = csv.reader(csvfile, delimiter=',')
#read the file with csv
next(election_data)
#looping through each row in the table
for row in election_data :
#increment the counter by 1 every iteration
count += 1
#storing a value in candidate per iteration for row[2]
candidate = row[2]
#check for condition
if candidate in mydict:
mydict[candidate] += 1
else:
mydict[candidate] = 1
#open file to write results to file
with open('results.txt', 'w') as results:
#Print the header string
print("Election Results")
print("-------------------------")
print("Total Votes: " + str(count))
print("-------------------------")
#print result to file
print("Election Results", file = results)
print("-------------------------", file = results)
print("Total Votes: " + str(count), file = results)
print("-------------------------", file = results)
for candidate in mydict.keys() :
count_of_votes = mydict[candidate]
#calculating the percentage and rounding of thr result to 2 places of decimal
percentage = round((count_of_votes/count)*100.00,2)
#print the result
print (candidate + (": ") + str(percentage) + ("% (") + str(count_of_votes) + ")")
#print result to file
print (candidate + (": ") + str(percentage) + ("% (") + str(count_of_votes) + ")", file = results)
#check for condition to find out winner by finding the max votes
if count_of_votes > max_votes :
max_votes = count_of_votes
winner = candidate
print("-------------------------")
print("Winner: "+ winner)
print("-------------------------")
#print result to file
print("-------------------------", file = results)
print("Winner: "+ winner, file = results)
print("-------------------------", file = results)
|
174f435d046ba8843973a73cd9f1c1c7c688d58e
|
lukabombala/adventofcode2019
|
/task1/task1_solution.py
| 556 | 3.53125 | 4 |
import math
# solution for 1st part
output1 = 0
with open('task1/input1.txt', 'r') as file:
for line in file:
line = int(line)
output1 += math.floor(line/3) - 2
# printing answer
print(output1)
# solution for 2nd part
output2 = 0
with open('task1/input2.txt', 'r') as file:
for line in file:
fuel = 0
mass = int(line)
while True:
mass = math.floor(mass/3) - 2
if mass <= 0:
break
fuel += mass
output2 += fuel
# printing answer
print(output2)
|
3eed1f413dc2e6dd6c8dbcfded6e911b99741916
|
zoomjuice/CodeCademy_Learn_Python_3
|
/Unit 10 - Classes/10_02_01-Inheritance.py
| 1,019 | 4.5 | 4 |
"""
Classes are designed to allow for more code reuse, but what if we need a class that looks a lot like a class we
already have? If the bulk of a class’s definition is useful, but we have a new use case that is distinct from how the
original class was used, we can inherit from the original class. Think of inheritance as a remix — it sounds a lot
like the original, but there’s something… different about it.
class User:
is_admin = False
def __init__(self, username)
self.username = username
class Admin(User):
is_admin = True
Above we defined User as our base class. We want to create a new class that inherits from it, so we created the
subclass Admin. In the above example, Admin has the same constructor as User. Only the class variable is_admin is set
differently between the two.
Sometimes a base class is called a parent class. In these terms, the class inheriting from it, the subclass,
is also referred to as a child class.
"""
class Bin:
pass
class RecyclingBin(Bin):
pass
|
9bf7e1deb26b057a24380371c1f9f023a2a14e62
|
rangermx/Git_Project
|
/Python/tools/get_cs.py
| 1,750 | 3.53125 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'get 376.2 cs sum'
__author__ = 'Mingxin Liu'
import sys
def start_working(param = 1):
print('please enter your 376.2 string without starting code "68", strlen, and the ending code "16"')
while True:
# 第一步,输入字符串
source_str = sys.stdin.readline()
if source_str == 'quit\n' or source_str == 'exit\n':
return
# 第二步,字符串以空格为单位切割为字符数组
str_list = source_str.split(' ')
hex_list = []
# 第三步,将字符转换为16进制的数字
for num_str in str_list:
if num_str == '\n' or num_str == '':# 筛除末尾空格和连续空格被分割后产生的空字串
continue
if num_str.endswith('\n'):# 去掉字串末尾的换行符
num_str = num_str[:-1]
if param == 1:# 可选1,将长度超过2的字串,两个一组切片
if len(num_str) > 2:
n = 0
while n < len(num_str):
if n + 2 <= len(num_str):
hex_list.append(int(num_str[n:n+2], 16))
else:
hex_list.append(int(num_str[n:], 16))
n = n + 2
else:
hex_list.append(int(num_str, 16))
elif param == 2:# 可选2,将长度超过2的字串当成一个16进制数据处理
hex_list.append(int(num_str, 16))
# 第四步,求和
sum = 0x00
for num in hex_list:
sum = sum + num
# 第五步,求与
sum = sum & 0xFF
# 最后,输出结果
print('%#x' % sum)
if __name__ == '__main__':
start_working()
|
feb7084e1b113beb4b274feb520a6769f4d5e2f2
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/python/sieve/5965153ffbfd46b19869bc424d49b67d.py
| 198 | 3.59375 | 4 |
def sieve(n):
result = range(2, n + 1)
i = 0
p = result[i]
while p * p <= n:
result = [res for res in result if res == p or res % p != 0]
i += 1
p = result[i]
return result
|
05dbaa88671d5d794827814a3d570e244ac0e9d0
|
distractedpen/datastructures
|
/SearchOperations.py
| 871 | 4 | 4 |
def linearSearch(array, value):
i = 0
for i in range(len(array)):
if array[i] == value:
return "Found {0} at index {1}.".format(value, i)
i += 1
return "{0} not found.".format(value)
def binarySearch(array, value):
low = 0
mid = len(array) // 2
high = len(array) - 1
while(low <= high):
if array[mid] < value:
low = mid + 1
mid = low + (high - low) // 2
elif array[mid] > value:
high = mid - 1
mid = low + (high - low) // 2
else:
return "Found {0} at index {1}.".format(value, mid)
return "{0} not found.".format(value)
def main():
a = [0, 1, 3, 5, 6, 8]
print(linearSearch(a, 3))
print(linearSearch(a, 4))
print(binarySearch(a, 1))
print(binarySearch(a, 2))
if __name__ == "__main__":
main()
|
de84c306cd3602685f0aaeca1dd386c16216d79a
|
patrenaud/Python
|
/CoursPython/Len.py
| 268 | 3.921875 | 4 |
# Message Analyser
# Demonstrates the len() function and the in operator
message = input("Enter a message: ")
print("\nThe lenght of this message is: ", len(message))
if "e" in message.lower():
print(" 'e' is in this message")
input("\n\nPress enter to quit")
|
287621f37fa39e25f40a39c8f3bec018994946f6
|
wanwanaa/Leetcode
|
/数学/7.整数反转.py
| 384 | 3.765625 | 4 |
# 7.整数反转
# 负数取模下取整
def reverse(self, x: int) -> int:
while x != 0:
pop = x % 10
if (temp > sys.maxsize/10) or (temp == sys.maxsize/10 and pop > 7):
return 0
if (temp < (-sys.maxsize-1)/10 0r (temp == (-sys.maxsize-1)/10 and pop < -8):
return 0
temp = temp * 10 + pop
x = x // 10
return temp
|
4727e16923735122db2d496a0749e25160dc4ab8
|
folsomjenna/pythons
|
/1-3 deliverables/year.py
| 570 | 3.671875 | 4 |
# year.py
# Created on 12/11/18 by Jenna Folsom
# A program that prompts the user for a 4-digit year and then outputs the value of the epact
def main():
import math
# This is an introduction
print("This is a program that prompts you for a 4-digit year and then outputs the value of the epact.")
# This is an input
year = eval(input("What 4-digit year would you like to use? "))
C = year//100
epact = (8 + (C//4) - C + ((8*C + 13)//25) + 11 *(year%19)) %30
# This is an output
print("The value of the epact is", epact, ".")
main()
|
b1f1276512a78d2f671a0a90812a43f6c6149751
|
dslap0/Universite-Python
|
/PHY1234/Laboratoire2-codesQ3alt.py
| 1,021 | 3.890625 | 4 |
# -*- coding: latin-1 -*-
#@author: Nicolas
"""
Code incomplet visant à passer par une boucle for au lieu de while pour
trouver la somme de contrôle de l'algorithme de Luhn.
"""
liste = list(((input('Entrez un code à vérifier:')).\
replace(' ','')).replace('-',''))
i = 0
for x in (0,len(liste)): #On change tous les éléments de la liste en int
x = int(x)
for x in (0,len(liste),2): #On change un nombre sur deux
x *= 2
if x > 9:
"""Lorsqu'on arrive avec une solution à deux chiffres,
on soustrait 9 pour ne garder qu'un seul chiffre"""
x -= 9
liste[i] = x
i += 1
somme = sum(liste) #On produit la somme de contrôle
print(somme)
if somme % 10 == 0:
#Si la somme de contrôle est un multiple de 10, alors le code est valide
print('Le code semble être valide.')
else:
"""Si la somme de contrôle n'est pas divisible par 10, alors
le code est invalide"""
print('Le code est invalide.')
|
95fa89bb021493b6e6b05293435093d52783a14d
|
yilinanyu/Leetcode-with-Python
|
/test10.py
| 146 | 3.90625 | 4 |
def excel(num):
# number to title
ans = ''
while num:
ans = ans + chr(ord('A')+ (num-1)%26)
num = (num - 1)/26
return ans
print excel(27)
|
6fa8a1331880e8369f2c5b383ecef0a45c221ec9
|
gautam-dwivedi/Python-Basics-Arithmetic
|
/06 arithmetic2.py
| 255 | 3.96875 | 4 |
# Python Basics
print("enter no a")
a= input()
#a= int (input("enter the value of a\n"))
print("enter no b")
b= input()
#b= int(input("enter the value of b\n"))
addition = a + b
print("Addition is:", addition)
print("type",type(addition))
|
68cfb3b8e6fc75ce43751a4263b9166558f14cec
|
southpawgeek/perlweeklychallenge-club
|
/challenge-159/lubos-kolouch/python/ch-1.py
| 600 | 4.0625 | 4 |
""" Challenge 159 Task 1"""
def farey_sequence(n: int, descending: bool = False) -> str:
"""Print the n'th Farey sequence. Allow for either ascending or descending."""
(a, b, c, d) = (0, 1, 1, n)
solution = []
if descending:
(a, c) = (1, n - 1)
solution.append(f"{a}/{b}")
while (c <= n and not descending) or (a > 0 and descending):
k = (n + b) // d
(a, b, c, d) = (c, d, k * c - a, k * d - b)
solution.append(f"{a}/{b}")
return ", ".join(solution)
assert farey_sequence(5) == "0/1, 1/5, 1/4, 1/3, 2/5, 1/2, 3/5, 2/3, 3/4, 4/5, 1/1"
|
a66884e2c3cb289ce78d632d092737cdc82643c5
|
jasperthegeo/Python_1
|
/PyPoll/main.py
| 1,540 | 3.6875 | 4 |
import os
import csv
vote_dict ={}
votes_per_candidate={}
csvpath = ("Resources\election_data.csv")
with open (csvpath, 'r', encoding='utf-8') as csvfile:
csvreader = csv.reader(csvfile)
next (csvreader)
for row in csvreader:
vote_dict[int(row[0])]=row[2]
votes_cast = len(vote_dict) #number of votes cast
candidates = set(vote_dict.values()) #list of candidates
for candidate in candidates:
#summing votes for each candidate from the list generated
#from the candidates list above
votes_per_candidate[candidate] = sum(value == candidate for value in vote_dict.values())
#write to terminal
print ("Election Results")
print ("-------------------------")
print (f"Total Vote: {votes_cast}")
print ("-------------------------")
for key, value in votes_per_candidate.items():
print (f"{key} {round((value/votes_cast *100),2)}% ({value})")
print ("-------------------------")
print (f"Winner: {max(votes_per_candidate,key=votes_per_candidate.get)}")
#write to a file
f = open("PyPoll_Results.txt", "x")
f.write ("Election Results")
f.write ("\n-------------------------")
f.write (f"\nTotal Vote: {votes_cast}")
f.write ("\n-------------------------")
for key, value in votes_per_candidate.items():
f.write (f"\n{key} {round((value/votes_cast *100),2)}% ({value})")
f.write ("\n-------------------------")
f.write (f"\nWinner: {max(votes_per_candidate,key=votes_per_candidate.get)}")
|
fb54d77051a80ba9fff92347248298da2432d1f0
|
nelsonripoll/portfolio
|
/python/general/classes.py
| 1,020 | 4.375 | 4 |
class Rectangle():
"""A simple shape class"""
def __init__(self, length, width):
"""Initialize a rectangle with length and width"""
self.length = length
self.width = width
def get_area(self):
return self.length * self.width
def get_parameter(self):
return (self.length * 2) + (self.width * 2)
def is_square(self):
return self.length == self.width
class Square(Rectangle):
def __init__(self, side):
"""Initialize a square with length and width set to side"""
super().__init__(side, side)
# python 2.7
# class Square(Rectangle):
# def __init__(self, side):
# """Initialize a square with length and width set to side"""
# super(Square, self).__init__(side, side)
new_shape = Rectangle(2, 3)
new_shape.get_area() # 6
new_shape.get_parameter() # 10
new_shape.is_square() # False
another_shape = Square(2)
new_shape.get_area() # 4
new_shape.get_parameter() # 8
another_shape.is_square() # True
|
787db5a9244a5836705d542c1f9328081694d2f3
|
kmiozan/arSerial
|
/sp_recognition.py
| 4,233 | 3.640625 | 4 |
#!/usr/bin/env python3
# NOTE: this example requires PyAudio because it uses the Microphone class
import speech_recognition as sr
# this is called from the background thread
def callback(recognizer, audio):
# received audio data, now we'll recognize it using Google Speech Recognition
try:
print("Recognizing")
# for testing purposes, we're just using the default API key
# to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
# instead of `r.recognize_google(audio)`
print("Google Speech Recognition thinks you said " + recognizer.recognize_google(audio, language="tr-TR"))
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
r = sr.Recognizer()
m = sr.Microphone()
with m as source:
print("Calibrating")
#r.adjust_for_ambient_noise(source) # we only need to calibrate once, before we start listening
print("Listening")
# start listening in the background (note that we don't have to do this inside a `with` statement)
stop_listening = r.listen_in_background(m, callback, phrase_time_limit=5)
# `stop_listening` is now a function that, when called, stops background listening
# do some other computation for 5 seconds, then stop listening and keep doing other computations
import time
for _ in range(50): time.sleep(0.1) # we're still listening even though the main thread is doing other things
stop_listening() # calling this function requests that the background listener stop listening
while True: time.sleep(0.1)
def callback(recognizer, audio):
# received audio data, now we'll recognize it using Google Speech Recognition
try:
print("Recognizing")
# for testing purposes, we're just using the default API key
# to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
# instead of `r.recognize_google(audio)`
print("Google Speech Recognition thinks you said " + recognizer.recognize_google(audio, key="AIzaSyBv_c6hXAIFhKBTxfYbWine04aUkRvSOXA", language="tr-TR"))
#ars.string2command(recognizer.recognize_google(audio, language="tr-TR"))
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
r = sr.Recognizer()
m = sr.Microphone()
with m as source:
print("Calibrating")
#r.adjust_for_ambient_noise(source) # we only need to calibrate once, before we start listening
print("Listening")
# start listening in the background (note that we don't have to do this inside a `with` statement)
stop_listening = r.listen_in_background(m, callback, phrase_time_limit=4)
# `stop_listening` is now a function that, when called, stops background listening
# do some other computation for 5 seconds, then stop listening and keep doing other computations
#import time
for _ in range(50): time.sleep(0.1) # we're still listening even though the main thread is doing other things
stop_listening() # calling this function requests that the background listener stop listening
while True: time.sleep(0.1)
# !/usr/bin/env python3
# Requires PyAudio and PySpeech.
#import speech_recognition as sr
# Record Audio
r = sr.Recognizer()
with sr.Microphone() as source:
print("Say something!")
audio = r.listen(source,timeout=1,phrase_time_limit=4)
# Speech recognition using Google Speech Recognition
try:
print("Anliyor")
# for testing purposes, we're just using the default API key
# to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
# instead of `r.recognize_google(audio)`
#print("You said: " + r.recognize_google(audio, language="tr-TR"))
ars.string2command(r.recognize_google(audio, language="tr-TR"))
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
|
ede1296a5fe69e34a00f6ffb145bdc54f01e7674
|
dmironov1993/hackerRank
|
/interview_prep_kit/Sorting/Sorting: Bubble Sort.py
| 774 | 3.8125 | 4 |
# https://www.hackerrank.com/challenges/ctci-bubble-sort/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=sorting
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countSwaps function below.
def countSwaps(n,a):
cnt = 0
for i in range(n):
for j in range(n-1):
if a[j] > a[j+1]:
a[j], a[j+1] = a[j+1], a[j]
cnt += 1
return cnt, a[0],a[-1]
if __name__ == '__main__':
n = int(input())
a = list(map(int, input().rstrip().split()))
numSwap, first, last = countSwaps(n,a)
print ("Array is sorted in {} swaps.".format(numSwap))
print ("First Element: {}".format(first))
print ("Last Element: {}".format(last))
|
aeab0d086481ab904204fb39c9780a33cca6f3ca
|
flash-drive/Python-First-Go
|
/Homework 2 Distance Between Two Points.py
| 862 | 4.25 | 4 |
# Homework 2 Distance Between Two Points
# Mark Tenorio 5/10/2018
# Write a program that finds the distance between two points
# on the cartesian plane
# Function to find distance between two points
def distance(x1,y1,x2,y2):
distance = ((((float(x2)-float(x1)) ** 2) + ((float(y2)-float(y1)) ** 2)) ** (1/2))
distance = round(distance,2)
return distance
# Grab user's inputs
print('Please input the two cartesian points to find the distance in the form [x1,y1] and [x2,y2]')
print('Input a value for x1:')
x1 = input()
print('Input a value for y1:')
y1 = input()
print('Input a value for x2:')
x2= input()
print('Input a value for y2:')
y2=input()
# Call function
distance = distance(x1,y1,x2,y2)
# Print output
print('The distance between ['+str(x1)+','+str(y1)+'] and ['+str(x2)+','+str(y2)+'] is '+str(distance)+'.')
|
300e6b11d6f1a923b62722e8d112bae60a261956
|
archerImagine/myNewJunk
|
/my2015Code/myGithubCode/6.00SC/Lec_22/src/example03.py
| 5,049 | 3.5 | 4 |
import random
class Node(object):
"""The base class for node"""
def __init__(self, name):
self.name = name
def getName(self):
return self.name
def __str__(self):
return self.name
class Edge(object):
"""docstring for Edge"""
def __init__(self, src,dest,weight=0):
self.src = src
self.dest = dest
self.weight = weight
def getSource(self):
return self.src
def getDestination(self):
return self.dest
def getWeight(self):
return self.weight
def __str__(self):
return str(self.src) + "->" + str(self.dest)
class Digraph(object):
"""docstring for Digraph"""
def __init__(self):
self.nodes = set([])
self.edges = {}
def addNode(self,node):
if node.getName() in self.nodes:
raise ValueError('Duplicate Node')
else:
self.nodes.add(node)
self.edges[node] = []
def addEdge(self,edge):
src = edge.getSource()
dst = edge.getDestination()
if not(src in self.nodes and dst in self.nodes):
raise ValueError('Node not in graph')
self.edges[src].append(dst)
def childrenOf(self,node):
return self.edges[node]
def hasNode(self,node):
return node in self.nodes
def __str__(self):
res = ''
for k in self.edges:
for d in self.edges[k]:
res = res + str(k) + '->' + str(d) + '\n'
return res[:-1]
class Graph(Digraph):
def addEdge(self,edge):
Digraph.addEdge(self,edge)
rev = Edge(edge.getDestination(), edge.getSource())
Digraph.addEdge(self,rev)
def shortestPath(graph,start,end,toPrint=False,visited = []):
global numCalls
numCalls += 1
if toPrint: #for debugging
print "", start, end
if not (graph.hasNode(start) and graph.hasNode(end)):
raise ValueError('Start or end not in graph.')
path = [str(start)]
if start == end:
return path
shortest = None
for node in graph.childrenOf(start):
if (str(node) not in visited): #avoid cycles
visited = visited + [str(node)] #new list
newPath = shortestPath(graph, node, end, toPrint, visited)
if newPath == None:
continue
if (shortest == None or len(newPath) < len(shortest)):
shortest = newPath
if shortest != None:
path = path + shortest
else:
path = None
return path
def dpShortestPath(graph, start, end, visited = [], memo = {}):
global numCalls
numCalls += 1
if not (graph.hasNode(start) and graph.hasNode(end)):
raise ValueError('Start or end not in graph.')
path = [str(start)]
if start == end:
return path
shortest = None
for node in graph.childrenOf(start):
if (str(node) not in visited):
visited = visited + [str(node)]
try:
newPath = memo[node, end]
except:
newPath = dpShortestPath(graph, node, end,
visited, memo)
if newPath == None:
continue
if (shortest == None or len(newPath) < len(shortest)):
shortest = newPath
memo[node, end] = newPath
if shortest != None:
path = path + shortest
else:
path = None
return path
def test3(kind):
nodes = []
for name in range(10):
nodes.append(Node(str(name)))
g = kind()
for n in nodes:
g.addNode(n)
g.addEdge(Edge(nodes[0],nodes[1]))
g.addEdge(Edge(nodes[1],nodes[2]))
g.addEdge(Edge(nodes[2],nodes[3]))
g.addEdge(Edge(nodes[3],nodes[4]))
g.addEdge(Edge(nodes[3],nodes[5]))
g.addEdge(Edge(nodes[0],nodes[2]))
g.addEdge(Edge(nodes[1],nodes[1]))
g.addEdge(Edge(nodes[1],nodes[0]))
g.addEdge(Edge(nodes[4],nodes[0]))
print 'The graph:'
print g
shortest = shortestPath(g, nodes[0], nodes[4])
print 'The shortest path:'
print shortest
shortest = dpShortestPath(g, nodes[0], nodes[4])
print 'The shortest path: DP'
print shortest
# test3(Digraph)
def bigTest2(kind, numNodes = 25, numEdges = 200):
global numCalls
nodes = []
for name in range(numNodes):
nodes.append(Node(str(name)))
g = kind()
for n in nodes:
g.addNode(n)
for e in range(numEdges):
src = nodes[random.choice(range(0, len(nodes)))]
dest = nodes[random.choice(range(0, len(nodes)))]
g.addEdge(Edge(src, dest))
print g
numCalls = 0
print shortestPath(g, nodes[0], nodes[4])
print 'Number of calls to shortest path =', numCalls
numCalls = 0
print dpShortestPath(g, nodes[0], nodes[4])
print 'Number of calls to dp shortest path =', numCalls
bigTest2(Digraph)
|
b9b4a570c69545d84b06d685385c1a0f3e5091b5
|
ledbagholberton/holbertonschool-machine_learning
|
/math/0x00-linear_algebra/9-let_the_butcher_slice_it.py
| 476 | 4.21875 | 4 |
#!/usr/bin/env python3
"""FUnction which slice matrix
"""
import numpy as np
matrix = np.array([[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12],
[13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24]])
mat1 = matrix[1:3]
mat2 = matrix[0:, 2:4]
mat3 = matrix[1:, 3:]
print("The middle two rows of the matrix are:\n{}".format(mat1))
print("The middle two columns of the matrix are:\n{}".format(mat2))
print("The bottom-right, square, 3x3 matrix is:\n{}".format(mat3))
|
93659380cf303b40c95a940cb38fbbff98251244
|
chinmay81098/interview-coding-questions
|
/matrix_multiply.py
| 906 | 3.953125 | 4 |
def product_of_mtx(r1,c1,r2,c2):
mtx3 = []
if c1 != r2:
return "Product not possible"
else:
for i in range(r1):
row = []
for k in range(c2):
s = 0
for j in range(c1):
s = s+ mtx1[i][j]*mtx2[j][k]
row.append(s)
mtx3.append(row)
return mtx3
r1 = int(input("Enter rows of first: "))
c1 = int(input("Enter columns of first: "))
mtx1 = []
for i in range(r1):
row = list(map(int,input().split()))
mtx1.append(row)
print("\n")
r2 = int(input("Enter rows of second: "))
c2 = int(input("Enter columns of second: "))
mtx2 = []
for i in range(r2):
row = list(map(int,input().split()))
mtx2.append(row)
output = product_of_mtx(r1,c1,r2,c2)
print('Product of Matrices is:')
for i in range(r1):
for j in range(c2):
print(output[i][j],end=" ")
print()
|
57a1479f78f4145a9d47f7b100266a7c64f475de
|
jayesh580/my_python
|
/chapter7/14_star.py
| 111 | 3.96875 | 4 |
star = int(input("Enter the number of star you want to print: "))
for i in range(star):
print("*" * (i+1))
|
def5415e9671a357a5d7a54c56dc3a89bf2d86e5
|
HankerZheng/LeetCode-Problems
|
/python/213_House_Robber_II.py
| 1,403 | 3.90625 | 4 |
# After robbing those houses on that street,
# the thief has found himself a new place for his thievery so that he will not get too much attention.
# This time, all houses at this place are arranged in a circle.
# That means the first house is the neighbor of the last one.
# Meanwhile, the security system for these houses remain the same as for those in the previous street.
# Given a list of non-negative integers representing the amount of money of each house,
# determine the maximum amount of money you can rob tonight without alerting the police.
# Credits:
# Special thanks to @Freezen for adding this problem and creating all test cases.
# Subscribe to see which companies asked this question
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def rob_house(nums):
dp = [0,0,0]
for i, num in enumerate(nums):
if i == 0:
dp[0] = nums[0]
elif i == 1:
dp[1] = max(nums[0], nums[1])
else:
dp[i%3] = max(num + dp[(i-2)%3], dp[(i-1)%3])
return dp[i%3]
if len(nums) <= 3:
return max([0] + nums)
return max(nums[0]+rob_house(nums[2:-1]), rob_house(nums[1:]))
if __name__ == '__main__':
sol = Solution()
print sol.rob([1,2,3,4,5,3,2])
|
2d7b031efe2ffde9ce92d2826da5a179dc02e6b9
|
HymEric/LeetCode
|
/python/207-课程表/207.py
| 3,460 | 3.546875 | 4 |
# -*- coding: utf-8 -*-
# @Time : 2020/2/6 0006 10:02
# @Author : Erichym
# @Email : [email protected]
# @File : 207.py
# @Software: PyCharm
"""
现在你总共有 n 门课需要选,记为 0 到 n-1。
在选修某些课程之前需要一些先修课程。 例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示他们: [0,1]
给定课程总量以及它们的先决条件,判断是否可能完成所有课程的学习?
示例 1:
输入: 2, [[1,0]]
输出: true
解释: 总共有 2 门课程。学习课程 1 之前,你需要完成课程 0。所以这是可能的。
示例 2:
输入: 2, [[1,0],[0,1]]
输出: false
解释: 总共有 2 门课程。学习课程 1 之前,你需要先完成课程 0;并且学习课程 0 之前,你还应先完成课程 1。这是不可能的。
说明:
输入的先决条件是由边缘列表表示的图形,而不是邻接矩阵。详情请参见图的表示法。
你可以假定输入的先决条件中没有重复的边。
提示:
这个问题相当于查找一个循环是否存在于有向图中。如果存在循环,则不存在拓扑排序,因此不可能选取所有课程进行学习。
通过 DFS 进行拓扑排序 - 一个关于Coursera的精彩视频教程(21分钟),介绍拓扑排序的基本概念。
拓扑排序也可以通过 BFS 完成。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/course-schedule
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
def canFinish(self, numCourses: int, prerequisites:list) -> bool: # BFS
indegrees=[0 for _ in range(numCourses)]
adjaciency=[[] for _ in range(numCourses)]
# 完成邻接矩阵和入度表
for cur,pre in prerequisites:
indegrees[cur]+=1
adjaciency[pre].append(cur)
queue=[] # for 0 indegree
cnt=numCourses # 计算还剩几个课程需要完成
# 初始装入入度是0的节点
for i in range(numCourses):
if not indegrees[i]:
queue.append(i)
# 拓扑排序
while queue:
pre=queue.pop(0)
cnt-=1
for cur in adjaciency[pre]:
indegrees[cur]-=1
if indegrees[cur]==0:
queue.append(cur)
return cnt==0
def canFinish2(self, numCourses: int, prerequisites:list) -> bool: # DFS
def dfs(i,adjacency,flags):
if flags[i]==-1: return True
if flags[i]==1: return False
# 已被当前节点启动的DFS访问:i == 1。
flags[i]=1
for j in adjacency[i]:
if not dfs(j,adjacency,flags):
return False
# 已被其他节点启动的DFS访问:i == -1;
flags[i]=-1
return True
adjacency=[[] for _ in range(numCourses)]
# 未被 DFS 访问:i == 0;
flags=[0 for _ in range(numCourses)]
for cur,pre in prerequisites:
adjacency[pre].append(cur)
for i in range(numCourses):
if not dfs(i,adjacency,flags):
return False
return True
if __name__=="__main__":
n = 2
pre= [[1,0],[0,1]]
so=Solution()
a=so.canFinish2(n,pre)
print(a)
|
e8f2a4a83c6680fe5798568d0f13d08065fca8c4
|
gentov/RBE550-SearchAlgorithms
|
/Graph.py
| 3,637 | 3.859375 | 4 |
from Node import *
from tkinter import *
"""
the graph class handles all of the methods related to the grid. That includes: making it,
finding node neighbors, and finding node indexes and coordinates.
"""
class Graph():
def __init__(self, nodesTall = 4 ,nodesWide = 4):
self.nodesTall = nodesTall
self.nodesWide = nodesWide
self.graph = [[0 for i in range(nodesWide)] for j in range(nodesTall)]
self.makeGraph()
def makeGraph(self):
nodeNumber = 0
for i in range(self.nodesTall):
for j in range(self.nodesWide):
self.graph[i][j] = Node(number=nodeNumber, row = i, column = j)
nodeNumber+=1
def print(self):
for i in range(self.nodesTall):
for j in range(self.nodesWide):
print(i,j,self.graph[i][j].number)
def getNodeIndexes(self, nodeNumber):
row = int(nodeNumber/self.nodesWide)
column = nodeNumber % self.nodesWide
return [row, column]
def getNodeNumber(self, row, column):
number = row*self.nodesWide + column%self.nodesWide
return number
def getNodeNeighbors(self, nodeNumber):
# N,E,S,W
neighbors = []
row = self.getNodeIndexes(nodeNumber)[0]
column = self.getNodeIndexes(nodeNumber)[1]
#If we have neighbors to the north
if(row > 0):
neighbors.append(self.graph[row - 1][column].number)
# If we have neighbors to the east
if (column < self.nodesWide - 1):
neighbors.append(self.graph[row][column + 1].number)
# If we have neighbors to the south
if (row < self.nodesTall - 1):
neighbors.append(self.graph[row + 1][column].number)
# If we have neighbors to the west
if (column > 0):
neighbors.append(self.graph[row][column - 1].number)
#NW, NE, SW, SE
# If we have neighbors to the north and west
if (row > 0 and column > 0):
neighbors.append(self.graph[row - 1][column - 1].number)
#north east
if (row > 0 and column < self.nodesWide - 1):
neighbors.append(self.graph[row - 1][column + 1].number)
# If we have neighbors to the south west
if (row < self.nodesTall - 1 and column > 0):
neighbors.append(self.graph[row + 1][column - 1].number)
# south east
if (row < self.nodesTall - 1 and column < self.nodesWide - 1):
neighbors.append(self.graph[row + 1][column + 1].number)
return neighbors
def getFourNodeNeighbors(self, nodeNumber):
# N,E,S,W
neighbors = []
row = self.getNodeIndexes(nodeNumber)[0]
column = self.getNodeIndexes(nodeNumber)[1]
#If we have neighbors to the north
if(row > 0):
neighbors.append(self.graph[row - 1][column].number)
# If we have neighbors to the east
if (column < self.nodesWide - 1):
neighbors.append(self.graph[row][column + 1].number)
# If we have neighbors to the south
if (row < self.nodesTall - 1):
neighbors.append(self.graph[row + 1][column].number)
# If we have neighbors to the west
if (column > 0):
neighbors.append(self.graph[row][column - 1].number)
return neighbors
def makeNodeFromNumber(self, nodeNumber):
# Grab the indexes of that node so we can get our node object
nodeIndexes = self.getNodeIndexes(nodeNumber)
# we have our node object
madeNode = self.graph[nodeIndexes[0]][nodeIndexes[1]]
return madeNode
|
3917810b7eb2cae6c6c04a9c73e648d36f5c8514
|
marcluettecke/programming_challenges
|
/python_scripts/string_difference.py
| 3,354 | 4.1875 | 4 |
"""
Function to solve the following quiz, interesting for repeated sorting methods.
Given two strings s1 and s2, we want to visualize how different the two strings are. We will only take into account
the lowercase letters (a to z). First let us count the frequency of each lowercase letters in s1 and s2.
s1 = "A aaaa bb c"
s2 = "& aaa bbb c d"
s1 has 4 'a', 2 'b', 1 'c'
s2 has 3 'a', 3 'b', 1 'c', 1 'd'
So the maximum for 'a' in s1 and s2 is 4 from s1; the maximum for 'b' is 3 from s2. In the following we will not
consider letters when the maximum of their occurrences is less than or equal to 1.
We can resume the differences between s1 and s2 in the following string: "1:aaaa/2:bbb" where 1 in 1:aaaa stands for
string s1 and aaaa because the maximum for a is 4. In the same manner 2:bbb stands for string s2 and bbb because the
maximum for b is 3.
The task is to produce a string in which each lowercase letters of s1 or s2 appears as many times as its maximum if
this maximum is strictly greater than 1; these letters will be prefixed by the number of the string where they appear
with their maximum value and :. If the maximum is in s1 as well as in s2 the prefix is =:.
In the result, substrings (a substring is for example 2:nnnnn or 1:hhh; it contains the prefix) will be in decreasing
order of their length and when they have the same length sorted in ascending lexicographic order (letters and digits
- more precisely sorted by codepoint); the different groups will be separated by '/'.
"""
def mix(s1, s2):
"""
Function to compare two strings and return comparison in pre-defined output.
Args:
s1: string one
s2: string two
Returns:
string in predefined output, with very specific ordering.
"""
result_strings = []
# build dictionaries with letter counts
dict1, dict2 = {letter: s1.count(letter) for letter in s1}, {letter: s2.count(letter) for letter in s2}
# build list of all lowercase letters of boh strings
lowercase_letter = [letter for letter in set(s1).union(set(s2)) if letter.islower()]
# iterate through lowercase_letters and append appropriate string
for i, l in enumerate(lowercase_letter):
# ignore lettercounts < 1
if (l in dict1 and dict1[l] > 1) and (l in dict2 and dict2[l] > 1):
# find greater count to build string
if dict1[l] > dict2[l]:
result_strings.append("{}:{}".format(1, l * dict1[l]))
elif dict1[l] == dict2[l]:
result_strings.append("=:{}".format(l * dict1[l]))
else:
result_strings.append("{}:{}".format(2, l * dict2[l]))
elif (l in dict1 and dict1[l] > 1) and not (l in dict2 and dict2[l] > 1):
result_strings.append("{}:{}".format(1, l * dict1[l]))
elif (l in dict2 and dict2[l] > 1) and not (l in dict1 and dict1[l] > 1):
result_strings.append("{}:{}".format(2, l * dict2[l]))
# ordering, first (therefore conducted last and so on) by length, then by group, 1,2, or =,
# and then alphabetically of the letter counted
result_strings = sorted(result_strings, key=lambda entry: entry[2])
result_strings = sorted(result_strings, key=lambda entry: 3 if entry[0] == "=" else int(entry[0]))
return "/".join(sorted(result_strings, key=len, reverse=True))
|
cc7c8831ee0c2ad6c8fa35a806284227ef135809
|
DanielHowe/DanielHowe
|
/codeExamples/GraphicsProgramming/Games/calendar.py
| 504 | 4.15625 | 4 |
import calendar
from datetime import *
def mainCalendar():
#month = requestInteger("What month were you born?")
month = 2
#day = requestInteger("What day were you born?")
day = 9
#year = requestInteger("What year were you born?")
year = 1984
# Character formatting
lengthSpacing = 0
widthSpacing = 0
print 'Here is your birthday month\n'
print calendar.prmonth(year,month)
print '\n'
print date.today()
print date.days
print (date.today() - date(year,month,day)).days
|
0c4b8ca249da2ea1193a31f56adcb2292f5f3dc6
|
tszreder/python_day2
|
/Day2/conditionals.py
| 2,410 | 3.75 | 4 |
# Wyrażenie trójargumentowe
a = 25
b = 30
print(b) if a<b else print(a)
'''
P48
Napisz program, który wczyta od użytkownika liczbę całkowitą i bez użycia instrukcji if
wyświetli informację, czy jest to liczba parzysta, czy nieparzysta
'''
#print("PARZYSTA" if int(input("Podaj liczbę: ")) % 2 == 0 else "NIEPARZYSTA")
# instrukcja try to podstawowa obsługa błędów
'''
try:
print("NIEPARZYSTA" if int(input("Podaj liczbę: ")) % 2 else "PARZYSTA")
except:
print("TO NIE JEST LICZBA")
'''
'''
Ćwiczenie P49
Wykonaj prosty test poprawności logowania
Jeżeli użytkownik podał login: admin i hasło: admin – przejdź do panelu
administratora
Jeżeli użytkownik podał login: user i hasło: user – przejdź do panelu
użytkownika
W przeciwnym razie wyświetl stosowny komunikat
'''
#Logowanie na podstawie listy użytkowników
# Jeżeli błędne hasło będzie podane 3 razy u użytkownika to zablokuj mu konto
# isLogged = False
# for user in users:
# if login == user[0] and password == user[1]:
# isLogged = True
# if user[2] == "ROLE_ADMIN":
# print("Panel Admina")
# break
# else:
# print("PANEL USERA")
# break
# print("" if isLogged else "Błędny login lub hasło")
users = [
["mk","mk123","ROLE_ADMIN", True, 0],
["kk","kk123","ROLE_USER", True, 0],
["ll","ll123","ROLE_USER", True, 0]
]
isLogged = False
while(isLogged == False):
login = input("Podaj login")
for user in users:
#sprawddzam czy jest taki użytkownik
if login == user[0] and user[3] == True:
password = input("Podaj hasło")
#sprawdzam czy podał dobre hasło
if password == user[1]:
isLogged = True
# sprawdzam uprawnienia
if user[2] == "ROLE_ADMIN":
print("PANEL ADMINISTRATORA")
break
else:
print("PANEL USERA")
break
else:
print("BŁĘDNE HASŁO")
user[4] +=1
if user[4] == 3:
user[3] = False
break
elif login == user[0] and user[3] == False:
print("KONTO ZABLOKOWANE!")
break
# if isLogged == False:
# print("BŁĘDNY LOGIN")
|
b00a0c46600231d9bed736b656c9f97e919edb7a
|
ssmmchoi/python1
|
/workspace/chap03_DataStructure/exam/exam02.py
| 858 | 3.625 | 4 |
'''
step02 문제
문1) message에서 'spam' 원소는 1 'ham' 원소는 0으로 dummy 변수를 생성하시오.
<조건> list + for 형식1) 적용
<출력결과>
[1, 0, 1, 0, 1]
문2) message에서 'spam' 원소만 추출하여 spam_list에 추가하시오.
<조건> list + for + if 형식2) 적용
<출력결과>
['spam', 'spam', 'spam']
'''
message = ['spam', 'ham', 'spam', 'ham', 'spam']
print(message)
# 문1) 첫 번째 형식
dummy = [1 if m == 'spam' else 0 for m in message]
print(dummy) # [1, 0, 1, 0, 1]
dummy = []
dummy = [dummy.append(1) if m=='spam' else dummy.append(0) for m in message]
print(dummy) ######### error... # [None, None, None, None, None]
# 문2) 두 번째 형식
spam_list = [m for m in message if m == 'spam']
print(spam_list) # ['spam', 'spam', 'spam']
|
3a8d21c2d294927e93804da6a79ac19b04c3b369
|
ljia2/leetcode.py
|
/solutions/range/253.Meeting.Room.II.py
| 4,947 | 4 | 4 |
from heapq import heappop, heappush
class Solution:
def minMeetingRooms(self, intervals):
"""
Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei),
find the minimum number of conference rooms required.
Example 1:
Input: [[0, 30],[5, 10],[15, 20]]
Output: 2
Example 2:
Input: [[7,10],[2,4]]
Output: 1
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
:type intervals: List[List[Int]]
:rtype: int
"""
if not intervals:
return 0
# sorting meetings by their start
intervals.sort(key=lambda x: x[0])
# hint: use list and heappop/heappush from heapq to mimic priorityQueue
hp = [intervals[0][1]]
for start, end in intervals[1:]:
# peek the meeting with the earliest end time, if it ends before start, assign its room to new meeting
if hp and hp[0] <= start:
# the room with min ending time i; interval is overlap with i, push i back and break
# otherwise, keep popping booked room that had ended before interval.start.
heappop(hp)
heappush(hp, end)
return len(hp)
s = Solution()
print(s.minMeetingRooms([[0, 30], [15, 20], [5, 10]]))
# Scan the line
class LinearSolution:
def minMeetingRooms(self, intervals):
"""
Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei),
find the minimum number of conference rooms required.
Example 1:
Input: [[0, 30],[5, 10],[15, 20]]
Output: 2
Example 2:
Input: [[7,10],[2,4]]
Output: 1
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
:type intervals: List[List[Int]]
:rtype: int
"""
if not intervals:
return 0
maxEnd = max(map(lambda x: x[1], intervals))
space = [0] * maxEnd
# sorting meetings by their start
intervals.sort()
for start, end in intervals:
space[start] += 1
space[end] -= 1
# iterate over each vertical space
# icnt indicates the # of intervals covering it.
icnt = 0
ans = 0
for i in range(len(space)):
icnt += space[i]
# the vertical line at position i is covered by sum intervals.
ans = max(ans, icnt)
return ans
s = LinearSolution()
print(s.minMeetingRooms([[0, 30], [15, 20], [5, 10]]))
# No priority Queue
# class SolutionII(object):
# def minMeetingRooms(self, intervals):
# """
# :type intervals: List[List[Int]
# :rtype: int
# """
#
# # If there are no meetings, we don't need any rooms.
# if not intervals:
# return 0
#
# used_rooms = 0
#
# # Separate out the start and the end timings and sort them individually.
#
# start_timings = sorted([s for s, _ in intervals])
# end_timings = sorted(e for _, e in intervals)
#
# L = len(intervals)
#
# # The two pointers in the algorithm: e_ptr and s_ptr.
# end_pointer = 0
# start_pointer = 0
#
# # Until all the meetings have been processed
# while start_pointer < L:
#
# # If there is a meeting that has ended by the time the meeting at `start_pointer` starts
# if start_timings[start_pointer] >= end_timings[end_pointer]:
# # Free up a room and increment the end_pointer.
# used_rooms -= 1
# end_pointer += 1
#
# # We do this irrespective of whether a room frees up or not.
# # If a room got free, then this used_rooms += 1 wouldn't have any effect. used_rooms would
# # remain the same in that case. If no room was free, then this would increase used_rooms
# used_rooms += 1
# start_pointer += 1
#
# return used_rooms
# Follow up: What if the times are given as 10AM - 11:30AM or 11:00AM to 1PM
import re
class Interval(object):
def __init__(self, start, end):
self.start = start
self.end = end
class Solution(object):
def translate(self, times):
ans = []
for time in times:
ts = re.split(r"-", time.trim().lower().replace("to", "-"))
start = self.convert(ts[0])
end = self.convert(ts[1])
ans.append(Interval(start, end))
return ans
def convert(self, ts):
i = ts.find("am")
base = 0 if i > 0 else 12
ts = ts[:i]
hm = ts.split(":")
h = int(hm[0]) + base
m = int(hm[1])
return h * 60 + m
|
6570c97c43af3dddb06fc0ddfa16e906e541f969
|
caozongliang/1805
|
/11day/2列表循环练习.py
| 273 | 3.515625 | 4 |
a = []
for i in range(1,101,2):
a.append(i)
#print(a)
a.pop()
#print("删除最后一个",a)
a.pop(0)#删除索引上的值
print(a)
a.remove(3)#删除指定值
print(a)
del a[0]#索引
print(a)#系统提供删除方法
#number = a[18]
#print(number,'laowang')
|
2a6e4a7b0e7ca8ca134419372afa4a881eb46c13
|
qian316/Python_demo
|
/第9章 魔法方法、特性和迭代器/init_demo.py
| 1,178 | 3.828125 | 4 |
# _*_ coding:utf-8 _*_
# 构造函数__init__
class FooBar:
def __init__(self):
self.somevar = 42
f = FooBar()
print(f.somevar)
# 继承时候对构造函数的处理方法
## 第一种是调用未关联的超类构造函数
# class Brid:
# def __init__(self):
# self.hungry = True
# def eat(self):
# if self.hungry:
# print('Aaaah...')
# self.hungry = False
# else:
# print('No,Thanks!')
#
# class SongBride(Brid):
# def __init__(self):
# Brid.__init__(self)
# self.sound = 'Squawk!'
# def sing(self):
# print(self.sound)
#
# sb = SongBride()
# print(sb.sing())
# print(sb.eat())
# print(sb.eat())
## 第二种使用函数super()
class Brid:
def __init__(self):
self.hungry = True
def eat(self):
if self.hungry:
print('Aaaah...')
self.hungry = False
else:
print('No,Thanks!')
class SongBride(Brid):
def __init__(self):
super().__init__()
self.sound = 'Squawk!'
def sing(self):
print(self.sound)
sb = SongBride()
print(sb.sing())
print(sb.eat())
print(sb.eat())
|
de1b44d8403319daff4a882a72f31a04240d1828
|
RoastedTurkey/ECTTP
|
/Class_Code/Les_10_Example/Les_10_Example.pyde
| 1,015 | 3.515625 | 4 |
scramble("Kip", "kaars")
def scramble(word1, word2):
lengthWord = max(len(word1), len(word2))
result = ""
for i in range(0,lengthWord):
if (len(word1) < i):
result+= word1[i]
else:
if(i != lengthWord -1):
result+='0'
if (len(word2) < i):
result+= word2[i]
else:
if(i != lengthWord -1):
result+='0'
if(result[len(result)-1] == '0'):
result = result[0 : len(result)-1]
return result
'''
myList = [ "hoi", "doei" ]
myList2 = []
myList2.append("hoi")
myList2.append("doei")
for kip in [0, 1] :
for inceptionKip in range(0,len(myList[kip])):
if(myList[kip][inceptionKip] == 'o':
myList[kip][inceptionKip] = 'a'
print myList[kip][inceptionKip]
kip =0
while (kip < len(myList)):
print myList[kip]
kip +=1
for (int kip = 0 ; kip < myList.Length() ; kip+=1 )
{
print myList[kip]
}
'''
|
982f08c89e239fc8ce4bdb90a81b0cde8d26fd05
|
Shnobs/PythonOzonNS
|
/Lesson7/insert_sort.py
| 560 | 3.84375 | 4 |
import random
def insert_sort(arr):
result = arr.copy()
for i in range(1, len(result)):
currentValue = result[i]
currentPosition = i
while currentPosition > 0 and result[currentPosition - 1] > currentValue:
result[currentPosition] = result[currentPosition -1]
currentPosition = currentPosition - 1
result[currentPosition] = currentValue
return result
random_list = []
for i in range(10):
random_list.append(random.randint(1,100))
print(random_list)
print(insert_sort(random_list ))
|
c55153906343a57464290f20672082ffb82911eb
|
alekswatts/python
|
/p4u/3_dz/cycle.py
| 381 | 3.890625 | 4 |
keywords ="""
netflix ukraine
netflix сериалы
netflix українською
netflix это
netflix фильмы
netflix ru
netflix на русском
netflix movies
""".strip().split("\n")
print(keywords)
word = "netflix"
for keyword in enumerate(keywords):
print("Word: ", keyword, i)
if word in keyword:
print("Word in: ", keyword)
print("All done")
|
35178a2f86a45d4acb431e8c0649abd6dfffe42b
|
zhao-staff-officer/python-code
|
/Python_/day34.获取列表元素/ex34.py
| 448 | 3.546875 | 4 |
list1 = ['Google', 'Runoob', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
list4 = ['red', 'green', 'blue', 'yellow', 'white', 'black']
print("正序访问list1元素")
print(list1[0],list1[1],list1[2])
print("反序访问list1元素")
print(list1[-1],list1[-2],list1[-3])
print("截取list2字符")
print("list2[0:4]",list2[0:4])
print("list2[1:-2]",list2[1:-2])
print("list2[:-1]",list2[:-1])
print("list2[1:]",list2[1:])
|
5f9aa388dc0c1c3fb2879db5903afbed98c700c5
|
daianasousa/Ensinando-com-as-Tartarugas
|
/Funcoes_em_toda_Parte.py
| 1,941 | 3.734375 | 4 |
from turtle import *
from random import *
#uma função para mover a tartaruga para uma posição aleatória
def moveToRandomLocation():
penup()
setpos( randint(-700,700) , randint(-700,700))
pendown()
#uma função para desenhar uma estrela de um tamanho específico
def drawStar(starSize, starColour):
color(starColour)
pendown()
begin_fill()
for side in range(5):
left(144)
forward(starSize)
end_fill()
penup()
#uma função para desenhar um planeta de um tamanho específico
def drawPlanet(starSize, starColour):
color(starColour)
pendown()
begin_fill()
for side in range(360):
left(1)
forward(starSize)
end_fill()
penup()
speed(30)
#isso desenha um fundo preto
bgcolor("black")
#desenha 200 estrelas brancas e 200 estrelas Azuis (tamanho,posições aleatórias)
for star in range(200):
moveToRandomLocation()
drawStar( randint(1,5) , "White")
for star in range(200):
moveToRandomLocation()
drawStar( randint(1,5) , "SkyBlue")
#desenha Planetas e sol (tamanho,posições especificas)
for Planeta in range(1):
#SOL
penup()
setpos(-700,-100)
pendown()
drawPlanet(3, "gold")
#MERCURIO
penup()
setpos(-400,30)
pendown()
drawPlanet(0.4, "gray")
#VENUS
penup()
setpos(-300,10)
pendown()
drawPlanet(0.7,"DarkGoldenrod")
#TERRA
penup()
setpos(-170,-10)
pendown()
drawPlanet(1.1,"LightSkyBlue")
#MARTE
setpos(-25,0)
pendown()
drawPlanet(0.8,"DarkRed")
#JUPITE
penup()
setpos(130,-30)
pendown()
drawPlanet(1.5, "Khaki")
#SATURNO
penup()
setpos(300,0)
pendown()
drawPlanet(0.9,"PaleGoldenrod")
#URANO
penup()
setpos(410,20)
pendown()
drawPlanet(0.6, "blue")
#NETUNO
penup()
setpos(500,25)
pendown()
drawPlanet(0.4,"DeepSkyBlue")
hideturtle()
done()
|
6141f51504cd085b38edac4071dfc3b38a141c31
|
marybahati/PYTHON
|
/MAKING LISTS.py
| 5,769 | 3.765625 | 4 |
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 22:20:52) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> fruits=['banana','apple','mango','orange','melon']
>>> for fruit in fruits:
print(fruits)
['banana', 'apple', 'mango', 'orange', 'melon']
['banana', 'apple', 'mango', 'orange', 'melon']
['banana', 'apple', 'mango', 'orange', 'melon']
['banana', 'apple', 'mango', 'orange', 'melon']
['banana', 'apple', 'mango', 'orange', 'melon']
>>> numbers=[1,2,3,4,5,6,7,8,9,]
>>> for number in numbers
SyntaxError: invalid syntax
>>> for number in numbers
SyntaxError: invalid syntax
>>> for number in numbers:
print(number)
1
2
3
4
5
6
7
8
9
>>> fruits[0]
'banana'
>>> fruits[4]
'melon'
>>> fruits[0:4]
['banana', 'apple', 'mango', 'orange']
>>> fruits[3:5]
['orange', 'melon']
>>> fr
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
fr
NameError: name 'fr' is not defined
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> c=a+b
>>> c
[1, 2, 3, 4, 5, 6]
>>> d=a*3
>>> d
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> fruits
['banana', 'apple', 'mango', 'orange', 'melon']
>>> fruits.append('grapes')
>>> fruits
['banana', 'apple', 'mango', 'orange', 'melon', 'grapes']
>>> fruits.extend(['peach','kiwi'])
>>> fruits
['banana', 'apple', 'mango', 'orange', 'melon', 'grapes', 'peach', 'kiwi']
>>> fruits.remove('melon')
>>> fruits
['banana', 'apple', 'mango', 'orange', 'grapes', 'peach', 'kiwi']
>>> fruits.sort()
>>> fruits
['apple', 'banana', 'grapes', 'kiwi', 'mango', 'orange', 'peach']
>>> fruits.reverse()
>>> fruits
['peach', 'orange', 'mango', 'kiwi', 'grapes', 'banana', 'apple']
>>> fruits.pop()
'apple'
>>> fruits
['peach', 'orange', 'mango', 'kiwi', 'grapes', 'banana']
>>> del fruits[0]
>>> fruits
['orange', 'mango', 'kiwi', 'grapes', 'banana']
>>> fruits.replace('banana','dates')
Traceback (most recent call last):
File "<pyshell#49>", line 1, in <module>
fruits.replace('banana','dates')
AttributeError: 'list' object has no attribute 'replace'
>>> fruits.replace('banana','apple')
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
fruits.replace('banana','apple')
AttributeError: 'list' object has no attribute 'replace'
>>> numbers
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> sum(numbers)
45
>>> sum(fruits)
Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
sum(fruits)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> min(numbers)
1
>>> max(numbers)
9
>>> fruits.append('banana')
>>> fruits
['orange', 'mango', 'kiwi', 'grapes', 'banana', 'banana']
>>> fruits.count('banana')
2
>>> n=range(10)
>>> for x in n
SyntaxError: invalid syntax
>>> for x in n:
print(x)
0
1
2
3
4
5
6
7
8
9
>>> m=range(10,20)
>>> for x in m:
print(x)
10
11
12
13
14
15
16
17
18
19
>>> for f in fruits:
print(f)
orange
mango
kiwi
grapes
banana
banana
>>> e=[x*10 for x in a]
>>> e
[10, 20, 30]
>>> f=[x*2 for x in e]
>>> f
[20, 40, 60]
>>> g=range(25,50)
>>> h=[x*x for x in g]
>>> h
[625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]
>>> for x in g:
h.append(x)
>>> h
[625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
>>> h=[]
>>> for x in g:
y=x*x
h.append(y)
>>> h
[625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]
>>> v=[100,200,300,400,500]
>>> y[v/7 %]
SyntaxError: invalid syntax
>>> y[v%7]
Traceback (most recent call last):
File "<pyshell#91>", line 1, in <module>
y[v%7]
TypeError: unsupported operand type(s) for %: 'list' and 'int'
>>> y[v/7]
Traceback (most recent call last):
File "<pyshell#92>", line 1, in <module>
y[v/7]
TypeError: unsupported operand type(s) for /: 'list' and 'int'
>>> y[% x/7]
SyntaxError: invalid syntax
>>> y=[% of v/7]
SyntaxError: invalid syntax
>>> for x in v:
y=v/7
h.append
Traceback (most recent call last):
File "<pyshell#98>", line 2, in <module>
y=v/7
TypeError: unsupported operand type(s) for /: 'list' and 'int'
>>> y=[v%7 for y in v]
Traceback (most recent call last):
File "<pyshell#99>", line 1, in <module>
y=[v%7 for y in v]
File "<pyshell#99>", line 1, in <listcomp>
y=[v%7 for y in v]
TypeError: unsupported operand type(s) for %: 'list' and 'int'
>>> y=[z%7 for z in x]
Traceback (most recent call last):
File "<pyshell#101>", line 1, in <module>
y=[z%7 for z in x]
TypeError: 'int' object is not iterable
>>> x=[100,200,300,400,500]
>>> y=[z%7 for z in x]
>>> y
[2, 4, 6, 1, 3]
>>>
>>>
>>>
>>>
>>>
>>>
>>> for z in x:
SyntaxError: unexpected indent
>>> for z in x:
q=z%7
y.append(q)
>>> y
[2, 4, 6, 1, 3, 2, 4, 6, 1, 3]
>>> y=[z%7 for z in x]
>>> y
[2, 4, 6, 1, 3]
>>> a=range(99-109)
>>> b=[z*z for z in a]
>>> b
[]
>>> for x in a:
s=x*
SyntaxError: invalid syntax
>>> for x in a:
b=x*
SyntaxError: invalid syntax
>>> for x in a:
b=x*x
>>> b
[]
>>> n=range(99-109)
>>> for x in n:
print(x*x)
>>> x
[100, 200, 300, 400, 500]
>>>
>>>
>>>
>>>
>>> a=range(99-109)
>>> b=[x*x for x in a]
>>> b
[]
>>> for x in a:
print(a*a)
>>> a
range(0, -10)
>>> a=range(99,109)
>>> b=[x*x for x in a}
SyntaxError: invalid syntax
>>> b=[x*x for x in a]
>>> b
[9801, 10000, 10201, 10404, 10609, 10816, 11025, 11236, 11449, 11664]
>>> nested=[[1,2,3],[4,5,6],[7,8,9]]
>>> j=range(0,10)
SyntaxError: unexpected indent
>>> j=range(0,10)
>>> j
range(0, 10)
>>>
|
e8d40f6035d178f81ae1f61d95c5dfa1440ffeb8
|
WouterDelouw/5WWIPython
|
/Toets 2/Niet-starter.py
| 204 | 3.78125 | 4 |
# invoer
getal = float(input('geef een getal tussen 0 en 1: '))
som, exponent = 0, 0
# berekeningen
while som < getal:
exponent += 1
som += (1 / (pow(2, exponent)))
# uitvoer
print(exponent, som)
|
0c3447af7c6c9e6871ec06ef322ae0563b03aa54
|
daniel-reich/turbo-robot
|
/k87ztfzqrpPHvgNWR_6.py
| 1,040 | 3.875 | 4 |
"""
Given a list of strings _depicting a row of buildings_ , create a function
which **sets the gap between buildings** as a given amount.
### Examples
widen_streets([
"### ## #",
"### # ## #",
"### # ## #",
"### # ## #",
"### # ## #"
], 3) ➞
[
"### ## #",
"### # ## #",
"### # ## #",
"### # ## #",
"### # ## #"
]
widen_streets([
"## ### ###",
"## ### ###",
"## ### ###",
"## ### ###"
], 2) ➞
[
"## ### ###",
"## ### ###",
"## ### ###",
"## ### ###"
]
widen_streets([
"# # # # #"
], 2) ➞
[
"# # # # #"
]
### Notes
* Buildings may be different sizes.
* There will always be a starting gap size of **one character**.
"""
def widen_streets(lst, n):
gaps = [i for i in range(len(lst[0])) if lst[-1][i] == " "]
return ["".join(" " * n if i in gaps else r[i] for i in range(len(r))) for r in lst]
|
d92e9d9228f92a39cefe12473fa73e9ded4763f1
|
queirozfcom/desafiohu1
|
/scripts/csvtosqlinsert
| 4,429 | 3.640625 | 4 |
#!/usr/bin/env python
import sys
import os
import re
from datetime import date
# convert a csv file into sql insert statements
# to insert those values into given table and rownames
def run(inputfile,outputfile,tablename,rownames):
if not os.path.isfile(inputfile):
raise Exception('\'{0}\' is not a valid filepath'.format(inputfile))
outputfile = relativetoabsolutepath(outputfile)
if os.path.isfile(outputfile):
print('Output file already exists; will overwrite.\n')
os.remove(outputfile)
inputfile = relativetoabsolutepath(inputfile)
firstline = "insert into {0}({1}) values \n".format(tablename,rownames)
fout = open(outputfile,'w')
fout.write(firstline)
with(open(inputfile)) as fin:
for line in fin:
# parse line to 'clean' values
outputline = parseline(line)
fout.write(outputline)
# last line will have a trailing comma, but we can remove it by hand
# and replace by a semicolon
fout.close()
# takes an input line and returns a line that's fit
# to be in an sql insert statement
def parseline(line):
outputline = '('
parts = line.split(',')
for part in parts:
value = part.lstrip().rstrip()
if isbraziliandate(value):
outputline += formatdate(value)
elif isboolean(value):
outputline += formatboolean(value)
elif isstring(value):
outputline += formatstring(value)
else:
outputline += value
outputline += ','
# a trailing comma will be added so we must strip it out
outputline = outputline.rstrip(',')
outputline += '),'
outputline += '\n'
return(outputline)
def usage():
message = """
Convert a CSV file into an SQL file containing inserts
Usage: ./csvtosqlinsert <inputfile> <outputdir> <tablename> <rownames>
Where:
<inputfile> is the path to the csv file
<outputdir> is the directory where the sql file should be written to
<tablename> is the table to use in the inserts
<rownames> is a comma-separated list of row names
"""
print(message)
######################################################
### FUNCTIONS TO PARSE TEXT INTO POSTGRES-FRIENDLY FORMATS
######################################################
def isboolean(txt):
if txt == '1' or txt == '0':
return(True)
else:
return(False)
def isbraziliandate(txt):
brazildatepattern = re.compile("^(\d{1,2})\/(\d{1,2})\/(\d{4})$")
if brazildatepattern.match(txt):
return(True)
else:
return(False)
def isstring(txt):
# for our purposes, it's a string if it's not a number
numberpat = re.compile("^\d+$")
if numberpat.match(txt):
return(False)
else:
return(True)
# encodes a value as postgresql boolean
def formatboolean(booleanstring):
if(booleanstring == '1'):
return('TRUE')
else:
return('FALSE')
# takes a brazilian style date and returns a ISO-date
# of form yyyy-mm-dd
def formatdate(braziliandate):
brazildatepattern = re.compile("^(\d{1,2})\/(\d{1,2})\/(\d{4})$")
matches = brazildatepattern.match(braziliandate)
day = matches.group(1)
month = matches.group(2)
year = matches.group(3)
dt = date(int(year),int(month),int(day))
# zero-padded days and months
# within single quotes
dateiso = "'"+dt.strftime('%Y-%m-%d')+"'"
return(dateiso)
# adds single quotes around a value
def formatstring(value):
# must escape single quotes for postgresql
output = re.sub("'","''",value)
# and add single quotes around (normal sql)
output = "'"+value+"'"
return(output)
######################################################
### HELPER FUNCTIONS
######################################################
def relativetoabsolutepath(relpath):
currentdir = os.path.dirname(os.path.realpath(__file__))
absolutepath = currentdir+'/'+relpath
return(relpath)
if __name__ == "__main__":
args = sys.argv
if len(args)!=5:
usage()
sys.exit(1)
else:
inputfile = args[1]
outputdir = args[2]
tablename = args[3]
rownames = args[4]
run(inputfile,outputdir,tablename,rownames)
|
dc37bbfe05d6f5f50c0ebb1a7972b1f50c6359ad
|
borjur/discrete_Structures
|
/Cesar Cipher/Ceaser_Cipher.py
| 1,776 | 3.65625 | 4 |
'''
Created on Mar 4, 2013
@author: Boris Jurosevic
CS 2430
Assignment: Ceaser Cipher
TUTORIAL: stackoverflow, youtube videos,python forum.
'''
import time
import string
from string import ascii_lowercase
def Ceaser(words, enter):
converts = ""
new = ""
for a in words:
if aDict.count(a):
if(enter == "encrypt"):
enc = into[aDict.index(a.lower())]
new = new + enc
'''if not (enter != "encrypt"):
print ("wrong spelling!")'''
elif(enter == "decrypt"):
dec = aDict[into.index(a)]
new = new + dec
'''if not (enter != "decrypt"):
print ("wrong spelling!")'''
else:
new = new + a
return new
aDict = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
into = []
convert = ""
encryption = ""
decryption = ""
print("Welcome to Ceaser Cipher")
enter = (input("Do you want to encrypt or decrypt? Please no capital letters "))
words = str(input("Enter the word you want to " + enter ))
shift = int(input("Enter the number of letters it is going to be shifted to the right "))
for a in range(0, len(aDict)):
b = len(aDict)
into.append((aDict[(a+shift)%b]))
if(enter == "encrypt"):
print ("This encrypted word is: %s" %(Ceaser(words, enter)))
elif(enter == "decrypt"):
print ("This decrypted word is: %s" %(Ceaser(words, enter)))
if not (enter == "encrypt" or enter == "decrypt"):
print (" Its not encrypted or decrypted. Please try again")
else:
print("You did not spell right encrypt or decrypt. Please no capital letters. Try again!")
|
55e82664af3679e60f4bef593164da2011c0a2b9
|
bgeer/ALDS
|
/Tutorial_2/2-2.py
| 5,869 | 3.515625 | 4 |
from matplotlib import pyplot as plt
import numpy as np
import time
import statistics as stats
# Schrijf hier de code voor opgave 2
def random_int_array(length):
array = np.random.randint(-128, high=127, size=length,
dtype=np.int8) # een array'tje met ints tussen de 0 en de 100 (exclusief)
return array
def quicksort(array, low, high):
counter = 0
if low >= high:
return array, counter
p, p_counter = partition(array, low, high)
array, counter1 = quicksort(array, low, p - 1)
array, counter2 = quicksort(array, p + 1, high)
counter += p_counter + counter1 + counter2
return array, counter
def partition(array, low, high):
counter = 0
pivot = array[high]
i = low
for j in range(low, high, 1):
if array[j] <= pivot:
temp = array[i]
array[i] = array[j]
array[j] = temp
i += 1
counter += 1
temp = array[i]
array[i] = array[high]
array[high] = temp
return i, counter
def quicksort_low(array, low, high):
counter = 0
if low >= high:
return array, counter
p, p_counter = partition_low(array, low, high)
array, counter1 = quicksort_low(array, low, p - 1)
array, counter2 = quicksort_low(array, p + 1, high)
counter += p_counter + counter1 + counter2
return array, counter
def partition_low(array, low, high):
counter = 0
pivot = min(array[low:high + 1])
i = array.tolist().index(pivot)
array[high], array[i] = array[i], array[high]
i = low
for j in range(low, high):
counter += 1
if array[j] <= pivot:
array[i], array[j] = array[j], array[i]
i += 1
array[i], array[high] = array[high], array[i]
return i, counter
def quicksort_med(array, low, high):
counter = 0
if low >= high:
return array, counter
p, p_counter = partition_med(array, low, high)
array, counter1 = quicksort_med(array, low, p - 1)
array, counter2 = quicksort_med(array, p + 1, high)
counter += p_counter + counter1 + counter2
return array, counter
def partition_med(array, low, high):
counter = 0
pivot = int(stats.median_high(array[low:high + 1]))
i = array.tolist().index(pivot)
array[high], array[i] = array[i], array[high]
i = low
for j in range(low, high):
counter += 1
if array[j] <= pivot:
array[i], array[j] = array[j], array[i]
i += 1
array[i], array[high] = array[high], array[i]
return i, counter
mean_std_max = []
stdev_std_max = []
mean_my_max = []
stdev_my_max = []
mean_my_med = []
stdev_my_med = []
mean_std_max_time = []
stdev_std_max_time = []
mean_my_max_time = []
stdev_my_max_time = []
mean_my_med_time = []
stdev_my_med_time = []
meetpunten = list(range(5, 201, 5))
for i in meetpunten:
quick1 = []
quick1_time = []
quick2 = []
quick2_time = []
quick3 = []
quick3_time = []
for j in range(50): # vijftig metingen per datapunt
array = random_int_array(i)
t1 = time.time()
res, compared1 = quicksort(array, 0, len(array) - 1)
t2 = time.time()
quick1_time.append(t2 - t1)
quick1.append(compared1)
t1 = time.time()
res, compared2 = quicksort_low(array, 0, len(array) - 1)
t2 = time.time()
quick2_time.append(t2 - t1)
quick2.append(compared2)
t1 = time.time()
res, compared3 = quicksort_med(array, 0, len(array) - 1)
t2 = time.time()
quick3_time.append(t2 - t1)
quick3.append(compared3)
mean_std_max.append(stats.mean(quick1))
stdev_std_max.append(stats.stdev(quick1))
mean_my_max.append(stats.mean(quick2))
stdev_my_max.append(stats.stdev(quick2))
mean_my_med.append(stats.mean(quick3))
stdev_my_med.append(stats.stdev(quick3))
mean_std_max_time.append(stats.mean(quick1_time))
stdev_std_max_time.append(stats.stdev(quick1_time))
mean_my_max_time.append(stats.mean(quick2_time))
stdev_my_max_time.append(stats.stdev(quick2_time))
mean_my_med_time.append(stats.mean(quick3_time))
stdev_my_med_time.append(stats.stdev(quick3_time))
plt.plot(meetpunten, mean_std_max, 'b-')
plt.fill_between(meetpunten, np.array(mean_std_max) - np.array(stdev_std_max),
np.array(mean_std_max) + np.array(stdev_std_max), color='b', alpha=0.3)
plt.plot(meetpunten, mean_my_max, 'r-')
plt.fill_between(meetpunten, np.array(mean_my_max) - np.array(stdev_my_max),
np.array(mean_my_max) + np.array(stdev_my_max), color='r', alpha=0.3)
plt.plot(meetpunten, mean_my_med, 'y-')
plt.fill_between(meetpunten, np.array(mean_my_med) - np.array(stdev_my_med),
np.array(mean_my_med) + np.array(stdev_my_med), color='y', alpha=0.3)
plt.xlabel("number of array elements")
plt.ylabel("Comparisons")
plt.legend(["Quicksort1(Normal)", "Quicksort2(Minimum)", "Quicksort3(Median)"], loc='upper left')
plt.show()
plt.plot(meetpunten, mean_std_max_time, 'b-')
plt.fill_between(meetpunten, np.array(mean_std_max_time) - np.array(stdev_std_max_time),
np.array(mean_std_max_time) + np.array(stdev_std_max_time), color='b', alpha=0.3)
plt.plot(meetpunten, mean_my_max_time, 'r-')
plt.fill_between(meetpunten, np.array(mean_my_max_time) - np.array(stdev_my_max_time),
np.array(mean_my_max_time) + np.array(stdev_my_max_time), color='r', alpha=0.3)
plt.plot(meetpunten, mean_my_med_time, 'y-')
plt.fill_between(meetpunten, np.array(mean_my_med_time) - np.array(stdev_my_med_time),
np.array(mean_my_med_time) + np.array(stdev_my_med_time), color='y', alpha=0.3)
plt.xlabel("number of array elements")
plt.ylabel("Time")
plt.legend(["Quicksort1(Normal)", "Quicksort2(Minimum)", "Quicksort3(Median)"], loc='upper left')
plt.show()
|
3f8b26e719d44d213e42121254b7b536d19f4d39
|
maliksh7/Data-Structure-and-Algorithms-in-Python
|
/Case Study of OOP via Python/oop.py
| 2,090 | 3.84375 | 4 |
class Address:
def __init__(self, house_no = 0, street = 0, city = "", country = ""):
self.house_no = house_no
self.street = street
self.city = city
self.country = country
def get_full_address(self):
return "H. No. "+ str(self.house_no) + ", Street "+ str(self.street) + ", "+ self.city + " "+ self.country
def __str__(self):
return self.get_full_address()
class Employee:
def __init__(self, id = 1, name = None, current_address = None, permanent_address = None):
self.id = id
self.name = name
self.current_address = current_address
self.permanent_address = permanent_address
def set_current_address(self,house_no,street,city,country):
self.current_address = Address(house_no,street,city,country)
def set_permanent_address(self,house_no,street,city,country):
self.permanent_address = Address(house_no,street,city,country)
def get_current_address(self):
return str(self.current_address)
def get_permanent_address(self):
return str(self.permanent_address)
def __str__(self):
return str(self.id) + " " + str(self.name) + " " + self.get_permanent_address()
class Lecturer(Employee):
def __init__(self):
super().__init__(id = 1, name = "Mr. Bigshot")
def __str__(self):
return "Lecturer: "+ str(self.id)+ " "+ str(self.name)+ str(self.get_permanent_address())
if __name__ == "__main__":
# Uncomment these to test out your code before run.py local
# a = Address()
# a.house_no = 2
# a.street = 3
# a.city = "Peshawar"
# a.country = "Pakistan"
# print(a.get_full_address())
# # print(a)
# e = Employee()
# e.set_current_address(1, 2, "Cape Town", "South Africa")
# print(e.get_current_address())
# e.set_permanent_address(4, 19, "Cape Town", "South Africa")
# print(e.get_permanent_address())
# print(e)
l = Lecturer()
l.set_permanent_address(44, 24, "KL", "Malaysia")
print(l.get_permanent_address())
print(l)
|
bd91b0ee12e6e201b5cbcf39608d012b29864938
|
dsztanko/Algorithms_practice
|
/binary_tree/node.py
| 400 | 3.609375 | 4 |
class Node(object):
def __init__(self, value, left, right):
self.value = value
self.left = left
self.right = right
if self.left is not None:
self.left.parent = self
if self.right is not None:
self.right.parent = self
self.visited = False
self.parent = None
def set_to_visited(self):
self.visited = True
|
ee6c8337b6029379f9bd3149b48bc4366f8a5723
|
rbozzini/python-repo
|
/examples/array_sum_functional_imperative.py
| 392 | 3.875 | 4 |
import functools
my_list = [1, 2, 3, 4, 5]
def add_it(x, y):
print("add_it(" + str(x) + ", " + str(y) + ")")
return (x + y)
# https://docs.python.org/3/library/functools.html
# Functional:
sum = functools.reduce(add_it, my_list)
print(sum)
# Lambda:
sum = functools.reduce(lambda x, y: x + y, my_list)
print(sum)
# Imperative:
sum = 0
for x in my_list:
sum += x
print(sum)
|
6b39168f8d402038b27fb4733dcfe34dc101ac8a
|
MysteriousSonOfGod/Python-2
|
/Lyceum/lyc2/pg_rgb_target.py
| 561 | 3.828125 | 4 |
import pygame
n = int(input())
k = int(input())
red, green, blue = (255, 0, 0), (0, 255, 0), (0, 0, 255)
if k % 3 == 0:
colors = [blue, green, red]
elif k % 3 == 1:
colors = [red, blue, green]
else:
colors = [green, red, blue]
size = n
n += k * n - size
pygame.init()
screen = pygame.display.set_mode((300, 300))
c = 0
while k > c:
pygame.draw.circle(screen, colors[c % 3], (n, n), n - c * size)
c += 1
pygame.display.update()
while 1:
pygame.time.delay(1000)
for i in pygame.event.get():
if i.type == pygame.QUIT: exit()
|
ae3579dd35fd375f39266c261013e28b6ab17a8e
|
iampaavan/Stacks_Queues_Deques_Python
|
/print_queue_challenge.py
| 1,186 | 3.59375 | 4 |
import random
class Queue:
def __init__(self):
self.items = []
def enqueue(self, item):
self.items.insert(0, item)
def dequeue(self):
if self.items:
return self.items.pop()
return None
def is_empty(self):
return self.items == []
class Job:
def __init__(self):
self.pages = random.randint(1, 11)
def print_page(self):
if self.pages > 0:
self.pages -= 1
def check_complete(self):
if self.pages == 0:
return True
return False
class Printer:
def __init__(self):
self.current_job = None
def get_job(self, print_queue):
try:
self.current_job = print_queue.dequeue()
except IndexError:
return f"No Jobs to Print."
def print_job(self, job):
while job.pages > 0:
job.print_page()
if job.check_complete():
return f"Printing Complete."
else:
return f"An error occurred."
my_queue = Queue()
my_job = Job()
my_printer = Printer()
my_queue.enqueue('job_1')
print(my_queue.items)
my_queue.enqueue('job_2')
my_queue.enqueue('job_3')
print(my_queue.items)
my_printer.get_job(my_queue)
print(my_printer.print_job(my_job))
|
9623c76235db38b3934f64559b2836a0160cb387
|
suresh-boddu/algo_ds
|
/ds/trees/amazon_test.py
| 1,502 | 3.890625 | 4 |
class Node:
left = None
right = None
data = None
def __init__(self, data, left, right):
self.data = data
self.left = left
self.right = right
class Tree:
root = None
def __init__(self, root):
self.root = root
def find_lca(node, key1, key2):
if not node:
return
if node.data == key1 or node.data == key2:
return node
lca_left = find_lca(node.left, key1, key2)
lca_right = find_lca(node.right, key1, key2)
if lca_left and lca_right:
return node
return lca_left if lca_left else lca_right
def main():
node5 = Node(5, None, None)
node4 = Node(4, None, node5)
node3 = Node(3, None, None)
node2 = Node(2, node3, None)
node1 = Node(1, node2, node4)
tree = Tree(node1)
lca = find_lca(tree.root, 3, 5)
print("LCA of 3, 5: %s"%(lca.data if lca else None))
lca = find_lca(tree.root, 2, 3)
print("LCA of 2, 3: %s"%(lca.data if lca else None))
lca = find_lca(tree.root, 5, 4)
print("LCA of 5, 4: %s"%(lca.data if lca else None))
lca = find_lca(tree.root, 2, 4)
print("LCA of 2, 4: %s"%(lca.data if lca else None))
lca = find_lca(tree.root, 5, 1)
print("LCA of 5, 1: %s"%(lca.data if lca else None))
lca = find_lca(tree.root, 6, 1)
print("LCA of 6, 1: %s"%(lca.data if lca else None))
lca = find_lca(tree.root, 6, 7)
print("LCA of 6, 7: %s" % (lca.data if lca else None))
if __name__ == '__main__':
main()
|
8d87fae41fc862a47059f0169c978c65d2370a01
|
catoteig/julekalender2020
|
/knowitjulekalender/door_03/door_03.py
| 2,397 | 3.890625 | 4 |
def make_horizontal(matrix_txt_txt):
horizontal_result = ''
file = open(matrix_txt_txt, 'r')
horizontal = file.readlines()
for row in horizontal:
horizontal_result += row[:-1]
return horizontal_result + ' ' + horizontal_result[::-1]
def make_vertical(matrix_txt):
vertical_result = ''
file = open(matrix_txt, 'r')
horizontal = file.readlines()
for i in range(len(horizontal)):
vertical_string = ''.join([word[i] for word in horizontal])
vertical_result += vertical_string
return vertical_result + ' ' + vertical_result[::-1]
def make_diagonal(matrix_txt):
diagonal = ''
file = open(matrix_txt, 'r')
horizontal = file.readlines()
# South -> east, X-direction
for i in range(len(horizontal)):
y = 0
for x in range(len(horizontal)-i):
diagonal += horizontal[x+i][y]
y += 1
diagonal += ' '
# South -> east, Y-direction
for i in range(len(horizontal)):
y = 0
for x in range(len(horizontal)-i):
diagonal += horizontal[y][x+i]
y += 1
diagonal += ' '
# South -> west, Y-direction
for i in range(len(horizontal)):
y = len(horizontal) - 1
for x in range(0, len(horizontal)-i):
diagonal += horizontal[x+i][y]
y -= 1
diagonal += ' '
# South -> west, X-direction
for i in range(len(horizontal)):
y = 0
for x in range(len(horizontal)-1, -1, -1):
diagonal += horizontal[y][x-i]
y += 1
diagonal += ' '
return diagonal + ' ' + diagonal[::-1]
def parse_wordlist(wordlist_txt):
wordlist = []
file = open(wordlist_txt, 'r')
list = file.readlines()
for row in list:
wordlist.append(row[:-1])
return wordlist
def find_words(matrix_txt, wordlist_txt):
wordlist = parse_wordlist(wordlist_txt)
horizontal = make_horizontal(matrix_txt)
vertical = make_vertical(matrix_txt)
diagonal = make_diagonal(matrix_txt)
no_match = []
for word in wordlist:
if word not in (horizontal + vertical + diagonal):
no_match.append(word)
return ','.join(sorted(no_match))
def test_1():
assert find_words('matrix_txt_test.txt', 'wordlist_test') == 'palmesøndag,påskeegg,smågodt'
print(find_words('matrix.txt', 'wordlist.txt'))
|
6242edcc86f032baf60c1dacd5186290475f9398
|
TodorovicIgor/Yamb
|
/util/aux_funcs.py
| 4,036 | 3.6875 | 4 |
import numpy as np
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def calc_val(dices, i, throws):
if 0 <= i <= 5:
sum = 0
for dice in dices:
sum = sum+dice.get_val() if dice.get_val() == i + 1 else sum
return sum
elif i == 6:
"""
for min value it is common sense to exclude maximum dice
"""
sum = 0
max = 0
for dice in dices:
if dice.get_val() > max:
max = dice.get_val()
sum += dice.get_val()
return sum-max
elif i == 7:
"""
excluding minimum dice
"""
sum = 0
min = 7
for dice in dices:
if dice.get_val() < min:
min = dice.get_val()
sum += dice.get_val()
return sum - min
elif i == 8:
if has_straight(dices):
if throws == 1:
# print("this should print alot1")
return 66
if throws == 2:
# print("this should print alot2")
return 56
if throws == 3:
# print("this should print alot3")
return 46
else:
return 0
elif i == 9:
return get_three(dices)
elif i == 10:
return get_full(dices)
elif i == 11:
return get_four(dices)
elif i == 12:
return get_yamb(dices)
else:
print("Unexpected error! Row index is", i, "expected values range from 0 to 12")
def has_straight(dices):
found = {
1: False,
2: False,
3: False,
4: False,
5: False,
6: False
}
for dice in dices:
found.update({dice.get_val(): True})
if not found[1] and found[2] and found[3] and found[4] and found[5] and found[6] or found[1] and found[2] and found[
3] and found[4] and found[5] and not found[6]:
return True
else:
return False
def get_three(dices):
found = {
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
6: 0
}
for dice in dices:
found.update({dice.get_val(): found[dice.get_val()]+1})
for i in reversed(range(6)):
if found[i + 1] >= 3:
return 3 * (i + 1)+20
return 0
def get_four(dices):
found = {
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
6: 0
}
for dice in dices:
found.update({dice.get_val(): found[dice.get_val()]+1})
for i in reversed(range(6)):
if found[i + 1] >= 4:
return 4 * (i + 1)+40
return 0
def get_yamb(dices):
found = {
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
6: 0
}
for dice in dices:
found.update({dice.get_val(): found[dice.get_val()]+1})
for i in reversed(range(6)):
if found[i + 1] >= 5:
return 5 * (i + 1)+50
return 0
def get_full(dices):
found = {
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
6: 0
}
for dice in dices:
found.update({dice.get_val(): found[dice.get_val()]+1})
for i in reversed(range(6)):
for j in reversed(range(i)):
if found[j + 1] >= 3 and found[i + 1] >= 2:
return 3 * (j + 1) + 2 * (i + 1)+30
elif found[j + 1] >= 2 and found[i + 1] >= 3:
return 2 * (j + 1) + 3 * (i + 1)+30
return 0
if __name__ == '__main__':
import game.Yamb as yamb
dices = [yamb.Dice() for _ in range(6)]
while True:
for dice in dices:
dice.roll()
# elif get_full(dices) != 0:
# print("Full")
# elif get_three(dices) != 0:
# print("Three of a kind")
if get_yamb(dices) != 0:
print("YAMB!!!!")
elif get_four(dices) != 0:
print("Four of a kind")
# elif has_straight(dices):
# print("Straight")
# for dice in dices:
# print(dice.get_val())
|
727f675002bf05b5b133d8d7540df8793f49b9ba
|
wattewiler/CIP_Project
|
/c1_web_scrapper.py
| 1,015 | 3.640625 | 4 |
#### webscrapping of data source C1; data dimansions: Country name, continent name
####
#### input: https://www.bernhard-gaul.de/wissen/staatenerde.php#uebneu
#### output: c1_country_src.csv
# ladet die Libraries
import requests
from bs4 import BeautifulSoup as bs
# download html file und unwanldung in soup objekt
raw_html = requests.get("https://www.bernhard-gaul.de/wissen/staatenerde.php#uebneu")
soup_html = bs(raw_html.text, "html.parser")
# loop durch das html code und speichert die gesuchten, linie für linie.
csv_file = open("c1_country_src.csv", "w", encoding='utf-8')
for p in soup_html.select("tr"):
y = p.select("td")
a = y[0].text
b = y[1].text
csv_file.write(a + "," + b + "\n")
print(a + ",")
csv_file.close()
#### Lessons learned:
# - wie bei web_scrapper_b1 ist das webpage html einfach geholten und ohne grosse struktur. die kleine
# auswahl von html tags und attributen machten es kaum möglich, einen html muster für die
# extraktion zu erkennen.
|
f18ce2e18d4d2b118f9864b5b004873aeaf2f9d8
|
ElizabethBeck/Class-Labs
|
/lab01.py
| 1,137 | 4.40625 | 4 |
integer_1 = int(input("Enter one integer: "))
integer_2 = int(input("Enter one integer: "))
integer_3 = int(input("Enter one more integer: "))
print("You put in:", integer_1, integer_2, integer_3)
added = integer_1 + integer_2 + integer_3
print("Sum =", added)
product = integer_1 * integer_2 * integer_3
print("Product =", product)
power = added**integer_1
print("Sum to the power of the first integer:", power)
sum_divided_int2 = added / integer_2
print("Sum divided by second integer: ", sum_divided_int2)
sum_divided_int3 = added // integer_3
print("Sum divided by integer 3:", sum_divided_int3)
remainder = added % integer_1
print("Remainder of sum divided by integer 1:", remainder)
highest = max(integer_1, integer_2, integer_3)
print("The largest integer is:", highest)
smallest = min(integer_1, integer_2, integer_3)
print("The smallest integer is:", smallest)
average = added/3
print("Average of the integers:", average)
average_2 = (added - smallest)/2
average_3 = (added - highest)/2
print("Average of the largest integers", average_2, "Average of the smallest integers:", average_3)
print("Ellie")
print("Computer Scinence")
|
ee4e4287fad943bbbfb0d758e8061a6fcfe41d45
|
codingyen/CodeAlone
|
/Python/0206_reverse_linked_list.py
| 583 | 3.96875 | 4 |
class ListNode:
def __init__(self, val = 0, next = None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head):
prev = None
while head:
curr = head
head = head.next
curr.next = prev
prev = curr
return prev
if __name__ == "__main__":
l1 = ListNode(1)
l2 = ListNode(2)
l3 = ListNode(3)
l4 = ListNode(4)
l5 = ListNode(5)
l1.next = l2
l2.next = l3
l3.next = l4
l4.next = l5
s = Solution()
print(s.reverseList(l1))
|
3932d629a09debcfd22695434fffc5038e5fa5a2
|
MerrickMath/MerrickMath.github.io-PythonProject
|
/Square.py
| 212 | 4.5 | 4 |
# This Is A Program That Finds Area Given Sidelength
print("This is a Program That Finds The Area Of A Square Given A Sidelength")
a = input("input a sidelength: ")
a = int(a)
area = a**2
print("Area: ", area)
|
0759274e584965c5b26d9a7dd1f070fb279df27d
|
qhuydtvt/C4E6-Lectures
|
/Session1/1.py
| 155 | 3.953125 | 4 |
print('Hello world')
n = input("what's your name?")
n = "ahfuehf"
print('Hello ', n)
y = int(input('your year of birth?'))
age = 2016 - y
print(age)
|
72f44d445be20c46469d1d29ad54c169b8812062
|
billkrauss3/pynet_test
|
/strex1.py
| 202 | 3.78125 | 4 |
#!/usr/bin/env python
str_1 = "John Doe"
str_2 = "John Conner"
str_3 = "John Lennon"
print "{:>30} {:>30} {:>30}".format(str_1, str_2, str_3)
str_4 = raw_input("Enter fourth name: ")
print "{:>30}".format(str_4)
|
3ad4128eed8c5122fc21bf18228d8e63cc7c93ba
|
kartik-soni1707/Python-Practicals
|
/Binary Search.py
| 392 | 3.734375 | 4 |
def binary_search(ar,key,low,high):
if low >high:
return -1
else :
mid =int((low+high)/2)
if ar[mid]==key:
return mid
elif key>ar[mid]:
low=mid+1
else:
high=mid-1
binary_search(ar,key,low,high)
ar=[1,2,3,4,5,6,7,8,9]
key=int(input('Enter no.:'))
print(binary_search(ar,key,0,len(ar)-1))
|
f9753ff525e8241f4a1db0770ba211a88609e3f1
|
pepperchini/curly-funicular
|
/Guessing_Game.py
| 722 | 4.34375 | 4 |
secret_number = 16
print(
"""
+================================+
| Welcome to my game, muggle! |
| Enter an integer number |
| and guess what number I've |
| picked for you. |
| So, what is the secret number? |
+================================+
""")
number = int(input("Enter a number: "))
while number != secret_number:
if number < secret_number:
print("You're stuck in my loop! To get out you must guess a bigger number.")
elif number > secret_number:
print("You're stuck in my loop! To get out you must guess a lower number.")
number = int(input("Try again!: "))
else:
print("Well done, muggle! You are free now!")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.