blob_id
stringlengths 40
40
| repo_name
stringlengths 5
127
| path
stringlengths 2
523
| length_bytes
int64 22
545k
| score
float64 3.5
5.34
| int_score
int64 4
5
| text
stringlengths 22
545k
|
---|---|---|---|---|---|---|
4c7f6e74dad352ec6d2627ee502384a7dd361c8f | kenshimota/Learning-Python | /Learning Basic/if_elif_else.py | 167 | 4.09375 | 4 | num1 = 8
num2 = 6
if num1 < num2:
print("num1 es menor que num2...\n")
elif num1 == num2:
print("Son identicos....\n")
else:
print("num1 es mayor que num2...\n")
|
1c321283b31a0d7822c27bc3042dce99f1891527 | Keerthana8897/Bridgelabz | /Algorithms/monthlypayment.py | 181 | 3.703125 | 4 | import math
def monthlypay(P,Y,R):
n=12*Y
r=R/(12*100)
k=P*r
h=1-(1+r)**(-n)
pay=float(k)/float(h)
print pay
P=input()
Y=input()
R=input()
monthlypay(P,Y,R)
|
30b829b57ba2d58fc07c15c00aa7edeba79b1a4f | Keerthana8897/Bridgelabz | /Algorithms/mergesort.py | 525 | 3.734375 | 4 | def merge_sort(a):
l = len(a)
if l == 1:
return a
a1 = merge_sort(a[:l//2])
a2 = merge_sort(a[l//2:])
a_sort = []
idx1, idx2 = 0, 0
while idx1 < len(a1) and idx2 < len(a2):
if a1[idx1] >= a2[idx2]:
a_sort.append(a2[idx2])
idx2 += 1
else:
a_sort.append(a1[idx1])
idx1 += 1
if idx1 < len(a1):
a_sort.extend(a1[idx1:])
else:
a_sort.extend(a2[idx2:])
return a_sort
a=[3,8,2,9,4]
print(merge_sort(a))
|
df9db9f0378177ce3dc0daadc266f5b3eb5730a5 | vivek-x-jha/TIL | /leet_code/algorithm_problems/twosum.py | 361 | 3.671875 | 4 | def twoSum(nums, target):
complements = {}
for i, num in enumerate(nums):
comp = target - num
if comp not in complements:
complements[num] = i
else:
assert target == nums[complements[comp]] + nums[i]
return [complements[comp], i]
nums = [2, 7, 11, 15]
target = 9
print(twoSum(nums, target))
|
85207e81ace52bfdcb2be5813bb5d42a5f7842f0 | mootils/mootils | /mootils/visualization/__init__.py | 974 | 3.65625 | 4 | from matplotlib import pyplot as plt
class Plot:
def __init__(self,
title: str = '',
subtitle: str = '',
font: str = 'serif',
fontsize: int = 16,
default_color: str = '#236FA4',
**kwargs):
"""
:param title: Title of the graph.
:param subtitle: Subtitle of the graph.
"""
self.title = title
self.subtitle = subtitle
self.font = font
self.fontsize = fontsize
self.default_color = default_color
self.n_dim = 0
# matplotlib classes
self._figure = None
def initialize(self):
""" Creates an empty figure.
"""
self._figure = plt.figure()
self._figure.suptitle(self.title, fontsize=self.fontsize)
# change the font of plots
plt.rc('font', family=self.font)
@property
def fig(self):
return self._figure
|
1a21136bd05b232ac4e636e3ddf71e5ec5f44738 | ClaudiaSofia222/homework2 | /02 - String/04 - Sherlock and Valid String.py | 779 | 3.859375 | 4 | #!/bin/python
import sys
def isValid(s):
ele = {}
for e in "abcdefghijklmnopqrstuvwxyz":
times = s.count(e)
if times > 0:
if times in ele:
ele[times].append(e)
else:
ele[times] = [e]
if len(ele) == 2:
keys = ele.keys()
if (abs(keys[0] - keys[1]) == 1) and ((len(ele[keys[0]]) is 1) or (len(ele[keys[1]]) is 1)):
return "YES"
elif (len(ele[keys[0]]) is 1 and (keys[0] == 1)) or (len(ele[keys[1]]) is 1 and (keys[1] == 1)):
return "YES"
else:
return "NO"
elif len(ele) > 2:
return "NO"
else:
return "YES"
s = raw_input().strip()
result = isValid(s)
print(result)
|
0fb3bf481431a680512dbcb404e1409059705123 | felipegarciab9601/Ejercicios.py | /Ejercicios.py/Condicional8.py | 369 | 3.9375 | 4 | user = str(input("Please introduce your name: "))
age_user = int(input("Please introduce your age: "))
if age_user <0:
print("Invalid age please try again")
elif age_user <4:
print("Your entrance is free")
elif age_user <=18:
print("Your entrance will be $5")
elif age_user >18:
print("Your entrance will be $10")
else:
print("Sorry command not valid")
|
7181067911603e216f432c9cacfbd7294170499a | felipegarciab9601/Ejercicios.py | /Ejercicios.py/Condicional2.py | 134 | 3.796875 | 4 | edad = int(input("Please introduce your age: "))
if edad < 18:
print("No eres mayor de edad")
else:
print("Eres mayor de edad") |
e7f99a79fe4d6eea70f633d16a0343dc7fe704f1 | felipegarciab9601/Ejercicios.py | /Ejercicios.py/Condicional7.py | 415 | 3.84375 | 4 |
inaceptable = 0.0
aceptable = 0.4
dinero = 2400
score = float(input("Please insert the score of the user: "))
if score == 0.0:
print("Insuficient, Your bonus would be : " + str(dinero*0.0))
elif score == 0.4:
print("Aceptable, Your bonus would be: " + str(dinero*0.4))
elif score >= 0.6:
print("Wonderful, Your bonus would be : " + str(dinero*score))
else:
print("Sorry request can't be processed") |
756259025fb02d1c167a17d85e9069ca9dd2cb8c | avkour13/Avinash_C0804437_Assignment3 | /Student.py | 1,044 | 3.734375 | 4 | import unittest
import logging
class Student(unittest.TestCase):
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
def total_marks(self, subject1, subject2, subject3):
try:
assert subject1 > 0
assert subject2 > 0
assert subject3 > 0
self.assertGreater(subject1, subject2, "Subject 2 has higher marks")
self.assertLess(subject2, subject3, "Subject 2 has less marks.")
total = subject1+subject2+subject3
self.logger.info("The total marks for the student calculated successfully.")
return total
except:
self.logger.warning("The marks entered must be greater than zero.")
def avg_marks(self, total_marks, num_students):
try:
average = total_marks/num_students
self.logger.info("The average marks for the student calculated successfully.")
return average
except:
self.logger.error("Number of students must be greater than zero.")
|
281ba6307be6d9dc6ae528eda2f25e7e95d2fd7e | PaulWang1905/tint | /stage1/expression.py | 116 | 3.953125 | 4 | length = 5
breadth = 2
area = length * breadth
print('Area is',area)
print('Perimeter is' , 2*(length + breadth))
|
ce80bd1bbe2f8034a45c68e4c3ddb9ca2248d5ed | PaulWang1905/tint | /stage2/assignment11.py | 233 | 3.53125 | 4 | import re
name = input('Enter File Name:')
handle = open(name)
total = 0
for line in handle:
x = line
y = re.findall('[0-9]+',x)
for number in y:
number = int(number)
total += number
print(total)
|
c35759cf6ddf382cd6ec14e90bd013707af13fd6 | learninfo/pythonAnswers | /Task 5 - boolean.py | 236 | 4.375 | 4 | import turtle
sides = int(input("number of sides"))
while (sides < 3) or (sides > 8) or (sides == 7):
sides = input("number of sides")
for count in range(1, sides+1):
turtle.forward(100)
turtle.right(360/sides)
|
81849f77995e755e9e592c926feb7cee8535cc32 | NicholasMaisel/Algorithms | /Stack.py | 1,093 | 4.0625 | 4 | from LinkedList import Node
from LinkedList import LinkedList
class Stack(LinkedList): #this inherits the Node class
def __init__(self):
self.top = None
#The isEmpty function is used to make sure, before the linkedlist is edited
#that the edit will cause no errors.
def isEmpty(self):
if self.top:
empty = False
else:
empty = True
return(empty)
def push(self,valueOfNode):
if self.isEmpty():
#Creates a new node to be pushed and attaches it to list with next node
n = Node(valueOfNode,self.top)
self.top = n #Makes the new node the top of list for LIFO
else:
n = Node(valueOfNode,None)
n.nextNode = self.top
self.top = n
def pop(self):
if not self.isEmpty(): # Ensures an empty list isnt popped
nodeToBePopped = self.top # Makes a copy of the node to return
self.top = self.top.nextNode # Remove node from list by moving up
return(nodeToBePopped)
|
b394361baed2d048d3c658525763171df3ae95e0 | NicholasMaisel/Algorithms | /knapsack.py | 1,959 | 3.78125 | 4 |
def read():
items = {}
capacities =[]
for line in open('spice.txt','r'):
line = line.rstrip().split(';')
line = [x.strip() for x in line]
if 'spice name' in line[0]:
items[line[0].split('=')[1].strip()] = [float(line[1].split('=')[1].strip()),
int(line[2].split('=')[1].strip())]
elif 'knapsack capacity' in line[0]:
capacities.append(int(line[0].split('=')[1].strip()))
# Orders the spices based on their price
sortedItems = sorted(items.items(), key=lambda val: val[1], reverse=True)
return(sortedItems,capacities)
def knapsack(itemGen, capacity):
sack = {}
sackValue = 0
while capacity > 0:
try:
item = next(itemGen) # Yield the next value from generator
itemName = item[0]
itemQty = item[1][1]
itemPrice = item[1][0]
except:
return(sack, sackValue)
if capacity >= itemQty:
sack[itemName] = itemQty #adds all of item[index] qty to sack
sackValue += itemQty * itemPrice #adds to sack value
capacity -= itemQty #updates cap
item[1][1] = 0
elif capacity < itemQty:
sack[itemName] = capacity
item[1][1] -= capacity
sackValue += capacity * itemPrice
capacity = 0
return(sack, sackValue)
def spice_gen(items):
''' The spice_gen is a generator function
used to yeild each spice one at a time'''
i = 0
while i < len(items):
yield(items[i])
i +=1
def main():
items, capacities = read()
for cap in capacities:
items=read()[0]
sg = spice_gen(items)
contents, value = knapsack(sg,cap)
print(f'The sack with capacity: {cap}, is worth {value} and contains:')
for k,v in contents.items():
print(f'{v} of {k}')
main()
|
b76a2b62821a3c9b3e1394fab64b78f8abe6e711 | sauravgupta2800/Bikeshare-Project-Python | /bikeshare_2.py | 10,192 | 4.3125 | 4 | import time
import pandas as pd
import numpy as np
CITY="'washington'"
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
MONTH_LIST = ['january', 'february', 'march', 'april', 'may', 'june','all']
DOW_LIST = ['sunday','monday','tuesday','wednesday','thursday','friday','saturday','all']
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print("="*80)
print('Hello! Let\'s explore some US bikeshare data!')
print("="*80)
# get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
while True:
try:
city = input(" Enter the name of the city:(out of chicago/new york city/washington): ").lower()
#Now it should accept both "ChicAgo" and "Chicago" input
if not city:
raise ValueError("empty string")
if city in CITY_DATA.keys(): # matching with out CITY_DATA list for validation
print("City name is matched :)")
break
else:
print("Your entered city name not in list!!!.....please write again\n")
except ValueError:
print("City name is invalid")
except KeyboardError:
print("Keyboard Error")
# get user input for month (all, january, february, ... , june)
while True:
try:
month = input("Enter the name of the month (only first 6 months in full words {ex. january/february/march/april/may/june/all}): ").lower()
if not month:
raise ValueError("empty string")
if month in MONTH_LIST: # matching with our MONTH_LIST for validation
print("Month name is matched :)")
break
else:
print("Your entered month name not in list!!!.....please write again\n")
except ValueError:
print("month name is invalid")
except KeyboardError:
print("Keyboard Error")
# get user input for day of week (all, monday, tuesday, ... sunday)
while True:
try:
day = input("Enter the name of Day of the week (in full words{ex. sunday/monday/tuesday/wednesday/thursday/friday/saturday/all}): ").lower()
if not day:
raise ValueError("empty string")
if day in DOW_LIST: # matching with out DOW_LIST list for validation
print("Day name is matched :)")
break
else:
print("Your entered day name is invalid!!!.....please write again\n")
except ValueError:
print("day is invalid")
except KeyboardError:
print("Keyboard Error")
print('-'*40)
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
#load data to df dataframe
df = pd.read_csv(CITY_DATA[city])
#convert the Start Time column to datatime
df["Start Time"] = pd.to_datetime(df["Start Time"])
#extract month and day of week,also create new columns
df["month"] = df["Start Time"].dt.month
df["day_of_week"] = df["Start Time"].dt.weekday_name
#filter by month if applicable
if month != "all":
#use the index of the months list to get it's int ValueError
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = months.index(month)+1
#filter by months to create the new DataFrame
df=df[df["month"]==month]
#filter by day of week if applicable
if day != "all":
#filter by day of week to create the new DataFrame
df = df[df["day_of_week"]==day.title()]
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print("="*80)
print('\nCalculating The Most Frequent Times of Travel...\n')
print("="*80)
start_time = time.time()
# display the most common month
common_month = df["month"].mode()[0] # or df["month"].value_count().idxmax()
print("\n")
print("Popular month is: ",common_month)
# display the most common day of week
common_day_of_week = df["day_of_week"].mode()[0]
print("\n")
print("Popular Day of Week is: ",common_day_of_week)
# display the most common start hour
df["Start Time"] = pd.to_datetime(df["Start Time"])
df["hour"] =df["Start Time"].dt.hour
common_hour = df["hour"].mode()[0]
print("\n")
print("Popular Start hour is: ",common_hour)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print("="*80)
print('\nCalculating The Most Popular Stations and Trip...\n')
print("="*80)
start_time = time.time()
# display most commonly used start station
common_start_station = df["Start Station"].value_counts().idxmax()
print("\n")
print("most commonly used start station:: ",common_start_station)
# display most commonly used end station
common_end_station = df["End Station"].value_counts().idxmax()
print("\n")
print("most commonly used End station:: ",common_end_station)
# display most frequent combination of start station and end station trip
print("most frequebt trip:: \n",df[["Start Station","End Station"]].mode())
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def time_conversion(sec):
""" Converts seconds into --> Days : Hour : Minutes : Seconds"""
day = sec//(24*3600)
sec = sec %(24*3600)
hour = sec //3600
sec%=3600
minute = sec //60
sec%=60
seconds = sec
return ("Days : Hour : Minutes : Seconds -> %d : %d : %d : %d"%(day,hour,minute,seconds))
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print("="*80)
print('\nCalculating Trip Duration...\n')
print("="*80)
start_time = time.time()
# display total travel time
total_travel_time = df["Trip Duration"].sum()
print("Total travel time is : ",time_conversion(total_travel_time)) # calling time_conversion() to convert the seconds into days:hour:min:sec
# display mean travel time
mean_travel_time = df["Trip Duration"].mean()
print("Mean travel time is : ",time_conversion(mean_travel_time)) # calling time_conversion() to convert the seconds into days:hour:min:sec
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df):
"""Displays statistics on bikeshare users."""
print("="*80)
print('\nCalculating User Stats...\n')
print("="*80)
start_time = time.time()
# Display counts of user types
print("COUNT OF USER TYPE:\n")
print(df["User Type"].value_counts())
if CITY!="washington":
# Display counts of gender
print("COUNT OF GENDER:\n")
""" here we could have NaN in various rows First we remove those rows"""
df.dropna(axis=0)
print(df["Gender"].value_counts())
# Display earliest, most recent, and most common year of birth
#calculation of earliest( i.e., minimum value)
asc_order = df["Birth Year"].sort_values(ascending=True)#first sort (asc)
print("earliest DOB is {}".format(int(asc_order.iloc[0])))# then choose first value
#calculation of most recent(i.e., maximum value)
desc_order = df["Birth Year"].sort_values(ascending=False)#first sort (desc)
print("recent DOB is {}".format(int(desc_order.iloc[0])))# then choose first value
#calculation of most common year of birth
print("Most common year of birth is {}".format(int(df["Birth Year"].mode()[0])))
else:
print("There is no data related to Gender and Birth Year in this file beacuse of absence of gender and birth column ")
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def correlation(x,y):
"""
"correlation assuming x and y are independent"
This function computes the correlation between the two input variable
either a NumPy array or a pandas
correlation = average of (x in standard units) times (y in standard units)
"""
x_std = (x-x.mean())/x.std(ddof=0)
y_std = (y-y.mean())/y.std(ddof=0)
return (x_std*y_std).mean()
def find_correlation(df):
"""Displays statistics of correlation"""
print("="*80)
print('\nCalculating Correlation...\n')
print("="*80)
Trip_Duration = df["Trip Duration"]
hour = df["hour"]
print("correlation b/w Trip_Duration and hour is: ",correlation(Trip_Duration,hour))
def main():
while True:
city, month, day = get_filters()
global CITY
CITY=city
#df=load_data("new york city", 'february', 'all')
#print(df)
df = load_data(city, month, day)
print("-"*60)
#showing some statixtical analysis
print("Various statistical analysis:")
print(df.head(4))
print(df.columns)
print(df.info())
print(df.describe())
print("-"*60)
#appliyng various functions
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
find_correlation(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
227dbfbd5ae0bea2281533033a010b996c27fef7 | martintvarog/python | /domecek.py | 361 | 3.5 | 4 | from turtle import forward, left, right, penup, pendown, exitonclick
from math import sqrt
for _ in range (4):
forward (100)
left (90)
left (45)
for _ in range (2):
forward (100 * sqrt(2))
left (135)
forward (100)
left (135)
right (135)
for _ in range (2):
left (45)
forward ((100 * sqrt(2)/2))
left (45)
exitonclick () |
d99396e79e06fe7ef172ff5f1613e43d32a27a75 | alexandnpu/pythonLearning | /test_corountine.py | 1,263 | 3.515625 | 4 |
import time
def coroutine(func):
def start(*args, **kwargs):
cr = func(*args, **kwargs)
next(cr)
return cr
return start
def follow(thefile, target):
thefile.seek(0, 2)
while True:
line = thefile.readline()
if not line:
time.sleep(0.1)
continue
target.send(line)
@coroutine
def printer():
while True:
line = yield
print(line)
@coroutine
def grep(patten):
print("Looking for {}".format(patten))
try:
while True:
line = (yield)
if patten in line:
print(line)
except GeneratorExit:
print("Going away. Goodbye")
def countdown(n):
print("Counting down from {}".format(n))
while n >= 0:
newvalue = (yield n) # yield n if no value is sent in,
if newvalue is not None: # if there is valude sent in, we use the new value
n = newvalue
else:
n -= 1
def test_countdown():
c = countdown(5)
for n in c:
print(n)
if n == 3:
c.send(9)
def test_follow_printer():
f = open("/tmp/log", "r")
follow(f, printer())
if __name__ == "__main__":
#test_countdown()
test_follow_printer()
|
7cfc168f42e036a36e9886891ff683d5f1d2d9c8 | rajdeep2804/OpenCV | /canny_edge_detection_in_opencv.py | 720 | 3.65625 | 4 | #the canny edge detection is an edge detection operator that uses a multi-stage algorithm to detect
#a wide range of edges in images. it was developed by john f canny in 1986
#the canny edge detection algorithm is composed of 5 steps:
# 1.) noise reduction
# 2.) gradient calculation
# 3.) non-maximum suppression
# 4.) double threshold
# 5.) edge tracking by Hysteresis
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread("lena.jpg", 0 )
canny = cv2.Canny(img, 100, 200, )
titles = ["image", "canny"]
image = [img, canny]
for i in range(2):
plt.subplot(1, 2, i+1), plt.imshow(image[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show() |
a7bef5820765e1ab474de3769ed461300ba9385a | ameliacgraham/udemy_courses | /python_for_data_structures/linked_list_cycle_check.py | 971 | 3.96875 | 4 | class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
def is_cycle(self):
"""Checks if a singly linked list contains a cycle given a head node.
>>> a = Node("a")
>>> b = Node("b")
>>> c = Node("c")
>>> a.next = b
>>> b.next = c
>>> a.is_cycle()
False
>>> d = Node("d")
>>> e = Node("e")
>>> f = Node("f")
>>> d.next = e
>>> e.next = f
>>> f.next = d
>>> d.is_cycle()
True
"""
seen = set()
current = self
while current is not None:
if current in seen:
return True
else:
seen.add(current)
current = current.next
return False
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TESTS PASSED. RIGHT ON!\n" |
8323d427d833cc9faaedecc8598c782e090b4dba | DanLivassan/clean_code_book | /chapter3/employee_clean_code.py | 1,457 | 3.640625 | 4 | from abc import ABC, abstractmethod
MANAGER_EMPLOYEE = 1
SELLER_EMPLOYEE = 2
"""
Switch statements should be avoid or buried in one class
(Ps.: Python have no switch statement but its like a if sequence)
"""
class Employee(ABC):
def __init__(self, name: str, employee_type: int, hour: float):
self.name = name
self.employee_type = employee_type
self.hour = hour
@abstractmethod
def calculate_pay(self):
pass
class AdmManager(Employee):
def calculate_pay(self):
return self.hour * 8.25 * 1.3
class Seller(Employee):
def calculate_pay(self):
return self.hour * 8.25
class EmployeeFactory:
@staticmethod
def makeEmployee(employee) -> Employee:
raise NotImplemented
class EmployeeFactoryImpl(EmployeeFactory):
@staticmethod
def makeEmployee(**employee) -> Employee:
if employee["employee_type"] == SELLER_EMPLOYEE:
return Seller(**employee)
elif employee["employee_type"] == MANAGER_EMPLOYEE:
return AdmManager(**employee)
seller_empl = EmployeeFactoryImpl.makeEmployee(name="Danilo", employee_type=SELLER_EMPLOYEE, hour=40)
manager_empl = EmployeeFactoryImpl.makeEmployee(name="Deise", employee_type=MANAGER_EMPLOYEE, hour=50)
print("-" * 20)
print(f"\nSalário de {seller_empl.name}: {seller_empl.calculate_pay()}")
print(f"\nSalário de {manager_empl.name}: {manager_empl.calculate_pay()}\n")
print("-" * 20)
|
a8a5edf3c6cf3f5a6470016eb6c5802e18df4338 | bharath-acchu/python | /calci.py | 899 | 4.1875 | 4 | def add(a,b): #function to add
return (a+b)
def sub(a,b):
return (a-b)
def mul(a,b):
return (a*b)
def divide(a,b):
if(b==0):
print("divide by zero is not allowed")
return 0
else:
return (a/b)
print('\n\t\t\t SIMPLE CALCULATOR\n')
while 1:
print('which operation you want to ?\n')
print('1.addition\n2.subtraction\n3.multiplication\n4.division\n')
ch=int(input('ENTER YOUR CHOICE\n'))
a=float(input("Enter first number\n"))
b=float(input("Enter second number\n"))
if ch is 1: #is also used as equality operator
print("ans=",add(a,b))
elif(ch==2):
print("ans=",sub(a,b))
elif(ch==3):
print("ans=",mul(a,b))
elif(ch==4):
print("ans=",divide(a,b))
else:print("improper choice\n")
|
b12f5b4ab877f09ba7ffbe98ed5ce569c8c475f8 | qzwj/learnPython | /learn/基础部分/序列化.py | 2,477 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# 我们把变量从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,在其他语言中也被称之为serialization,marshalling,flattening等等,都是一个意思。
# 序列化之后,就可以把序列化后的内容写入磁盘,或者通过网络传输到别的机器上。
# 反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化,即unpickling。
# d = dict(name = 'Bob', age = 20, score = 88)
d = dict(name='Bob', age=20, score=88)
print(d['name'])
print(d.get('name'))
import pickle
# pickle.dumps(d) #序列化为二进制
f = open('../dump.txt', 'wb')
pickle.dump(d, f) #写进一个文件
f.close()
f = open('../dump.txt', 'rb')
print(pickle.load(f)) #读取序列化的文件
f.close()
#JSON 编码是utf-8
#如果我们要在不同的编程语言之间传递对象,就必须把对象序列化为标准格式,比如XML,但更好的方法是序列化为JSON,因为JSON表示出来就是一个字符串,可以被所有语言读取,也可以方便地存储到磁盘或者通过网络传输。JSON不仅是标准格式,并且比XML更快,而且可以直接在Web页面中读取,非常方便。
#JSON表示的对象就是标准的JavaScript语言的对象,JSON和Python内置的数据类型对应如下
import json
print(json.dumps(d)) #序列化为一个为str, 内容就是标准的json
json_str = '{"name": "Bob", "age": 20, "score": 88}'
print(json.loads(json_str)) #把json字符串反序列化为对象
#JSON进阶
#class类对象的json
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
def student2dict(std): #类方法 序列化
return {
'name' : std.name,
'age' : std.age,
'score' : std.score
}
def dict2student(d): #反序列化
return Student(d['name'], d['age'], d['score'])
s = Student('lwj', 24, 60)
f1=open('../json_test.txt', 'w')
json.dump(s, f1, default=Student.student2dict)
f1.close()
str1 = json.dumps(s, default=Student.student2dict)
#偷懒方法, 每个类都默认有__dict__这个
str2 = json.dumps(s, default=lambda obj: obj.__dict__)
print(str1)
print('str2 =',str2)
s1 = json.loads(str1, object_hook=Student.dict2student)
print(s1)
# 接口典范, 需要怎么样的格式, 就可以传入配置
obj = dict(name='小明', age=20)
s1 = json.dumps(obj, ensure_ascii=True)
print(s1)
|
da13a5588d74bedac440978ed66363fcc1d7fc24 | qzwj/learnPython | /learn/基础部分/类和对象.py | 4,325 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
print('--------------类和对象-------------')
class Student(object): #object 继承object
pass
bart = Student()
bart.name = 'lwj' #感觉有点类似js的对象
bart.age = 25
print('name =', bart.name, ',age =', bart.age)
#ming = Student()
#print('name =', ming.name) #上面对象的变量不影响下面的, 下面的对象仍然没有这个name变量
class Person(object):
def __init__(self, name, age):
self.name = name #self 是初始化好的空对象, 外面调用时可以省略, 可以直接给一个对象初始化有2个变量
self.age = age
def print_info(self):
print('name =',self.name, ',age =', self.age)
def get_grade(self):
if self.age < 18:
print('未成年')
elif self.age < 30:
print('青年')
elif self.age < 50:
print('壮年')
else:
print('老年')
hong = Person('xiaohong', 18)
hong.print_info()
hong.get_grade()
print('--------------访问限制-------------')
class Car(object):
def __init__(self, name, age):
self.__name = name #__name 隐藏外部使用的权限, 本质上是改为了 _Car__name, 但是不建议这么访问
self.__age = age #__XX__ 这个是关键字变量, 外部可以访问
def get_name(self): # _XX 也是私有变量, 不建议随意访问
return self.__name
def set_name(self, name):
self.__name = name
def get_age(self):
return self.__age
def set_age(self, age):
self.__age = age
car = Car('BMW', 1)
print('car.name =', car.get_name())
print('car.age =', car.get_age())
print('--------------继承, 多态-------------')
class Animal(object):
def run(self):
print('Animal is running ...')
class Dog(Animal):
def run(self):
print('Dog is running ...')
class Cat(Animal):
def run(self):
print('Cat is running ...')
class Timer(object):
def run(self):
print('Timer is running ...')
def run_twice(s):
s.run()
s.run()
run_twice(Animal()) #像鸭子模型
run_twice(Dog())
run_twice(Cat())
run_twice(Timer()) #类鸭子模型, 走起路来像鸭子, 没有继承指定的父类, 只是有了这个方法, 就可以执行
print(isinstance(Dog(), Animal))
print(isinstance(Timer(), Animal))
print('--------------获取对象信息-------------')
import types
# type()
print('type(123) =', type(123))
print('type(dog) =', type(Dog())) #判断 原生的类型, 不能判断父类
print('type(str) =', type('str'))
print('type(abc) =', type(abs)) #函数
print('type(run_twice) =', type(run_twice))
print(type(123) == int)
print(type('123') == type(123))
print(type(run_twice) == types.FunctionType)
print(type(abs) == types.BuiltinFunctionType)
print(type(lambda x: x*x) == types.LambdaType)
print(type(x for x in range(10)) == types.GeneratorType )
#isinstance() 比较常用, 还可以判断子类
print(isinstance('123', str))
print(isinstance([1,2,3], (list,tuple)))
print(isinstance((1,2,3), (list,tuple)))
#dir() 获取一个对象所有的属性和方法, 不记得的方法的时候可以看一下
print(dir([]))
#getattr() setattr() hasattr()
class MyObject(object):
def __init__(self):
self.x = 9
def power(self):
return self.x * self.x
obj = MyObject()
if hasattr(obj, 'x'):
print('obj 有属性 x')
if hasattr(obj, 'y'):
print('obj 有属性 y')
else:
setattr(obj, 'y', 20)
print(getattr(obj, 'y'))
print(obj.y)
# 试图获取不存在的 属性会报错, 所以这个用在我们不知道对象有什么属性的时候, 知道了就直接用
def readImage(fp):
if hasattr(fp, 'read'):
return readData(fp)
return None
#假设我们希望从文件流fp中读取图像,我们首先要判断该fp对象是否存在read方法,如果存在,则该对象是一个流,如果不存在,则无法读取。hasattr()就派上了用场。
#请注意,在Python这类动态语言中,根据鸭子类型,有read()方法,不代表该fp对象就是一个文件流,它也可能是网络流,也可能是内存中的一个字节流,但只要read()方法返回的是有效的图像数据,就不影响读取图像的功能。
print('--------------实例属性和类属性-------------')
class Image(object):
path = '/User/wjl/Desktop/1.png' #类属性
image = Image()
print(image.path)
image.path = '123' #新增加一个同名实例属性, 优先级高
print(image.path)
del image.path
print(image.path) |
c8166981f11f593d2dcee65efc6839a7796159a9 | Terminator163/tfkdr0dodu | /venv/nemazice.py | 256 | 3.765625 | 4 |
гшшыагщрку
date = input().split()
x = before_the_concert(date[0], date
8ehsioerhgihgiohoiesghoieshigheosgergihgoihore
date = input().split()
x = before_the_concert(date[0], date
date = input().split()
x = before_the_concert(date[0], date
|
9020848d921ee28d2d3ce6455b0c69aeb1089fdc | alehatsman/pylearn | /py/lists/find_nth_from_the_end_test.py | 392 | 3.5 | 4 | import unittest
from lists.test_utils import simple_list
from lists.find_nth_from_the_end import find_nth_from_the_end
class TestFindNthFromTheEnd(unittest.TestCase):
def test_find_nth_from_the_end(self):
ll = simple_list(10)
for i in range(0, 10):
self.assertEqual(9 - i, find_nth_from_the_end(ll.head, i))
if __name__ == '__main__':
unittest.main()
|
18aaa52439a63cf8158f67fe1578cd229e91f352 | alehatsman/pylearn | /py/lists/test_utils.py | 837 | 4.09375 | 4 | """
LinkedList test utils. Functions for generating lists.
"""
import random
from lists.linked_list import LinkedList
def simple_list(n):
"""
Generates simple linked lists with numbers from 0 to n.
Time complexity: O(n)
Space complexity: O(n)
"""
ll = LinkedList()
for i in range(n - 1, -1, -1):
ll.prepend(i)
return ll
def cycle_list(n):
"""
Generates cycle list with numbers from 0 to n.
Last node points to head.
"""
ll = simple_list(n)
last = ll.last()
last.next = ll.head
return ll
def random_cycle_list(n):
"""
Generates cycle list with numbers from 0 to n.
Last node points to random node.
"""
ll = simple_list(n)
last = ll.last()
random_node = ll.get(random.randint(0, n-1))
last.next = random_node
return ll
|
cdfec446b032f3161d3049c9c67da71dbd9680b1 | alehatsman/pylearn | /py/lists/linked_list.py | 2,403 | 3.84375 | 4 | """
LinkedList ADT implementation.
"""
class Node:
"""
Node represents Node ADT in LinkedList.
Usage:
Node(value)
"""
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert(self, value, position):
new_node = Node(value)
if position == 0:
new_node.next = self.head
self.head = new_node
return
pos = 0
prev = None
current = self.head
while current and pos < position:
pos += 1
prev = current
current = current.next
prev.next = new_node
new_node.next = current
def prepend(self, value):
self.insert(value, 0)
def append(self, value):
new_node = Node(value)
if not self.head:
self.head = new_node
return
last_node = self.last()
last_node.next = new_node
def delete(self, position):
if position == 0:
self.head = self.head.next
return
node = self.get(position - 1)
node.next = node.next.next
def get(self, position):
pos = 0
current = self.head
while current and pos < position:
pos += 1
current = current.next
return current
def last(self):
current = self.head
if not current:
return None
while current.next:
current = current.next
return current
def iterator(self):
current_node = self.head
while current_node:
yield current_node
current_node = current_node.next
def length(self):
count = 0
current = self.head
while current:
count += 1
current = current.next
return count
def to_list(self):
res = []
current = self.head
while current:
res.append(current.value)
current = current.next
return res
def from_array_list(array_list):
ll = LinkedList()
if len(array_list) == 0:
return ll
ll.head = Node(array_list[0])
current_node = ll.head
for i in range(1, len(array_list)):
current_node.next = Node(array_list[i])
current_node = current_node.next
return ll
|
314a0e022ad79a3c9271b34e9a4dca94daeff484 | LostHeir/Coffee-Machine-oop | /main.py | 867 | 3.546875 | 4 | from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine
coffee_menu = Menu()
espresso = MenuItem("espresso", 75, 0, 7, 1.2)
cappuccino = MenuItem("cappuccino", 125, 30, 10, 1.9)
latte = MenuItem("latte", 200, 100, 15, 2)
coffee_maker = CoffeeMaker()
money_machine = MoneyMachine()
exit_machine = False
while not exit_machine:
user_input = input(f"What would you like? ({coffee_menu.get_items()}): ")
if user_input == "end":
exit_machine = True
print("Shutting down...")
elif user_input == "report":
coffee_maker.report()
money_machine.report()
else:
user_drink = coffee_menu.find_drink(user_input)
if coffee_maker.is_resource_sufficient(user_drink) and money_machine.make_payment(user_drink.cost):
coffee_maker.make_coffee(user_drink)
|
a1629771647bbf9b0ae5087e3bdf73734b905c85 | ovasylev/dev-sprint2 | /chap6.py | 330 | 3.921875 | 4 | # Enter your answrs for chapter 6 here
# Name: Olha Vasylevska
# Ex. 6.6
def is_palindrome(word):
length = len(word)
for i in range (length/2):
if word[i]!=word[length-1-i]:
return False
return True
print is_palindrome("noon")
# Ex 6.8
def gcd(a, b):
if b==0:
return a
else:
r = a % b
return gcd(b, r)
print gcd(8, 12) |
b0c9d4b7b8644a9a25a671919869253fc9d86ad8 | piperpi/python_book_code | /Python编程锦囊/Code(实例源码及使用说明)/08/09/dataframe_drop_duplicates.py | 652 | 3.703125 | 4 | import pandas as pd
aa =r'../data/1月销售数据.xls'
df = pd.DataFrame(pd.read_excel(aa))
#判断每一行数据是否重复(全部相同),False表示不重复,返回值为True表示重复
print(df.duplicated())
#去除全部的重复数据
print(df.drop_duplicates())
#去除指定列的重复数据
print(df.drop_duplicates(['买家会员名']))
#保留重复行中的最后一行
print(df.drop_duplicates(['买家会员名'],keep='last'))
#inplace=True表示直接在原来的DataFrame上删除重复项,而默认值False表示生成一个副本。
print(df.drop_duplicates(['买家会员名','买家支付宝账号'],inplace=False))
|
158a744489b862223cdc88890e5da7c535de81ff | piperpi/python_book_code | /Python编程锦囊/Code(实例源码及使用说明)/01/12/1.字符串去重的5种方法:/demo02.py | 415 | 3.703125 | 4 | # *_* coding : UTF-8 *_*
# 开发团队 :明日科技
# 开发人员 :Administrator
# 开发时间 :2019/7/1 16:23
# 文件名称 :demo02.py
# 开发工具 :PyCharm
name='王李张李陈王杨张吴周王刘赵黄吴杨'
newname=''
i = len(name)-1
while True:
if i >=0:
if name[i] not in newname:
newname+=(name[i])
i-=1
else:
break
print (newname)
|
d2646ffd9542f0231615afebcf29893cf503cfcf | piperpi/python_book_code | /Python编程锦囊/Code(实例源码及使用说明)/03/01/createfile.py | 907 | 3.703125 | 4 | # !/usr/bin/env python3
# -*- coding: utf-8 -*-
# 开发团队 :明日科技
# 开发人员 :小科
# 开发时间 :2019/4/9 9:31
# 文件名称 :createfile.PY
# 开发工具 :PyCharm
'''
以当前日期时间创建文件
'''
import os
import datetime
import time
while True:
path=input('请输入文件保存地址:') # 记录文件保存地址
num=int(input('请输入创建文件的数量:')) # 记录文件创建数量
# 循环创建文件
for i in range(num):
t=datetime.datetime.now() # 获取当前时间
# 对当前日期时间进行格式化,作为文件名
file=os.path.join(path,t.strftime('%Y%m%d%H%M%S')+'.txt')
open(file,'w',encoding='utf-8') # 以UTF8编码创建文件
time.sleep(1) # 休眠1秒钟
i+=1 # 循环标识加1
print('创建成功!')
os.startfile(path) # 打开路径查看
|
00b09af8de5cafd536f08b46fdbb8e917b0a6af6 | piperpi/python_book_code | /Python编程锦囊/Code(实例源码及使用说明)/02/02/方法1:利用zfill()函数实现数字编号/demo02.py | 1,158 | 3.578125 | 4 | # *_* coding : UTF-8 *_*
# 开发团队 :明日科技
# 开发人员 :Administrator
# 开发时间 :2019/7/2 13:49
# 文件名称 :demo02.py
# 开发工具 :PyCharm
import random # 导入随机模块
char=['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'] # 随机数据
shop='100000056303' # 固定编号
prize=[] # 保存抽奖号码的列表
inside='' # 中段编码
amount = input('请输入购物金额:') # 获取输入金额
many=int(int(amount)/100)
if int(amount)>=100:
# 随机生成中段7为编码
for i in range(0,7):
if inside=='':
inside = random.choice(char)
else:
inside =inside+ random.choice(char)
# 生成尾部4为数字,并将组合的抽奖号添加至列表
for i in range(0,many):
number = str(i+1).zfill(4)
prize.append([shop,inside, number])
else:
print('购物金额低于100元,不能参加抽奖!!!')
print("\033[1;34m=" *24)
print("本次购物抽奖号码")
print('=' *24 +'\033[0m' )
# 打印最终的抽奖号码
for item in prize:
print(''.join(item))
|
be5d95d9cbbd2c44a43149038aa15b55e2a22799 | piperpi/python_book_code | /Python高级编程(第二版)/chapter13/threads_one_per_item.py | 1,002 | 3.734375 | 4 | """
"An example of a threaded application" section example
showing how to use `threading` module in simplest
one-thread-per-item fashion.
"""
import time
from threading import Thread
from gmaps import Geocoding
api = Geocoding()
PLACES = (
'Reykjavik', 'Vien', 'Zadar', 'Venice',
'Wrocław', 'Bolognia', 'Berlin', 'Słubice',
'New York', 'Dehli',
)
def fetch_place(place):
geocoded = api.geocode(place)[0]
print("{:>25s}, {:6.2f}, {:6.2f}".format(
geocoded['formatted_address'],
geocoded['geometry']['location']['lat'],
geocoded['geometry']['location']['lng'],
))
def main():
threads = []
for place in PLACES:
thread = Thread(target=fetch_place, args=[place])
thread.start()
threads.append(thread)
while threads:
threads.pop().join()
if __name__ == "__main__":
started = time.time()
main()
elapsed = time.time() - started
print()
print("time elapsed: {:.2f}s".format(elapsed))
|
abdd6c39ce1f703848351413b7564d55bfa5d9c1 | hnagib/Parametric-Curves | /parametric_curve_functions.py | 7,389 | 3.515625 | 4 | import matplotlib.pyplot as plt
import numpy as np
from scipy.misc import *
import seaborn as sns
# Functions for constructing and plotting Bezier Curves
# ------------------------------------------------------------------------
def bezier_poly_interact(ctrl_points, pt, t=0.5, P1x=-1, P1y=2, P2x=3, P2y=2):
'''
Inputs
ctrl_points:
0 (or any int): Use default set of control points
P_i: Use set of control points specified in P_i
t: value between 0 and 1 for indexing a point on the blending functions
pt: number of control points to use
P1x: x-value of control point P1
P1y: y-value of control point P1
Outputs
Interactive plot of the Bezier curve and its blending functions
'''
if type(ctrl_points) == int:
P_i = np.array([[-2,-1,3,4,1,0,3], [0,2,2,0,1,0.5,-0.5]])
# Control points
P_i[0][1] = P1x
P_i[1][1] = P1y
P_i[0][2] = P2x
P_i[1][2] = P2y
else:
P_i = ctrl_points
# Parameter space
h = 0.01
u = np.arange(0,1,h)
t = int(t/h)
# Select N control points from P_i
P_i = P_i[:,0:pt]
# Initialize emp
P_u = np.zeros((2,u.size))
Bi = []
n = P_i.shape[1]-1;
for i in range(n+1):
Bi.append(comb(n,i)*(u**i)*((1-u)**(n-i)))
P_u += Bi[i]*P_i[:,i].reshape(2,1)
plt.subplot(1,2,1)
ax = plt.gca()
plt.plot(P_i[0,:],P_i[1,:],'k--')
for i in range(n+1):
plt.plot(P_i[0,i],P_i[1,i],'o')
plt.plot(P_u[0,:],P_u[1,:],'k'), plt.plot(P_u[0,t],P_u[1,t],'ko')
ax.set_xlim(-3, 5)
ax.set_ylim(-1, 3)
plt.title('Bezier Curves')
plt.subplot(1,2,2)
for i in range(n+1):
plt.plot(u,Bi[i]), plt.plot(u[t],Bi[i][t],'ko')
plt.axvline(u[t],color='k', linestyle='dotted')
plt.title('Blending functions')
# Functions for constructing and plotting B-Spline Curves
# ------------------------------------------------------------------------
def non_periodic_knot(n,k):
'''
Inputs
k: order of curve
n: n+1 control points
Outputs
u_i: vector of length n+k+1 containing the knot values
'''
u_i = np.zeros(n+k+1)
for i in range(n+k+1):
if 0<=i<k:
u_i[i] = 0
elif k<=i<=n:
u_i[i] = i-k+1
elif n<i<=(n+k):
u_i[i] = n-k+2
return u_i
def blending_func(u,u_i,k):
'''
Inputs
u: parameter values of which the blending function is defined
u_i: vector of length n+k+1 containing the knot values
k: order of curve
Outputs
N: List containing knot values and blending functions
N[0]: N_{i,0} contains the knot values
N[1]: N_{i,1}
N[k]: N_{i,k} for k >= 2, contains the blending functions of degree k-1
'''
N =[]
for k in range(k+1):
N.append([])
if k == 0:
for i in range(len(u_i)-k):
N[k].append(u_i[i])
elif k == 1:
for i in range(len(u_i)-k):
N[k].append(((u >= u_i[i]) & (u < u_i[i+1]) ).astype(int))
else:
for i in range(len(u_i)-k):
if (u_i[i+k-1]-u_i[i]) == 0:
N_ik_1 = np.zeros(u.size)
else:
N_ik_1 = ((u-u_i[i])*N[k-1][i])/(u_i[i+k-1]-u_i[i])
if (u_i[i+k]-u_i[i+1]) == 0:
N_ik_2 = np.zeros(u.size)
else:
N_ik_2 = ((u_i[i+k]-u)*N[k-1][i+1])/(u_i[i+k]-u_i[i+1])
N_ik = N_ik_1 + N_ik_2
N[k].append(N_ik)
return N
def B_spline(N,u,u_i,P_i,k):
'''
Inputs
N: List containing knot values and blending functions
N[0]: N_{i,0} contains the knot values
N[1]: N_{i,1}
N[k]: N_{i,k} for k >= 2, contains the blending functions of degree k-1
u: parameter values of which the blending function is defined
u_i: vector of length n+k+1 containing the knot values
P_i: array of control points
k: order of curve
Outputs
P_u: B-Spline curve values
P_u[0,:]: x-components of the B-Spline curve
P_u[1,:]: y-components of the B-Spline curve
'''
P_u = np.zeros((2,u.size))
for i in range(len(u_i)-k):
P_u += N[k][i]*P_i[:,i].reshape(2,1)
return P_u
def plot_bspline_blendfunc(t, N, P_i, P_u, u, u_i,k):
'''
Inputs
t: value between u_i[0] and u_i[-1] for indexing a point on the blending functions
N: List containing knot values and blending functions
N[0]: N_{i,0} contains the knot values
N[1]: N_{i,1}
N[k]: N_{i,k} for k >= 2, contains the blending functions of degree k-1
u: parameter values of which the blending function is defined
u_i: vector of length n+k+1 containing the knot values
P_i: array of control points
k: order of curve
P_u: B-Spline curve values
P_u[0,:]: x-components of the B-Spline curve
P_u[1,:]: y-components of the B-Spline curve
Outputs
Plots the B-Spline curve and its blending functions of different degrees
'''
plt.subplot(3,2,1)
ax = plt.gca()
plt.plot(P_u[0],P_u[1],'k')
plt.plot(P_u[0][t],P_u[1][t],'ko')
plt.plot(P_i[0,:],P_i[1,:],'k--')
for i in range(P_i.shape[1]):
plt.plot(P_i[0,i],P_i[1,i],'o')
ax.set_xlim(-3, 5)
ax.set_ylim(-1, 3)
plt.title('B-Spline Curve')
for k in np.arange(2,k+1):
plt.subplot(3,2,k)
plt.axvline(u[t],color='k', linestyle='dotted')
for i in range(len(u_i)-k):
plt.plot(u,N[k][i])
plt.plot(u[t],N[k][i][t],'ko')
plt.title('Blending functions of degree %d' %(k-1))
def B_spline_interact(ctrl_points, pt=8, k=4, t=0.5, P1x=-1,P1y=2):
'''
Inputs
ctrl_points:
0 (or any int): Use default set of control points
P_i: Use set of control points specified in P_i
t: value between 0 and 1 for indexing a point on the blending functions
pt: number of control points to use
k: order of curve
P1x: x-value of control point P1
P1y: y-value of control point P1
Outputs
Interactive plots of the B-Spline curve and its blending functions of different degrees
'''
if type(ctrl_points) == int:
P_i = np.array([[-2,-1,3,4,1,0,2,0], [0,2,2,0,1,0.5,-0.5,-0.5]])
# Control points
P_i[0][1] = P1x
P_i[1][1] = P1y
else:
P_i = ctrl_points
t = float(t);
if k == '':
k = 2
else:
k = int(k)
P_i = P_i[:,0:pt]
n = P_i.shape[1]-1; k = k; h = 0.01
if k > (n+1):
print("Can't draw degreee = %d curve through %d control points"%(k,n+1))
elif k == 0:
print("k must be greater than 0")
else:
u_i = non_periodic_knot(n,k)
u = np.arange(u_i[k-1],u_i[n+1],h)
t = int((t/h)*u_i[-1])
N = blending_func(u,u_i,k)
P_u = B_spline(N,u,u_i,P_i,k)
plot_bspline_blendfunc(t,N, P_i, P_u, u, u_i,k); |
4510765c18aea20419106e1ec9c1cd22e84a8d84 | mayurigujja/PythonTest1 | /StringDemo.py | 143 | 3.578125 | 4 | Str = "Mayuri Gujja"
print(Str[0])
print(Str[2:5])
mun = Str.split(" ")
print(mun[0])
Str1 = " Mayuri "
print(Str1 in Str)
print(Str1. strip())
|
97f5dae4bd5a790d2628007409f09f7d4d02ecbe | bladedpenguin/meow | /main.py | 1,269 | 3.5 | 4 | """a little game about various things"""
import pygame as pg
# import menu
from main_menu import MainMenu
# from lore import Lore
from event import SCREEN_TRANSITION
class Game:
"""run the whole game"""
def __init__(self):
self.display = pg.display.set_mode([640, 480])
self.next_screen = None
self.running = True
# menu = menu.Menu()
self.screen = MainMenu()
# screen = Lore()
self.screen.bake()
self.clock = pg.time.Clock()
def main(self):
"""Run the main tickloop"""
while self.running:
#handle events
events = pg.event.get()
for event in events:
if event.type == pg.QUIT:
self.running = False
if event.type == SCREEN_TRANSITION:
if event.new_screen is not None:
self.next_screen = event.new_screen
self.screen = self.next_screen
self.screen.handle_events(events)
self.display.fill((0, 0, 0))
self.screen.draw(self.display)
self.clock.tick(60)
pg.display.update()
print("goodbye!")
pg.quit()
##actually do the thing
game = Game()
game.main()
|
609322d1fb5216022d5cdaeba6c812ed9d6a4bf9 | haxsgvnbdus/UPGMA-clustering | /matrixTest.py | 312 | 3.90625 | 4 | '''
Created on Mar 15, 2017
@author: Hannie
'''
def matrixToList(table):
matrix = []
for i in range(0, len(A[0])):
row = []
for j in range(0, len(A[0])):
if i>j:
row.append(A[i][j])
matrix.append(row)
# print(pos)
print(matrix)
|
7cf42fdcdb3e23f2988006ce8cd2ac4773cf1dca | neiljdo/problem-solving-practice | /UVa/solved/12709.py | 645 | 3.640625 | 4 | import sys
import math
import bisect
def main():
while True:
n = int(sys.stdin.readline().strip())
if n == 0: break
# max h gives the largest downward acceleration
max_h = -math.inf
max_volume = -math.inf
for ant in range(n):
l, w, h = list(map(int, sys.stdin.readline().strip().split()))
if h > max_h:
max_h, max_volume = h, l * w * h
elif h == max_h:
volume = l * w * h
if volume > max_volume:
max_volume = volume
print(max_volume)
if __name__ == "__main__":
main()
|
873cb8a71f6bceb866c4cd88a442fd15edf52edc | neiljdo/problem-solving-practice | /EPIP/10_1.py | 1,307 | 4 | 4 | import sys
import math
import heapq
from functools import partial
from collections import namedtuple
"""
Test if a binary tree is height-balanced
i.e. abs(height(left subtree) - heigh (right subtree)) = 1 for each node of the tree
"""
# For trees, function call stack is part of the space complexity
class BinaryTreeNode:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def is_height_balanced(root):
# O(n) time since we have to compute this for all n nodes of the tree
# O(h) space since we have h calls in the call stack
if root:
# recursive step with a few optimizations
left_balanced, left_height = is_height_balanced(root.left)
if not left_balanced:
return False, 0 # no need to compute height
right_balanced, right_height = is_height_balanced(root.right)
if not right_balanced:
return False, 0
# merge left and right results
node_balanced = abs(left_height - right_height) <= 1
node_height = max(left_height, right_height) + 1
return node_balanced, node_height
else:
# base case
return True, -1
if __name__ == "__main__":
tree = BinaryTreeNode()
|
047239ca05aa7e55383767f781c5f5f6b026389f | neiljdo/problem-solving-practice | /EPIP/8_1.py | 1,405 | 4 | 4 | import sys
import math
from functools import partial
from collections import namedtuple
"""
Create a stack with a `max` API.
"""
class Stack():
"""
O(1) space
straightforward approach is to compute the max every push
when popping:
* if element popped is < max, no issue
* if element popped is max, O(n) to get new max via linear search
time-space tradeoff
compute max for current stack for each push - additional O(n) space
but for O(1) time max retrieval
"""
ElementWithMax = namedtuple("ElementWithMax", ("val", "max"))
def __init__(self):
self._stack = []
def is_empty(self):
return not len(self._stack)
def get_max(self):
# check for empty stack
if self.is_empty():
raise IndexError("max(): empty stack")
return self._stack[-1].max
def push(self, el):
self._stack.append(
self.ElementWithMax(el, el if self.is_empty() else max(el, self.get_max()))
)
def pop(self):
if self.is_empty():
raise IndexError("pop(): empty stack")
return self._stack.pop().val
if __name__ == "__main__":
stack = Stack()
stack.push(1)
print(stack.get_max())
stack.push(5)
stack.push(2)
print(stack.get_max())
stack.pop()
print(stack.get_max())
stack.pop()
print(stack.get_max()) |
212917d8632ff3d9d03628bcebd888fe356b6df4 | Indrasena8/Python-Programs | /GeometricProgression.py | 232 | 3.9375 | 4 | def printGP(a, r, n):
for i in range(0, n):
curr_term = a * pow(r, i)
print(curr_term, end =" ")
a = 2 # starting number
r = 3 # Common ratio
n = 5 # N th term to be find
printGP(a, r, n) |
04bd26afcd5d8f627206e8f311d27d7c9c0967dd | WahajAyub/RandomPythonProjects | /bounce.py | 2,000 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 29 13:47:34 2019
@author: wahaj
5"""
import math
class Box:
def __init__(self, mass, width, velocity, x):
self.m = mass
self.w = width
self.v = velocity
self.x = x
def checkCollision (self, other):
if ((self.x + self.w) >= other.x):
return True
else:
return False
def checkWallCollision (self):
if (self.x <= 0):
return True
else:
return False
def updatePosition (self):
self.x += self.v
# print (self.x)
def updateVelocity (self, other):
newv1 = ((self.m - other.m)*self.v + (2*other.m)*other.v)/(self.m+other.m)
newv2 = ((2*self.m)*self.v + (other.m - self.m)*other.v)/(self.m+other.m)
self.v = newv1
other.v = newv2
# print("v", self.v)
# print("v2", other.v)
def reverseVelocity (self):
self.v *= -1
def checkIfFinalCollision (self, other):
# print ("v1 {} v2 {}".format(self.v, other.v))
if self.v >= 0:
if other.v > self.v:
return True
else:
return False
else:
return False
counter = 0
digits = int (input ("Enter Number of Digits: "))
timesteps = 100
a = Box(1, 20, 0, 100)
mb = 100 ** (digits-1)
b = Box((mb), 100, (-5/timesteps), 200)
while (True):
a.updatePosition()
b.updatePosition()
if (a.checkCollision(b)):
a.updateVelocity(b)
counter += 1
if (a.checkIfFinalCollision(b)):
break
if (a.checkWallCollision()):
a.reverseVelocity()
counter += 1
if (a.checkIfFinalCollision(b)):
break
# print (counter)
print ("collisions", counter)
piestimate = counter/(10**(digits-1))
print ("pi is approximately equal to {}".format(piestimate))
|
541d24e31724f0e3b3180b9dfe3df381d05e510c | mateusfh/Concepcao | /MIPS/ADDAC/GoldenModel/somador.py | 230 | 3.640625 | 4 | def somador(a, b, carryIn):
y = a + b + carryIn
#print("Soma: ", y, a, b, carryIn)
cout = 0
if y > 1:
cout = 1
if y == 2:
y = 0
elif y == 3:
y = 1
return y, cout |
85be56b1f4f0ae5e51463b8ef7005fcef33fa357 | parasmaharjan/Python_DeepLearning | /ICP4/ClassObject.py | 1,226 | 4.125 | 4 | # Python Object-Oriented Programming
# attribute - data
# method - function associated with class
# Employee class
class Employee:
# special init method - as initialize or constructor
# self == instances
def __init__(self, first, last, pay, department):
self.first = first
self.last = last
self.pay = pay
self.department = department
def fullname(self):
return ('{} {}'.format(self.first, self.last))
# Instance variable
emp_1 = Employee('Paras','Maharjan', 50000, 'RnD')
#print(emp_1)
emp_2 = Employee('Sarap', 'Maharjan', 70000, 'Accounts')
#print(emp_2)
# print(emp_1.first, ' ', emp_1.last, ', ', emp_1.department, ', ', emp_1.pay)
# print(emp_2.first, ' ', emp_2.last, ', ', emp_2.department, ', ', emp_2.pay)
# print using place holder
print('First name\tLast name\tSalary($)\tDepartment')
print('----------------------------------------------')
print('{}\t\t{}\t{}\t\t{}'.format(emp_1.first, emp_1.last, emp_1.pay, emp_1.department))
print('{}\t\t{}\t{}\t\t{}'.format(emp_2.first, emp_2.last, emp_2.pay, emp_2.department))
# class instance is pass argument to method, so we need to use self
# print(Employee.fullname(emp_1))
# print(emp_2.fullname())
|
502f19b51e091cbe13dd7c94e6eb3556dcbf6b8c | parasmaharjan/Python_DeepLearning | /ICP2/Problem2.py | 138 | 3.78125 | 4 | file = open("Text.txt", 'r')
line = file.readline()
while line != "":
length = len(line)
print(length)
line = file.readline()
|
3107e5dd759abedf9efcd6e894fda9aefd350c61 | parasmaharjan/Python_DeepLearning | /ICP5/Problem1.py | 688 | 3.53125 | 4 | import numpy as np
import matplotlib.pyplot as plt
data = np.array([[0, 1], [1, 3], [2, 2], [3, 5], [4, 7], [5, 8], [6, 8], [7, 9], [8, 10], [9, 12]])
x = np.array([0, 1, 2, 3, 4, 5, 6, 7 , 8, 9])
y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12])
x_mean = np.mean(x)
print(x_mean)
y_mean = np.mean(y)
print(y_mean)
xx = x - x_mean
yy = y - y_mean
print(xx)
print(yy)
xy = xx * yy
print(xy)
xx_sqr = xx * xx
print(xx_sqr)
ssxy = np.sum(xy)
ssxx = np.sum(xx_sqr)
print(ssxy)
print(ssxx)
b1 = ssxy/ssxx
print(b1)
b0 = y_mean - b1*x_mean
print(b0)
# i = np.linspace(np.min(x)-1, np.max(x)+1, 1000)
j = b0 + b1 * x
plt.scatter(x, y, color='blue')
plt.plot(x, j, color='red')
plt.show()
|
ed0a242d34f528c283284beb7857763bd60b75c3 | Adam-smh/ErrorHandling | /main.py | 1,723 | 3.5625 | 4 | from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("Authentication")
root.config(bg="#e76f51")
root.geometry("500x600")
class Authentication:
def __init__(self, window):
self.username = Label(window, text="Enter Username:", font="25")
self.username.config(bg="#e76f51", fg="#2a9d8f")
self.username.place(relx="0.4", rely="0.1")
self.user_entry = Entry(window)
self.user_entry.place(relx="0.37", rely="0.2")
self.password = Label(window, text="Enter Password", font="25")
self.password.config(bg="#e76f51", fg="#2a9d8f")
self.password.place(relx="0.4", rely="0.4")
self.pass_entry = Entry(window)
self.pass_entry.place(relx="0.37", rely="0.5")
self.authenticate = Button(window, text="Authenticate", command=self.Auth)
self.authenticate.config(bg="#e9c46a", fg="#2a9d8f")
self.authenticate.place(relx="0.42", rely="0.6")
self.user_pass = {'Adam': 'bruh', 'Ronald': 'dudette', 'zoe': 'dude'}
def Auth(self):
name = self.user_entry.get()
pw = self.pass_entry.get()
try:
if name == "" or pw == "":
messagebox.showerror(message="Please enter details")
elif name in self.user_pass:
if pw == self.user_pass[name]:
root.destroy()
import window
else:
messagebox.showerror(message="Password incorrect")
else:
messagebox.showerror(message="Username not found")
except ValueError:
messagebox.showerror("error")
Authentication(root)
root.mainloop()
|
38a9a38575095feae8c1ed3b8509d61abade119a | dannyleandro/TDDKataSimple-G12 | /test_estadistica.py | 873 | 3.59375 | 4 | from unittest import TestCase
from KataSimple import Estadistica
class TestEstadistica(TestCase):
def test_getArregloVacio(self):
self.assertEqual(Estadistica().getArreglo(""), [0], "cadena vacia")
def test_getArregloUnNumero(self):
self.assertEqual(Estadistica().getArreglo("1"), [1], "Un numero")
# Ciclo TDD para que funcione con un string de 2 numeros
def test_getArregloDosNumeros(self):
self.assertEqual(Estadistica().getArreglo("1,3"), [2], "Dos numeros")
# Ciclo TDD para que funcione con un string de N numeros
def test_getArregloNNumeros(self):
self.assertEqual(Estadistica().getArreglo("1,3,5"), [3], "Tres numeros")
self.assertEqual(Estadistica().getArreglo("1,3,5,45"), [4], "Cuatro numeros")
self.assertEqual(Estadistica().getArreglo("1,3,5,45,10"), [5], "Cinco numeros")
|
88ea08642ab265bb8905d656916cae5922929d81 | Andrusha2999/pervaja | /pervaja.py | 586 | 3.875 | 4 | from module1 import *
while True:
print("funksioind".center(50,"+"))
print("arithmetic- A,\nis_year_leap-Y,\nseason- D ,\nyears- V")
v=input("arithmetic- A")
if v.upper()=="A":
a=float(input("esimene arv"))
b=float(input("teine arv"))
sym=input("Tehe:")
result=arithmetic(a,b,sym)
print(rezult)
elif v.upper()=="Y":
is_year_leap()
result=is_year_leap((int(input("sisesta aasta"))))
elif v.upper()=="D":
a=int(input("sisestage kuu"))
result=Aastahad(a)
print(result)
|
49629b071964130f6fb9034e96480f7b5a179e51 | aakhriModak/assignment-1-aakhriModak | /01_is_triangle.py | 2,117 | 4.59375 | 5 | """
Given three sides of a triangle, return True if it a triangle can be formed
else return False.
Example 1
Input
side_1 = 1, side_2 = 2, side_3 = 3
Output
False
Example 2
Input
side_1 = 3, side_2 = 4, side_3 = 5
Output
True
Hint - Accordingly to Triangle inequality theorem, the sum of any two sides of
a triangle must be greater than measure of the third side
"""
import unittest
# Implement the below function and run this file
# Return the output, No need read input or print the ouput
def is_triangle(side_1, side_2, side_3):
# write your code here
if side_1>0 and side_2>0 and side_3>0:
if side_1+side_2>side_3 and side_2+side_3>side_1 and side_1+side_3>side_2:
return True
else:
return False
else:
return False
# DO NOT TOUCH THE BELOW CODE
class TestIsTriangle(unittest.TestCase):
def test_01(self):
self.assertEqual(is_triangle(1, 2, 3), False)
def test_02(self):
self.assertEqual(is_triangle(2, 3, 1), False)
def test_03(self):
self.assertEqual(is_triangle(3, 1, 2), False)
def test_04(self):
self.assertEqual(is_triangle(3, 4, 5), True)
def test_05(self):
self.assertEqual(is_triangle(4, 5, 3), True)
def test_06(self):
self.assertEqual(is_triangle(5, 3, 4), True)
def test_07(self):
self.assertEqual(is_triangle(1, 2, 5), False)
def test_08(self):
self.assertEqual(is_triangle(2, 5, 1), False)
def test_09(self):
self.assertEqual(is_triangle(5, 1, 2), False)
def test_10(self):
self.assertEqual(is_triangle(0, 1, 1), False)
def test_11(self):
self.assertEqual(is_triangle(1, 0, 1), False)
def test_12(self):
self.assertEqual(is_triangle(1, 1, 0), False)
def test_13(self):
self.assertEqual(is_triangle(-1, 1, 2), False)
def test_14(self):
self.assertEqual(is_triangle(1, -1, 2), False)
def test_15(self):
self.assertEqual(is_triangle(1, 1, -2), False)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
cd9c9418168891a2255b5053d74b6db8cabafa82 | nevil-patel7/Astar-RigidRobots | /Project 3 Phase 3/Phase3.py | 11,657 | 3.515625 | 4 | import numpy as np
import matplotlib.pyplot as plt
import copy
import math
import time
#Variables
CurrentNode = []
UnvisitedNodes = []
VisitedNodes = []
CurrentIndex = 0
Rpm1 = 0
Rpm2 = 0
#Function to get Clearance,RPM
def GetParameters():
# global Rpm1,Rpm2
Clearance = int(input("Enter the Clearance of the robot in mm: "))
print("Enter the wheel RPM's separated by space: RPM1 RPM2")
RPM = list(map(int, input().split()))
Rpm1,Rpm2 = RPM[0]*3.14/30 , RPM[1]*3.14/30
Radius = 354/2
return Clearance,Rpm1,Rpm2,Radius
# print(GetParameters())
#To check the given node is in Obstacle Space
def InObstacleSpace(Node):
x = Node[0]
y = Node[1]
if(x**2 + y**2 <= (1000+Radius+Clearance)**2):
return True
Obstaclesx.append(x)
Obstaclesy.append(y)
elif((x+2000)**2 + (y+3000)**2 <= (1000+Radius+Clearance)**2):
return True
Obstaclesx.append(x)
Obstaclesy.append(y)
elif((x-2000)**2 + (y+3000)**2 <= (1000+Radius+Clearance)**2):
return True
Obstaclesx.append(x)
Obstaclesy.append(y)
elif((x-2000)**2 + (y-3000)**2 <= (1000+Radius+Clearance)**2):
return True
Obstaclesx.append(x)
Obstaclesy.append(y)
elif(((3750+Radius+Clearance)>=y>=(2250-Radius-Clearance)) and ((-2750-Radius-Clearance)<=x<=(-1250+Radius+Clearance))):
return True
Obstaclesx.append(x)
Obstaclesy.append(y)
elif(((750+Radius+Clearance)>=y>=(-750-Radius-Clearance)) and ((-4750-Radius-Clearance)<=x<=(-3250+Radius+Clearance))):
return True
Obstaclesx.append(x)
Obstaclesy.append(y)
elif(((750+Radius+Clearance)>=y>=(-750-Radius-Clearance)) and ((3250-Radius-Clearance)<=x<=(4750+Radius+Clearance))):
return True
Obstaclesx.append(x)
Obstaclesy.append(y)
elif((-5100)<=x<=(-5000+Radius+Clearance)):
return True
Obstaclesx.append(x)
Obstaclesy.append(y)
elif((5100)>=x>=(5000-Radius-Clearance)):
return True
Obstaclesx.append(x)
Obstaclesy.append(y)
elif((-5100)<=y<=(-5000+Radius+Clearance)):
return True
Obstaclesx.append(x)
Obstaclesy.append(y)
elif((5100)>=y>=(5000-Radius-Clearance)):
return True
Obstaclesx.append(x)
Obstaclesy.append(y)
else:
return False
# print(InObstacleSpace([-3075.39,-2904.24]))
#Function to get the Start Position
def GetStart():
global StartNode
while(True):
print("Enter the co-ordinates of starting point separated by space in mm (x,y,theta_s) --> x y theta_s :")
StartNode = list(map(int, input().split()))
if(len(StartNode)==3 and not(InObstacleSpace(StartNode))):
# StartNode = [StartNode[0],0,0,0,0]
StartNode = [StartNode[0],StartNode[1],StartNode[2],0,0,0,0]
# print("Start",StartNode)
break
else:
print("Please provide valid starting point")
return StartNode
# StartNode = GetStart()
#Function to get the Goal Position
def GetGoal():
global GoalNode
while(True):
print("Enter the co-ordinates of goal point separated by space in mm (x,y) --> x y : ")
GoalNode = list(map(int, input().split()))
if len(GoalNode)==2 and not(InObstacleSpace(GoalNode)):
break
else:
print("Please provide valid goal point")
return GoalNode
# GoalNode = GetGoal()
#Function to find the Euclidean Distance between two Points
def EuclieanDistance(x2,y2,x1,y1):
return math.sqrt((x2-x1)**2 + (y2-y1)**2)
#Function to Genrate map to plot the Obstacles
def GenerateMap():
# print("Entered GenerateMap")
XAll = np.linspace(-5100, 5100, num=200)
YAll = np.linspace(-5100, 5100, num=200)
Obstaclesx,Obstaclesy = [],[]
for x in XAll:
for y in YAll:
if(x**2 + y**2 <= (1000+Radius+Clearance)**2):
# return True
Obstaclesx.append(x)
Obstaclesy.append(y)
elif((x+2000)**2 + (y+3000)**2 <= (1000+Radius+Clearance)**2):
# return True
Obstaclesx.append(x)
Obstaclesy.append(y)
elif((x-2000)**2 + (y+3000)**2 <= (1000+Radius+Clearance)**2):
# return True
Obstaclesx.append(x)
Obstaclesy.append(y)
elif((x-2000)**2 + (y-3000)**2 <= (1000+Radius+Clearance)**2):
# return True
Obstaclesx.append(x)
Obstaclesy.append(y)
elif(((3750+Radius+Clearance)>=y>=(2250-Radius-Clearance)) and ((-2750-Radius-Clearance)<=x<=(-1250+Radius+Clearance))):
# return True
Obstaclesx.append(x)
Obstaclesy.append(y)
elif(((750+Radius+Clearance)>=y>=(-750-Radius-Clearance)) and ((-4750-Radius-Clearance)<=x<=(-3250+Radius+Clearance))):
# return True
Obstaclesx.append(x)
Obstaclesy.append(y)
elif(((750+Radius+Clearance)>=y>=(-750-Radius-Clearance)) and ((3250-Radius-Clearance)<=x<=(4750+Radius+Clearance))):
# return True
Obstaclesx.append(x)
Obstaclesy.append(y)
elif((-5100)<=x<=(-5000+Radius+Clearance)):
Obstaclesx.append(x)
Obstaclesy.append(y)
elif((5100)>=x>=(5000-Radius-Clearance)):
Obstaclesx.append(x)
Obstaclesy.append(y)
elif((-5100)<=y<=(-5000+Radius+Clearance)):
Obstaclesx.append(x)
Obstaclesy.append(y)
elif((5100)>=y>=(5000-Radius-Clearance)):
Obstaclesx.append(x)
Obstaclesy.append(y)
# print("Exitting GenerateMap")
return Obstaclesx,Obstaclesy
# Ox,Oy = GenerateMap()
# plt.show()
#Function to plot the Workspace
def GenerateWorkspace(Obstaclesx,Obstaclesy):
plt.xlim(-5100,5100)
plt.ylim(-5100,5100)
plt.plot(StartNode[0], StartNode[1], "gd", markersize = '2')
plt.plot(GoalNode[0], GoalNode[1], "gd", markersize = '2')
plt.scatter(Obstaclesx,Obstaclesy,color = 'b')
plt.pause(0.001)
# GenerateWorkspace(Ox,Oy)
# plt.show()
NodeInfo = np.zeros(np.array((205,205))) # Store visited Nodes
#Function to check if the node is already visited
def IsVisitedNode(Node):
global NodeInfo
if(NodeInfo[int(Node[0]/50)][int(Node[1]/50)] == 1):
# print("Duplicate")
return True
else:
NodeInfo[int(Node[0]/50)][int(Node[1]/50)] = 1
return False
# print(IsVisitedNode([25.01,61,178]))
# print(IsVisitedNode([25,74,-178]))
plotX =[]
#Function to add the new node to unvisited list if it is not in obstacle space and is unvisited
def AddNode(Node,px,py):
global CurrentNode
global UnvisitedNodes
global plotX
if not(InObstacleSpace(Node)) and not(IsVisitedNode(Node)):
UnvisitedNodes.append(Node)
# plt.plot(px, py, color="r")
plotX.append([px,py])
if(len(plotX)%100 == 0):
for i in plotX:
plt.plot(i[0], i[1], color="r")
plt.pause(0.0001)
plotX= []
if(EuclieanDistance(GoalNode[0],GoalNode[1],Node[0],Node[1]) <= 150):
CurrentNode = Node
for i in plotX:
plt.plot(i[0], i[1], color="r")
plt.pause(0.0001)
plotX= []
plt.scatter(Node[0],Node[1])
return True
else:
return False
# AddNode([3.27,2.75,30,5.22,1])
# AddNode([3.4,3.1,30,0,1])
fig, ax = plt.subplots()
#Function to Genrate a new node
def GenerateNode(Node,action):
# print(action)
t=0
r=38
L=317.5
dt=0.1
Xn=Node[0]
Yn=Node[1]
Thetan = 3.14 * Node[2] / 180
Cost = 0
# Xi, Yi,Thetai: Input point's coordinates
# Xs, Ys: Start point coordinates for plot function
# Xn, Yn, Thetan: End point coordintes
plotx = []
ploty = []
while t<1.5:
t = t + dt
Xs = Xn
Ys = Yn
Xn += 0.5*r * (action[0] + action[1]) * math.cos(Thetan) * dt
Yn += 0.5*r * (action[0] + action[1]) * math.sin(Thetan) * dt
Thetan += (r / L) * (action[1] - action[0]) * dt
Cost += EuclieanDistance(Xn,Yn,Xs,Ys)
if(InObstacleSpace([Xn,Yn])):
plotx = []
ploty = []
break
plotx.append([Xs,Xn])
ploty.append([Ys,Yn])
# plt.plot([Xs, Xn], [Ys, Yn], color="blue")
Thetan = 180 * (Thetan) / 3.14
CostToCome = Node[4] + Cost
NewCost = CostToCome + EuclieanDistance(Xn,Yn,GoalNode[0],GoalNode[1])
NewNode = [Xn,Yn,Thetan,NewCost,CostToCome,CurrentIndex,action]
return NewNode,plotx,ploty
#Function to Plot a Curve
def PlotPath(Node,action):
t=0
r=38
L=317.5
dt=0.1
Xn=Node[0]
Yn=Node[1]
Thetan = 3.14 * Node[2] / 180
# Cost = 0
# Xi, Yi,Thetai: Input point's coordinates
# Xs, Ys: Start point coordinates for plot function
# Xn, Yn, Thetan: End point coordintes
while t<1.5:
t = t + dt
Xs = Xn
Ys = Yn
Xn += 0.5*r * (action[0] + action[1]) * math.cos(Thetan) * dt
Yn += 0.5*r * (action[0] + action[1]) * math.sin(Thetan) * dt
Thetan += (r / L) * (action[1] - action[0]) * dt
plt.plot([Xs, Xn], [Ys, Yn], color="g")
#Action Set
actions=[[0,Rpm1],[Rpm1,0],[Rpm1,Rpm1],[0,Rpm2],[Rpm2,0],[Rpm1,Rpm2],[Rpm2,Rpm1],[Rpm2,Rpm2]]
#Function to generate possible motions based on parameters
def ActionMove(Node):
for action in actions:
NewNode,px,py = GenerateNode(Node,action)
Goal = AddNode(NewNode,px,py)
if(Goal):
return True
else:
return False
# x = ActionMove(StartNode)
Path = [] #To store the path
#Function to backtrack solution path
def BackTrack(Node):
global CurrentNode
Path.append(Node)
# print("Path",Path,CurrentNode)
while(Path[0][5] != 0):
print(VisitedNodes[Path[0][5]])
Path.insert(0,VisitedNodes[CurrentNode[5]])
CurrentNode=Path[0]
Path.insert(0,VisitedNodes[0])
plt.pause(0.001)
return Path
ax.set_aspect('equal')
plt.title('A-Star Algorithm',fontsize=10)
Goal = False
Clearance,Rpm1,Rpm2,Radius = GetParameters()
actions=[[0,Rpm1],[Rpm1,0],[Rpm1,Rpm1],[0,Rpm2],[Rpm2,0],[Rpm1,Rpm2],[Rpm2,Rpm1],[Rpm2,Rpm2]]
X,Y = GenerateMap()
StartNode = GetStart()
GoalNode = GetGoal()
GenerateWorkspace(X,Y)
StartTime = time.time()
CurrentNode = copy.deepcopy(StartNode)
UnvisitedNodes.append(CurrentNode)
while(1):
VisitedNodes.append(UnvisitedNodes.pop(0))
Goal = ActionMove(CurrentNode)
UnvisitedNodes.sort(key = lambda x: x[3])
if(len(UnvisitedNodes)>4000): #Removing Old nodes with higher cost to reduce the runtime
UnvisitedNodes = UnvisitedNodes[:3000]
print("Deleting")
if(Goal):
print("Goal",CurrentNode)
break
CurrentIndex += 1
CurrentNode = UnvisitedNodes[0]
if(Goal):
Path = BackTrack(CurrentNode)
print("Path",Path)
for i in range(len(Path)-1):
PlotPath(Path[i],Path[i+1][6])
EndTime = time.time()
print("Solved" , EndTime - StartTime)
plt.show()
plt.close()
|
34b54ec83214420e2b61b73a3c9f595cc9ca309d | xbash/Progra-0769 | /CLASES/holaPython18_1.py | 519 | 3.5625 | 4 | def validaNumero(promptText):
try:
x = int(float(raw_input(promptText)))
return x
except ValueError:
return None
def leerNumero(promptText):
x = validaNumero(promptText)
while(x == None):
x = validaNumero(promptText)
return x
try:
num = leerNumero('Ingrese numerador: ')
den = leerNumero('Ingrese denominador: ')
a = num / den
except ZeroDivisionError:
while(den == 0):
den = leerNumero('Tonto, ingrese un denominador valido: ')
a = num / den
print a
k
|
95ae4edda6635d1e4ee9d27c3ce435d344695974 | xbash/Progra-0769 | /CLASES/holaPython12.py | 1,373 | 3.59375 | 4 | #Diccionarios
Guatemala = {'Capital':'Guatemala','Habitantes':15.08e6,'Extension':108889}
Eslovenia = {'Capital':'Liublijana','Habitantes':2.047e6,'Extension':20253}
Italia = {'Capital':'Roma','Habitantes':59.4e6,'Extension':301338}
Cuba = {'Capital':'La Habana','Habitantes':11.24e6,'Extension':110860}
print Guatemala['Capital']
Guatemala['Capital'] = 'Cd. Guatemala'
print Guatemala['Capital']
print ""
print 'Habitantes en Eslovenia'
print Eslovenia['Habitantes']
Eslovenia['Habitantes'] = 2e6 #Notacion cientifica!
print ""
print "Existe la clave 'capital' en Guatemala?"
print (Guatemala.has_key('capital'))
print ""
print "Existe la clave 'Capital' en Guatemala?"
print (Guatemala.has_key('Capital'))
print ""
print "Que valor tiene asociada la clave 'Extension' en Cuba?"
print Cuba['Extension']
print ""
print "Cuantos elementos tiene Italia?"
print str(len(Italia))
print ""
print "Que claves tiene Italia?"
print Italia.keys()
print ""
print "Que valores tienen las claves de Italia?"
print Italia.values()
print ""
print "Que elementos contiene Italia?"
print Italia.items()
print ""
print "Eliminaremos la clave 'Extension' de Italia"
del Italia['Extension']
print ""
print 'Si juntamos todos los paises en una lista: '
paises = [Guatemala, Eslovenia, Italia, Cuba]
for i in paises:
print i
print "Notese que Italia ya no tiene 'Extension'..."
|
bfc62e67d675d594f83ddcd562fb5c44ed69a296 | xbash/Progra-0769 | /CLASES/holaPython11.py | 1,138 | 3.765625 | 4 | import random
#Mas sobre ciclos while
#Numero magico
def generaAleatorio(rango):
x = random.randrange(rango[0], rango[1], 1)
#print x #Imprimir el numero secreto: SOLO PARA DEPURACION
return x
def verifica(x, n):
"""
x: Ingresado por el usuario
n : Generado aleatoriamente al inicio del juego
"""
if(n < x):
print 'El numero secreto es menor a',str(x)
return 0
elif(n > x):
print 'El numero secreto es mayor a',str(x)
return 0
else:
print '\n\nAcertaste!'
return 1
def leeNumero(data):
if data.isdigit():
return int(data)
else:
print "Error"
return 0
def jugar(rango = [0, 20]):
n = generaAleatorio(rango)
cnt = 1 #Conteo de intentos
ok = 0 #Bandera para verificar si se acerto o no
while(not ok):
print '\nIntento:',str(cnt)
print 'Ingrese un numero entre',str(rango[0]),'y',str(rango[1]),':',
x = leeNumero(raw_input())
ok = verifica(x, n)
cnt += 1
print 'Utilizaste',str(cnt-1),'intentos para encontrar al secreto:' ,str(n)
jugar()
|
28ef97ef53a13df5260eb59cb610a624f2cad690 | dieuwkehupkes/POStagging | /HMMgenerator.py | 17,864 | 3.515625 | 4 | """
Functions to generate HMMs.
Add scaled smoothing lexicon dict (based on how often a word occured)
"""
from HMM2 import HMM2
import string
import numpy
import copy
from collections import Counter
import csv # do something with this
import sys
import itertools
class HMM2_generator:
"""
HMM2_generator is a class with functions to generate second
order hidden markov models from text files.
"""
def init_transition_matrix(self, tagIDs):
"""
Transition probabilities are stored in a 3-dimensional
matrix. The probabilities can be accessed with tagIDs.
E.g., P(t3| t1, t2) can be found in T[t1, t2, t3].
Initialise an empty transition matrix.
:param tagIDs: a map from tagnames to IDs
:type tagIDs: dictionary
"""
N = len(tagIDs)
transition_matrix = numpy.zeros(shape=(N, N, N), dtype=numpy.float64)
return transition_matrix
def init_lexicon_matrix(self, wordIDs, tagIDs):
"""
Emission probabilities are stored in a 2-dimensional
matrix. The probabilities can be accessed with tag-
and wordIDs. E.g. P(w|t) can be found in E[t, w].
Initialise an empty lexicon matrix.
"""
nr_of_words = len(wordIDs)
nr_of_tags = len(tagIDs)
lexicon_matrix = numpy.zeros(shape=(nr_of_tags, nr_of_words), dtype=numpy.float64)
return lexicon_matrix
def generate_tag_IDs(self, tags):
"""
Given a set of tags, generate a dictionary that
assigns an ID to every tag. The tagID can be used
to look up information in the transition and
emission matrix.
"""
IDs = [x for x in xrange(len(tags))]
maxID = IDs[-1]
self.tagIDs = dict(zip(tags, IDs))
self.tagIDs['$$$'] = maxID + 1
self.tagIDs['###'] = maxID + 2
return self.tagIDs
def generate_lexicon_IDs(self, words):
"""
Generate a dictionary that stores the relation between
words and emission matrix. The ID generated for a
word is the index that can be used to look up the
word in the emission matrix
"""
self.wordIDs = dict(zip(words, [i for i in xrange(len(words))]))
return self.wordIDs
def find_tags(self, input_data):
"""
Find all the tags occuring in the inputdata. Input data
can be both a file name and a list with sentences.
"""
data = self.get_data(input_data, delimiter=True)
tags = set([item[1] for item in data if item != []])
return tags
def get_hmm_dicts_from_file(self, input_data, tags, words):
"""
Generate a matrix containing trigram counts from a file.
The beginning and end of the sentence are modelled with
the beginning and end of sentence tags ('$$$' and "###',
respectively).
:param input_data: A list with sentences or a file with labeled
sentences. If input is a file, every line of it
should contain a word and a tag separated by a tab.
New sentences should be delimited by new lines.
:type input_data: string or list
:param tags: A list or set of possible tags
:param words: A list or set of all words
"""
# make list representation data.
data = self.get_data(input_data, delimiter=True)
# generate word and tagIDs
wordIDs = self.generate_lexicon_IDs(words)
tagIDs = self.generate_tag_IDs(tags)
ID_end, ID_start = tagIDs['###'], tagIDs['$$$']
# initialise transition and emission matrix
trigrams = self.init_transition_matrix(tagIDs)
emission = self.init_lexicon_matrix(wordIDs, tagIDs)
# initialisatie
prev_tagID, cur_tagID = ID_end, ID_start
# loop over lines in list:
# Maybe this can be done faster or smarter
for wordtag in data:
try:
# line contains a tag and a word
word, tag = wordtag
wordID, tagID = wordIDs[word], tagIDs[tag]
trigrams[prev_tagID, cur_tagID, tagID] += 1
emission[tagID, wordID] += 1
prev_tagID = cur_tagID
cur_tagID = tagID
except ValueError:
# end of sentence
trigrams[prev_tagID, cur_tagID, ID_end] += 1
trigrams[cur_tagID, ID_end, ID_start] += 1
prev_tagID, cur_tagID = ID_end, ID_start
# add last trigram if file did not end with white line
if prev_tagID != ID_end:
trigrams[prev_tagID, cur_tagID, ID_end] += 1
trigrams[cur_tagID, ID_end, ID_start] += 1
return trigrams, emission
def get_lexicon_counts(self, input_data, tagIDs, wordIDs):
"""
containing a word and a tag separated by a tab.
:param input_data: A list with sentences or a file with labeled
sentences. If input is a file, every line of it
should contain a word and a tag separated by a tab.
New sentences should be delimited by new lines.
should contain a word and a tag separated by a tab.
New sentences should be delimited by new lines.
:type input_data: string or list
:param tagIDs: A dictionary with IDs for all possible tags.
:param wordIDs: A dictionary with IDs for all possible words.
"""
# Load data
data = self.get_data(input_data, delimiter=True)
# initialise emission matrix
emission = self.init_lexicon_matrix(wordIDs, tagIDs)
# generate counts for all words in the data
counts = Counter([tuple(item) for item in data])
# remove newlines
del counts[()]
# add counts to lexicon
for wordtag in counts:
word, tag = wordtag
emission[tagIDs[tag], wordIDs[word]] = counts[wordtag]
return emission
def get_trigrams_from_file(self, input_data, tagIDs):
"""
Generate a matrix with trigram counts from the input file.
Use the tagIDs as indices for the different tags.
containing lines with a word and a tag separated by a tab.
:param input_data: A list with sentences or a file with labeled
sentences. If input is a file, every line of it
should contain a word and a tag separated by a tab.
New sentences should be delimited by new lines.
:type input_data: string or list
:param tagIDs: A dictionary with IDs for all possible tags.
:param wordIDs: A dictionary with IDs for all possible words.
"""
# get data
data = self.get_data(input_data, delimiter='\t')
# Initialisation
trigrams = self.init_transition_matrix(tagIDs)
ID_end, ID_start = tagIDs['###'], tagIDs['$$$']
prev_tagID, cur_tagID = ID_end, ID_start # beginning of sentence
# loop over data
# for line in data:
for line in data:
try:
word, tag = line
tagID = tagIDs[tag]
trigrams[prev_tagID, cur_tagID, tagID] += 1.0
prev_tagID = cur_tagID
cur_tagID = tagID
except ValueError:
# end of sentence
trigrams[prev_tagID, cur_tagID, ID_end] += 1.0
trigrams[cur_tagID, ID_end, ID_start] += 1.0
prev_tagID, cur_tagID = ID_end, ID_start
# f.close()
# add last trigram if file did not end with white line
if prev_tagID != ID_end:
trigrams[prev_tagID, cur_tagID, ID_end] += 1.0
trigrams[cur_tagID, ID_end, ID_start] += 1.0
return trigrams
def make_hmm(self, trigrams, emission, tagIDs, wordIDs, smoothing=None):
"""
Make an HMM object.
:param trigrams: A 3-dimensional matrix with trigram counts.
:param emission: A 2-dimensional matrix with lexical counts.
:param tagIDs: A map from tags to IDs.
:type tagIDs: dictionary
:param wordIDs: A map from words to IDs.
:type wordIDs: dictionary
:param smoothing: Optional argument to provide the lambda
values for linear interpolation.
"""
transition_dict = self.get_transition_probs(trigrams, smoothing)
emission_dict = self.get_emission_probs(emission)
hmm = HMM2(transition_dict, emission_dict, tagIDs, wordIDs)
return hmm
def weighted_lexicon_smoothing(self, lexicon_counts, unlabeled_dict, ratio=1.0):
"""
Smooth the lexicon by adding frequency counts f(w,tag) for
all words and tags in the lexicon. The total frequency added
is a ratio of the number of times a word is already in the
lexicon. The frequency is then split among all possible tags.
An exception exists for punctuation tags and words, whose frequency
counts will remain unchanged.
"""
nr_of_tags = len(self.tagIDs) - 2
# check if punctiation tag is in lexicon
punctID = None
if 'LET' in self.tagIDs:
nr_of_tags -= 1
punctID = self.tagIDs['LET']
word_sums = lexicon_counts.sum(axis=0)
# loop over words found in unlabeled file
for word in unlabeled_dict:
wordID = self.wordIDs[word]
# If word is in punctuation, assign punctuation tag
# and continue
if word in string.punctuation:
lexicon_counts[punctID, wordID] += 1
continue
# check occurences of word
word_sum_cur = word_sums[wordID]
if word_sum_cur == 0:
word_sum_cur = 1
# compute additional frequencies for word tag pairs
extra_freq = unlabeled_dict[word]/word_sum_cur*ratio
lexicon_counts[:-2, wordID] += extra_freq
if punctID:
lexicon_counts[punctID, wordID] -= extra_freq
return lexicon_counts
def lexicon_dict_add_unlabeled(self, word_dict, lexicon):
"""
Add counts to all words in an unlabeled file. It is assumed all
words are assigned IDs yet and exist in the emission matrix.
Currently the added counts are equally divided over all input tags,
and also regardless of how often the word occurred in the unlabeled file.
Later I should implement a more sophisticated initial estimation,
and do some kind of scaling to prevent the unlabeled words from becoming
too influential (or not influential enough).
"""
# create set with tagIDs
new_lexicon = copy.copy(lexicon)
word_IDs, punctuation_IDs = set([]), set([])
for word in word_dict:
if word not in string.punctuation:
word_IDs.add(self.wordIDs[word])
else:
punctuation_IDs.add(self.wordIDs[word])
word_IDs = tuple(word_IDs)
if 'LET' in self.tagIDs:
count_per_tag = 1.0/float(lexicon.shape[0]-3)
punctuation_ID = self.tagIDs['LET']
new_lexicon[:punctuation_ID, word_IDs] += count_per_tag
new_lexicon[:punctuation_ID+1:-2, word_IDs] += count_per_tag
new_lexicon[punctuation_ID, tuple(punctuation_IDs)] += 1.0
else:
count_per_tag = 1.0/float(lexicon.shape[0]-2)
if len(punctuation_IDs) == 0:
new_lexicon[:-2, word_IDs] += count_per_tag
else:
print "No punctuation tag is provided"
raise KeyError
return new_lexicon
def unlabeled_make_word_list(self, input_data):
"""
Make a dictionary with all words in
unlabeled file.
"""
data = self.get_data(input_data, delimiter=True)
words = Counter(itertools.chain(*data))
return words
def labeled_make_word_list(self, input_data):
"""
Make a dictionary with all words in a
labeled file.
"""
data = self.get_data(input_data, delimiter=True)
word_dict = Counter([item[0] for item in data if item != []])
return word_dict
word_dict = {}
for line in data:
try:
word, tag = line.split()
word_dict[word] = word_dict.get(word, 0) + 1
except ValueError:
continue
return word_dict
def get_transition_probs(self, trigram_counts, smoothing=None):
"""
Get trigram probabilities from a frequency matrix.
:param smoothing: give a list with lambdas to smooth the probabilities
with linear interpolation
:type smoothing list
"""
# Impossible events mess up the probability model, so that the counts
# do not add up to 1, I should do something about this.
trigram_sums = trigram_counts.sum(axis=2)
trigram_sums[trigram_sums == 0.0] = 1.0
trigram_probs = trigram_counts / trigram_sums[:, :, numpy.newaxis]
if not smoothing:
return trigram_probs
# Check if lambda values sum up to one
assert sum(smoothing) == 1.0, "lamdba parameters do not add up to 1"
# smooth counts to keep prob model consisent
smoothed_counts = trigram_counts + 0.001
smoothed_counts = self.reset_smoothed_counts(smoothed_counts)
smoothed_sums = smoothed_counts.sum(axis=2)
smoothed_sums[smoothed_sums == 0.0] = 1.0
smoothed_probs = smoothed_counts / smoothed_sums[:, :, numpy.newaxis]
# compute bigram counts
# note that this only works if the counts are generated
# from one file with the generator from this class
bigram_counts = self.reset_bigram_counts(smoothed_sums)
bigram_probs = bigram_counts/bigram_counts.sum(axis=1)[:, numpy.newaxis]
# compute unigram counts
# note that this only works if the counts are generated
# from one file with the generator from this class
unigram_counts = trigram_counts.sum(axis=(0, 2))
unigram_probs = unigram_counts/unigram_counts.sum()
# interpolate probabilities
l1, l2, l3 = smoothing
smoothed_probs = l1*unigram_probs + l2*bigram_probs + l3*trigram_probs
# reset probabilites for impossible events
smoothed_probs = self.reset_smoothed_counts(smoothed_probs)
# normalise again
sums = smoothed_probs.sum(axis=2)
sums[sums == 0.0] = 1.0
probabilities = smoothed_probs/sums[:, :, numpy.newaxis]
return probabilities
def reset_bigram_counts(self, bigram_counts):
"""
Reset counts for impossible bigrams.
"""
# reset counts for bigrams !### $$$
bigram_counts[:-2, -2] = 0.0
# reset counts for bigrams ### !$$$
bigram_counts[-1, :-2] = 0.0
bigram_counts[-1, -1] = 0.0
return bigram_counts
def reset_smoothed_counts(self, smoothed_counts):
"""
Reset probabilities for impossible trigrams.
"""
# reset matrix entries that correspond with trigrams
# containing TAG $$$, where TAG != ###
smoothed_counts[:, :-1, -2] = 0.0 # X !### $$$
smoothed_counts[:-1, -2, :] = 0.0 # !### $$$ X
# reset matrix entries that correspond with trigrams
# containing ### TAG where TAG != $$$
smoothed_counts[:, -1, :-2] = 0.0 # X ### !$$$
smoothed_counts[:, -1, -1] = 0.0 # X ### ###
smoothed_counts[-1, :-2, :] = 0.0 # ### !$$$ X
smoothed_counts[-1, -1, :] = 0.0 # ### ### X
# smoothed_probs[:, -1, -2] = 1.0 # P($$$| X ###) = 1
return smoothed_counts
def transition_dict_add_alpha(self, alpha, trigram_count_matrix):
"""
Add alpha smoothing for the trigram count dictionary
"""
# Add alpha to all matrix entries
trigram_count_matrix += alpha
# reset matrix entries that correspond with trigrams
# containing TAG $$$, where TAG != ###
trigram_count_matrix[:, :-1, -2] = 0.0 # X !### $$$
trigram_count_matrix[:-1, -2, :] = 0.0 # !### $$$ X
# reset matrix entries that correspond with trigrams
# containing ### TAG where TAG != $$$
trigram_count_matrix[:, -1, :-2] = trigram_count_matrix[:, -1, -1] = 0.0
trigram_count_matrix[-1, :-2, :] = trigram_count_matrix[-1, -1, :] = 0.0
return trigram_count_matrix
def get_emission_probs(self, lexicon):
"""
Get emission probabilities from a dictionary
with tag, word counts
"""
tag_sums = lexicon.sum(axis=1)
tag_sums[tag_sums == 0.0] = 1
lexicon /= tag_sums[:, numpy.newaxis]
return lexicon
def get_data(self, input_data, delimiter=None):
"""
If input_data is a filename, return
a list of the lines in the file with
this name. Otherwise, return
inputdata as inputted.
:rtype: list
"""
if isinstance(input_data, list):
data = input_data
elif isinstance(input_data, str):
f = open(input_data, 'r')
data = f.readlines()
f.close()
else:
return ValueError
if delimiter and not isinstance(data[0], list):
data = [x.split() for x in data]
return data
|
ff99acfff83d155f961d08ebf9301d8cb706d8ae | gandreadis/danger-zone | /danger_zone/agents/car.py | 12,743 | 3.6875 | 4 | from danger_zone.map.map import MAP_SIZE
from danger_zone.map.tile_types import TILE_DIRECTIONS, Tile, NEUTRAL_ZONES
CAR_LENGTH = 3
CAR_WIDTH = 2
class Car:
"""Class representing a car agent."""
def __init__(self, position, is_horizontal, map_state):
"""
Constructs an instance of this class.
:param position: The initial position of the agent (spawn-location).
:param is_horizontal: Whether the car is horizontally oriented.
:param map_state: The current MapState instance.
"""
self.position = position
self.spawn_position = position[:]
self.in_spawn_area = True
self.is_horizontal = is_horizontal
self.map_state = map_state
self.previous_direction = (0, 0)
def move(self):
"""
Evaluates the current tick state and makes a move if the tiles in front of it allow it.
Looks first at the probe tile underneath it. From this, it derives its preferred direction. After having decided
which way it wants to go, it checks the tiles immediately in front of it for other agents. If they are occupied,
the agent does not move. If those are free, the agent checks the tiles two steps in front of it. If those are
crosswalk (neutral) tiles and if they are occupied by pedestrians, no move is made. Else, the agent proceeds to
move ahead.
"""
x, y = self.position
if self.in_spawn_area:
if 0 <= x < MAP_SIZE and 0 <= y < MAP_SIZE:
self.in_spawn_area = False
preferred_direction = self.get_preferred_direction()
if preferred_direction == (0, 0):
return
new_tiles = self.calculate_tiles_ahead(preferred_direction)
if self.can_advance(new_tiles, preferred_direction):
self.position = self.position[0] + preferred_direction[0] * 2, self.position[1] + preferred_direction[1] * 2
self.update_cache_after_move(preferred_direction, new_tiles)
self.previous_direction = preferred_direction[:]
def get_preferred_direction(self):
"""
Decides which direction to go next.
If the agent is still in the spawn margin, it checks in which of the four margins it is situated. Else, it
checks the map tile underneath the top-left corner for the tile direction.
:return: The preferred direction of movement.
"""
x, y = self.position
current_map_tile = self.map_state.map.get_tile(*self.get_probe_location())
if self.in_spawn_area:
if x < 0:
return 1, 0
elif x >= MAP_SIZE:
return -1, 0
elif y < 0:
return 0, 1
elif y >= MAP_SIZE:
return 0, -1
elif current_map_tile in TILE_DIRECTIONS:
return TILE_DIRECTIONS[current_map_tile]
return 0, 0
def get_probe_location(self):
"""
Determines the coordinates of the probing location.
This location should always be the front left tile, relative to the cars rotation.
:return: The coordinates of the direction probing location.
"""
probe_x, probe_y = self.position
if self.previous_direction == (1, 0):
probe_x += CAR_LENGTH - 1
elif self.previous_direction == (0, 1):
probe_y += CAR_LENGTH - 1
return probe_x, probe_y
def calculate_tiles_ahead(self, preferred_direction):
"""
Calculates the coordinates of the tiles that lie immediately ahead.
:param preferred_direction: The direction the car will be moving in.
:return: The tiles that lie one or two hops ahead.
"""
if preferred_direction == (1, 0):
return (
(self.position[0] + CAR_LENGTH, self.position[1]),
(self.position[0] + CAR_LENGTH, self.position[1] + 1),
(self.position[0] + CAR_LENGTH + 1, self.position[1]),
(self.position[0] + CAR_LENGTH + 1, self.position[1] + 1),
)
elif preferred_direction == (-1, 0):
return (
(self.position[0] - 1, self.position[1]),
(self.position[0] - 1, self.position[1] + 1),
(self.position[0] - 2, self.position[1]),
(self.position[0] - 2, self.position[1] + 1),
)
elif preferred_direction == (0, 1):
return (
(self.position[0], self.position[1] + CAR_LENGTH),
(self.position[0] + 1, self.position[1] + CAR_LENGTH),
(self.position[0], self.position[1] + CAR_LENGTH + 1),
(self.position[0] + 1, self.position[1] + CAR_LENGTH + 1),
)
elif preferred_direction == (0, -1):
return (
(self.position[0], self.position[1] - 1),
(self.position[0] + 1, self.position[1] - 1),
(self.position[0], self.position[1] - 2),
(self.position[0] + 1, self.position[1] - 2),
)
def calculate_crosswalk_check_tiles(self, preferred_direction):
"""
Calculates the coordinates of the tiles that lie to either side of the car, for waiting pedestrians.
:param preferred_direction: The direction the car will be moving in.
:return: The tiles that lie to diagonally in front of it.
"""
if preferred_direction == (1, 0):
return (
(self.position[0] + CAR_LENGTH, self.position[1] - 1),
(self.position[0] + CAR_LENGTH, self.position[1] + 2),
(self.position[0] + CAR_LENGTH + 1, self.position[1] - 1),
(self.position[0] + CAR_LENGTH + 1, self.position[1] + 2),
)
elif preferred_direction == (-1, 0):
return (
(self.position[0] - 1, self.position[1] - 1),
(self.position[0] - 1, self.position[1] + 2),
(self.position[0] - 2, self.position[1] - 1),
(self.position[0] - 2, self.position[1] + 2),
)
elif preferred_direction == (0, 1):
return (
(self.position[0] - 1, self.position[1] + CAR_LENGTH),
(self.position[0] + 2, self.position[1] + CAR_LENGTH),
(self.position[0] - 1, self.position[1] + CAR_LENGTH + 1),
(self.position[0] + 2, self.position[1] + CAR_LENGTH + 1),
)
elif preferred_direction == (0, -1):
return (
(self.position[0] - 1, self.position[1] - 1),
(self.position[0] + 2, self.position[1] - 1),
(self.position[0] - 1, self.position[1] - 2),
(self.position[0] + 2, self.position[1] - 2),
)
def can_advance(self, new_tiles, preferred_direction):
"""
Determines whether the car can advance in the direction it wants to (based on occupancy of tiles ahead).
:param new_tiles: The differential of new tiles that will be occupied.
:param preferred_direction: The direction that the car should move in.
:return: Whether the agent is allowed to move in this direction.
"""
# If next tiles are beyond map, don't advance
if not self.map_state.map.is_on_map(*new_tiles[0]) or not self.map_state.map.is_on_map(*new_tiles[1]):
return False
# If next tiles are occupied, don't advance
if [self.map_state.get_tile_from_cache(*tile) != Tile.EMPTY for tile in new_tiles].count(True) > 0:
return False
# If the tiles are crosswalks and pedestrians are next to them, don't advance
if [self.map_state.map.get_tile(x, y) in NEUTRAL_ZONES for x, y in new_tiles].count(True) > 0:
crosswalk_checks = self.calculate_crosswalk_check_tiles(preferred_direction)
if [self.map_state.get_tile_from_cache(*crosswalk_check) == Tile.PEDESTRIAN
for crosswalk_check in crosswalk_checks].count(True) > 0:
return False
# Check three tiles ahead for pedestrians, in case of neutral zone
three_tiles_ahead = (
(new_tiles[2][0] + preferred_direction[0], new_tiles[2][1] + preferred_direction[1]),
(new_tiles[3][0] + preferred_direction[0], new_tiles[3][1] + preferred_direction[1]),
)
for x, y in three_tiles_ahead:
# If there is a pedestrian on a tile that's two steps ahead, don't advance
if self.map_state.map.is_on_map(x, y) \
and self.map_state.map.get_tile(x, y) in NEUTRAL_ZONES \
and self.map_state.get_dynamic_tile(x, y) == Tile.PEDESTRIAN:
return False
return True
def update_cache_after_move(self, direction_moved, new_tiles):
"""
Updates the dynamic MapState tile cache following a successful move.
:param direction_moved: The direction that the car has been determined to move in.
:param new_tiles: The differential of new tiles that will be occupied.
"""
self.map_state.set_tile_in_cache(*new_tiles[0], Tile.CAR)
self.map_state.set_tile_in_cache(*new_tiles[1], Tile.CAR)
if direction_moved == (1, 0):
self.map_state.set_tile_in_cache(self.position[0], self.position[1], Tile.EMPTY)
self.map_state.set_tile_in_cache(self.position[0], self.position[1] + 1, Tile.EMPTY)
self.map_state.set_tile_in_cache(self.position[0] + 1, self.position[1], Tile.EMPTY)
self.map_state.set_tile_in_cache(self.position[0] + 1, self.position[1] + 1, Tile.EMPTY)
elif direction_moved == (-1, 0):
self.map_state.set_tile_in_cache(self.position[0] + CAR_LENGTH - 2, self.position[1], Tile.EMPTY)
self.map_state.set_tile_in_cache(self.position[0] + CAR_LENGTH - 2, self.position[1] + 1, Tile.EMPTY)
self.map_state.set_tile_in_cache(self.position[0] + CAR_LENGTH - 2, self.position[1], Tile.EMPTY)
self.map_state.set_tile_in_cache(self.position[0] + CAR_LENGTH - 2, self.position[1] + 1, Tile.EMPTY)
elif direction_moved == (0, 1):
self.map_state.set_tile_in_cache(self.position[0], self.position[1], Tile.EMPTY)
self.map_state.set_tile_in_cache(self.position[0] + 1, self.position[1], Tile.EMPTY)
self.map_state.set_tile_in_cache(self.position[0], self.position[1] + 1, Tile.EMPTY)
self.map_state.set_tile_in_cache(self.position[0] + 1, self.position[1] + 1, Tile.EMPTY)
elif direction_moved == (0, -1):
self.map_state.set_tile_in_cache(self.position[0], self.position[1] + CAR_LENGTH - 1, Tile.EMPTY)
self.map_state.set_tile_in_cache(self.position[0] + 1, self.position[1] + CAR_LENGTH - 1, Tile.EMPTY)
self.map_state.set_tile_in_cache(self.position[0], self.position[1] + CAR_LENGTH - 2, Tile.EMPTY)
self.map_state.set_tile_in_cache(self.position[0] + 1, self.position[1] + CAR_LENGTH - 2, Tile.EMPTY)
def get_tiles(self):
"""
Returns the tiles that this car occupies on the map.
:return: The tiles that the agent occupies.
"""
tiles = []
for x in range(self.position[0],
self.position[0] + CAR_LENGTH if self.is_horizontal else self.position[0] + CAR_WIDTH):
for y in range(self.position[1],
self.position[1] + CAR_WIDTH if self.is_horizontal else self.position[1] + CAR_LENGTH):
tiles.append((x, y))
return tiles
def is_done(self):
"""
Determines if the car has reached a spawn area that is not its original spawn area.
:return: `True` iff. the car has reached another spawn area and can be removed from the map.
"""
x, y = self.position
if x <= -CAR_LENGTH \
and (self.spawn_position[0] > 0 or y != self.spawn_position[1]) \
and self.is_horizontal:
return True
elif x >= MAP_SIZE \
and (self.spawn_position[0] < MAP_SIZE or y != self.spawn_position[1]) \
and self.is_horizontal:
return True
elif y <= -CAR_LENGTH \
and (self.spawn_position[1] > 0 or x != self.spawn_position[0]) \
and not self.is_horizontal:
return True
elif y >= MAP_SIZE \
and (self.spawn_position[1] < MAP_SIZE or x != self.spawn_position[0]) \
and not self.is_horizontal:
return True
else:
return False
|
cec0813ca0fd3e4c623541014b9508b4f7af267b | prabyM/PassMan | /PassMan/db_handler.py | 448 | 3.59375 | 4 | import sqlite3
import os
file_present = os.path.isfile("credentials.db")
if file_present is False:
try:
open('credentials.db', 'w').close()
except Error as e:
print(e)
def create_connection(db_file):
""" create a database connection to a SQLite database """
try:
conn = sqlite3.connect(db_file)
print(sqlite3.version)
except Error as e:
print(e)
finally:
conn.close()
|
b39ee328950234e3ca4654f86a32cd0f4e41b849 | Bryan-20/t07_santamaria_baldera | /santamaria/codificadores_04.py | 233 | 3.5 | 4 | # iteracion decoficador 04
import os
msg=str(os.sys.argv[1])
for letra in msg:
if(letra == "P"):
print("Profesor")
if (letra == "F"):
print("Feliz")
if (letra == "N"):
print("Navidad")
#Fin_For
|
c66c83e5d5b08aa2a65fb8cccd93a35326f23c27 | Bryan-20/t07_santamaria_baldera | /santamaria/mientras03.py | 328 | 3.921875 | 4 | # Ejercicio nro 03
# Ingrese a1 y luego pedir a2, mientras a2 sea menor a a1
# Donde a1 es un numero para entero positivo
a1=1
numero_ivalido=((a1%2)!=0)
a2=0
while(numero_ivalido):
a1=int(input("Ingrese a1:"))
numero_ivalido=((a1%2)!=0)
while(a2<a1):
a2=int(input("Ingrese a2:"))
#Fi_While
print("A1=",a1,"A2=",a2)
|
ecd5aed47e007a597dd3ca6d1d755c3a4fb2099c | spontaneously5201314/Algorithms | /src/main/match/equal/Number.py | 449 | 3.71875 | 4 | def search(exp, nums):
if '_' not in exp or nums is None:
exps = exp.split('=')
if eval(exps[0]) == float(exps[1]):
print exps[0]+'='+exps[1]
return
else:
for num in nums:
e = exp.replace('_', num, 1)
ns = nums[:]
ns.remove(num)
search(e, ns)
if __name__ == '__main__':
exp = raw_input()
nums = raw_input().split(' ')
search(exp, nums) |
5097aa5c089e31d239b06bbd76e99942694cbdd7 | CBehan121/Todo-list | /Python_imperative/todo.py | 2,572 | 4.1875 | 4 | Input = "start"
wordString = "" #intializing my list
while(Input != "end"): # Start a while loop that ends when a certain inout is given
Input = input("\nChoose between [add], [delete], [show list], [end] or [show top]\n\n")
if Input == "add": # Check if the user wishes to add a new event/task to the list
checker = input("\nWould you Task or Event?\n") # Take the task/event input
if checker.lower() == "task":
words = input("Please enter a Date.\n") + " "
words += input("Please enter a Start time.\n") + " "
words += input("Please enter a Duration.\n") + " "
words += input("Please enter a list of members. \n")
wordString = wordString + words + "!" # Add the new task/event to the list. I use a ! to seperate each item.
elif checker.lower() == "event":
words = input("Please enter a Date, Start time and Location\n") + " "
words += input("Please enter a Start time. \n") + " "
words += input("Please enter a loaction. \n")
wordString = wordString + words + "!" # Add the new task/event to the list. I use a ! to seperate each item.
else:
print("you failed to enter a correct type.")
elif Input == "show top":
if wordString != "": # Enure there is something in your list already
i = 0
while wordString[i] != "!": # iterates until i hit a ! which means ive reached the end of an item
i += 1
print("\n\n" + wordString[:i] + "\n") # print the first item in the list
else:
print("\n\nYour list is empty.\n")
elif Input == "delete":
if wordString != "": #the try is put in place incase the string is empty.
i = 0
while wordString[i] != "!": # iterate until i reach the end of the first task/event
i += 1
wordString = wordString[i + 1:] #make my list equal from the end of the first item onwards
else:
print("\n\nYour list is already empty.\n")
elif Input == "show list":
if wordString != "":
fullList = "" # create a new instance of the list so i can append \n inbetween each entry.
i = 0 # Normal counter
j = 0 # holds the position when it finds a !
for letter in wordString:
if letter == "!":
fullList = fullList + wordString[j:i] + "\n" # appending each item to the new list seperated by \n
j = i + 1 # this needs a + 1 so it ignores the actual !
i = i + 1
print("\n\n" + fullList)
else:
print("\n\nYour list is empty\n")
elif Input == "end":
print("exiting program")
else:
print("\nYour input wasnt correct please try again\n") # This is just in place to catch any incorrect inputs you may enter. |
813e9e90d06cb05c93b27a825ac14e5e96abcc9b | bparker12/code_wars_practice | /squre_every_digit.py | 520 | 4.3125 | 4 | # Welcome. In this kata, you are asked to square every digit of a number.
# For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
# Note: The function accepts an integer and returns an integer
def square_digits(num):
dig = [int(x) **2 for x in str(num)]
dig = int("".join([str(x) for x in dig]))
print(dig)
square_digits(9119)
# more efficient
def square_digits1(num):
print(int(''.join(str(int(d)**2) for d in str(num))))
square_digits1(8118) |
312b662283a4f358cfaeec5bfd0e7793bf03816d | unisociesc/Projeto-Programar | /Operadores/Exercícios Aritméticos.py | 994 | 4.21875 | 4 | #Exercícios Operadores Aritméticos
# 1- Faça um Programa que peça dois números e imprima a soma.
print('Soma de valores...\n')
num1 = float(input('Digite um número: '))
num2 = float(input('Digite outro número: '))
soma = num1 + num2
#%s = string
#%d = inteiros
#%f = floats
#%g = genéricos
print('O resultado da soma de', num1,'+', num2,'é', soma)
print('O resultado da soma de %g + %g é %g' % (num1,num2,soma))
# 2- Faça um Programa que peça as 4 notas bimestrais e mostre a média.
n1 = float(input('Digite a nota 1: '))
n2 = float(input('Digite a nota 2: '))
n3 = float(input('Digite a nota 3: '))
n4 = float(input('Digite a nota 4: '))
media = n1 + n2 + n3 + n4 / 4
print('A média do aluno foi %g' % media)
# 3- Faça um Programa que converta metros para centímetros.
metros = float(input('Digite o valor em metros que queira converter: '))
convertido = metros * 100
print('O valor convertido de %g metros para centímetros é %g cm' % (metros, convertido))
|
95f6426db6745fd9196069fd507dd155259bf220 | unisociesc/Projeto-Programar | /Operadores/Logicos.py | 222 | 3.90625 | 4 | #Operadores Lógicos
num1 = int(10)
num2 = int(20)
num3 = int(30)
print(num1<num2 and num2<num3) #Operador and (e)
print(num1>num3 or num3>num2) #Operador or (ou)
print(not(num1<num2 and num2<num3)) #Operador not (não)
|
577a3f912959c0d5ef4e9cf02e0f70af5ac04496 | yusinzxc/python-basics | /OOP-INHERIT/test.py | 102 | 3.71875 | 4 |
test = []
for i in range(3):
p = i
test.append(p)
for i in test:
print(i)
print(test)
|
eeea25c958866630ec58fc4764cc91e122cfd865 | yusinzxc/python-basics | /OOP-INHERIT/OOP-inherit.py | 925 | 3.828125 | 4 | class Species:
def __init__(self,called,name,gender):
self.called = called
self.name = name
self.gender = gender
print("Those are " + self.called)
def introduce(self):
if self.called == "Human" or self.called == "human":
if self.gender == "Male" or self.gender == "male":
print("Him name is " + self.name)
else:
print("Her name is " + self.name)
else:
print("It is a " + self.name)
class Human(Species):
def __init__(self,called,name,gender):
super().__init__(called,name,gender)
def fullProfile(self):
super().introduce()
print(True)
hOne = Human("Human","Yujin","Female")
hOne.fullProfile()
class Animals(Species):
def __init__(self,called,name,gender):
super().__init__(called,name,gender)
aOne = Animals("Animals","Dog","Male")
aOne.introduce()
|
083bbb6fd84769a0911f5441713907ef95c3e4e4 | BrianArne/Schedule | /Schedule.py | 5,275 | 3.625 | 4 | import random
from enum import Enum
from random import randint
'''
MACROS
'''
# Total CPU quantums
C_TIME = 0
#Used to generate task IDs
CURR_ID = 0
# Total GPU quantums
G_TIME = 0
# Total time when GPU and CPU were running calculations
SAVED_TIME = 0
# Size that a process can be <= to be passed to CPU
SMALL_ENOUGH = 1
# Test Size
TEST_SIZE = 200000
# CPU and GPU queues
cpu_queue = []
gpu_queue = []
###################
### ENUMS ###
###################
'''
Enum representing job data sizes being passed to GPU or CPU processing
Currently not really being used, but ._size could be replaced with enums
'''
class JobSize(Enum):
HALF_SMALL = 0
SMALL = 1
MEDIUM =2
LARGE = 3
XLARGE = 4
XXLarge = 5
'''
Overwritting subtraction method to subtract int from value
'''
def __sub__(self, y):
self.value = self.value - 1
# End __sub__();
# End JobSize Enum
###################
### CLASS ###
###################
'''
Container Class represent a task. Holds ID and JobSize
'''
class Task:
'''
Initializes a Task with a size and a num_Id
'''
def __init__(self, num_id, job_size):
self._size = job_size
self._num_id = num_id
self._allocated = 2
# End __init__();
def __str__(self):
return "Job Size: " + str(self._size) \
+ " Num Id: " + str(self._num_id) \
+ " Allocation: " + str(self._allocated)
# End __str__();
# End Task Class
###################
### METHODS ###
###################
'''
Takes in a job and puts it in GPU or OS Queue
'''
def assign_two_queue(task):
if(task._size is JobSize.SMALL):
cpu_queue.append(task)
else:
gpu_queue.append(task)
# End assign_two_queue();
'''
Takes in a job and puts it in GPU queue
Used to for compring algorithm with and without CPU
'''
def assign_one_queue(task):
gpu_queue.append(task)
# End assign_one_queue();
'''
Returns bool. Checks if cpu can take another task
'''
def check_cpu_open():
global cpu_queue
if len(cpu_queue) == 0:
return True
# End check_cpu_open();
'''
Returns bool. Checks if gpu can take another task
'''
def check_gpu_open():
global gpu_queue
if len(gpu_queue) == 0:
return True
# End check_gpu_open();
'''
Looks at each process and "processes them"
Adds quantum time to overall time
'''
def decrement_task_times():
global gpu_queue; global cpu_queue; global G_TIME; global C_TIME; global SAVED_TIME;
if(len(gpu_queue) != 0 and len(cpu_queue) != 0):
saved = True
else:
saved = False
# Processes one round of GPU
if(len(gpu_queue) != 0):
if (gpu_queue[0]._size <= 2):
task = gpu_queue.pop(0)
if(task._size == 1):
G_TIME += 1
else:
G_TIME += 2
else:
gpu_queue[0]._size -= 2#gpu_queue[0]._size - 2
G_TIME +=2
# Processes one round of CPU
if(len(cpu_queue) != 0):
if(cpu_queue[0]._size == 0):
cpu_queue.pop(0)
if(saved):
SAVED_TIME += 1
else:
C_TIME += 1
else:
cpu_queue[0]._size -= 1#cpu_queue[0]._size - 1
C_TIME += 1
return
# End decrement_task_times();
'''
Creates 100 random Jobs
'''
def generate_queue():
queue = []
for i in range(0,TEST_SIZE):
job_size = randint(1,5)
global CURR_ID
new_task = Task(CURR_ID, job_size)
queue.append(new_task)
CURR_ID += 1
return queue
# End generate_queue();
'''
Looks at next task and assigns processor depending on JobSize and Allocated Time
While also implementing a GERM scheduling policy
'''
def GERM_process_task_variant(task_queue):
global SMALL_ENOUGH
if (task_queue[0]._size <= SMALL_ENOUGH):
if (check_cpu_open()):
global cpu_queue
cpu_queue.append(task_queue.pop(0))
elif (check_gpu_open()):
global gpu_queue
gpu_queue.append(task_queue.pop(0))
if (task_queue[0]._size > task_queue[0]._allocated):
task_queue[0]._allocated += 2
task = task_queue.pop(0)
task_queue.append(task)
return
else:
if(check_gpu_open()):
gpu_queue.append(task_queue.pop(0))
return
# End process_task();
'''
Print both queues to the console
'''
def print_queues():
print("*****GPU Queue*****")
global gpu_queue
for task in gpu_queue:
print(str(task))
print("*****CPU Queue*****")
global cpu_queue
for task in cpu_queue:
print(str(task))
# End print_queues();
###################
### MAIN ####
###################
'''
Main. Run a Process
'''
def main():
random.seed(1)
#Our Two Processing Avenues
cpu_queue = []
gpu_queue = []
task_queue = generate_queue()
# This will be main method
# while len(task_queue) > 0:
while len(task_queue) != 0:
GERM_process_task_variant(task_queue)
decrement_task_times()
print("Gpu processing time: ", G_TIME)
print("Cpu processing time: ", C_TIME)
print("Saved time: ", SAVED_TIME)
print("Total CPU Jobs: ", (C_TIME + SAVED_TIME) / 2)
# Run main
main()
|
28fe55b8782822236607c1c4fbce3524272b06b3 | ayellis/cerealrobot | /src/order2.py | 3,541 | 3.5625 | 4 | class Order:
def __init__(self, waiter):
self.waiter = waiter
self.items = {} #map MenuItem -> quantity
self.picked_up = {} #map MenuItem -> quantity
self.served_up = {} #map MenuItem -> quantity
def addItem(self, menuItem, quantity):
if (self.items.has_key(menuItem)):
quantity += self.items[menuItem]
self.items[menuItem] = quantity
def getTable(self):
return self.table
def getWaiter(self):
return self.waiter
def getItems(self):
return self.items
def getTotal(self):
total = 0
for menuItem, quantity in self.items.iteritems():
total += quantity * menuItem.getPrice()
return total
def pickedUp(self, item):
if (item in self.picked_up):
self.picked_up[item] = self.picked_up[item] + 1
else:
self.picked_up[item] = 1
def served(self, item):
if (item in self.served_up):
self.served_up[item] = self.served_up[item] + 1
else:
self.served_up[item] = 1
def checkPickUps(self):
for item, quantity in self.items.iteritems():
if(self.picked_up.has_key(item)):
if quantity != self.picked_up[item]:
raise Exception("Order for " + str(quantity) + " only picked up " + str(self.picked_up[item]))
else:
raise Exception("Order for " + str(quantity) + " but never picked up any")
def checkServed(self):
for item, quantity in self.items.iteritems():
if(self.served_up.has_key(item)):
if quantity != self.served_up[item]:
raise Exception("Order for " + str(quantity) + " only picked up " + str(self.served_up[item]))
else:
raise Exception("Order for " + str(quantity) + " but never picked up any")
def show(self):
print "\n*****"
print "Treat is ready for human consumption thanks to", self.waiter
for menuItem, quantity in self.items.iteritems():
print ("%-3s" % str(quantity)) + "\t@\t" + ("%-40s" % menuItem.getName())
print "Order Total: $", self.getTotal()
print "*****\n"
def showForBill(self):
print "Food made available for human consumption by", self.waiter
for menuItem, quantity in self.items.iteritems():
print ("%-3s" % str(quantity)) + "\t" + ("%-40s" % menuItem.getName()) + " @ " + ("%-6s" % ("$"+ str(menuItem.getPrice()))) + " : " + "$" + str(menuItem.getPrice() * quantity)
def merge(self,order):
self.waiter = order.waiter
for menuItem, quantity in order.items.iteritems():
if(self.items.has_key(menuItem)):
self.items[menuItem] = self.items[menuItem] + quantity
else:
self.items[menuItem] = quantity
for menuItem, quantity in order.picked_up.iteritems():
if(self.picked_up.has_key(menuItem)):
self.picked_up[menuItem] = self.picked_up[menuItem] + quantity
else:
self.picked_up[menuItem] = quantity
for menuItem, quantity in order.served_up.iteritems():
if(self.served_up.has_key(menuItem)):
self.served_up[menuItem] = self.served_up[menuItem] + quantity
else:
self.served_up[menuItem] = quantity |
f9b9cc936f7d1596a666d0b0586e05972e94cefa | jamiekiim/ICS4U1c-2018-19 | /Working/practice_point.py | 831 | 4.375 | 4 | class Point():
def __init__(self, px, py):
"""
Create an instance of a Point
:param px: x coordinate value
:param py: y coordinate value
"""
self.x = px
self.y = py
def get_distance(self, other_point):
"""
Compute the distance between the current obejct and another Point object
:param other_point: Point object to find the distance to
:return: float
"""
distance = math.sqrt((other_point.x - self.x)**2 + (other_point.y - self.y)**2)
return distance
def main():
"""
Program demonstrating the creation of Point instances and calling class methods.
"""
p1 = Point(5, 10)
p2 = Point(3, 4)
dist = p1.get_distance(p2)
print("The distance between the points is" + str(dist))
main()
|
2274eb9acc9808d5e0be1a7afe09666d9e4be977 | G-development/Python | /Python exercises/programmareInPython/seiUnaVocale.py | 179 | 3.875 | 4 | def seiUnaVocale():
vocali = "aeiou"
x = input("Inserisci un carattere:")
if x in vocali:
print(x + " è una vocale")
else:
print(x + " non lo è") |
174bed02a88e9ab467a20c27aab7eb0d75a5550d | G-development/Python | /Python exercises/programmareInPython/maggioreFraTutti.py | 209 | 3.734375 | 4 | def maggioreFraTutti(lista):
maggiore = 0
for numero in lista:
if numero > maggiore: maggiore = numero
print("Il maggiore è: " + str(maggiore))
#print("Il maggiore è: " + max(lista)) |
833b7f1186fa4bd1e46ef2035cadf235012f994a | G-development/Python | /Python exercises/Py ONE/GuessTheNumber.py | 385 | 3.984375 | 4 | import random
num = random.randint(0,20)
user = int(input("\nGuess the number between 0-20: "))
moves = 0
while user != num:
if user<num:
print("The number is bigger!")
user = int(input("Retry: "))
moves += 1
else:
print("The number is smaller!")
user = int(input("Retry: "))
moves += 1
print("Found it in:", moves, "moves.") |
e882c2b5a90168e73b14c24941cd50e8076ce947 | shalinichaturvedi20/decsonary | /question7.py | 818 | 3.609375 | 4 | # dic=[{"first":"1"}, {"second": "2"}, {"third": "1"}, {"four": "5"}, {"five":"5"}, {"six":"9"},{"seven":"7"}]
# c={}
# for i in dic:
# c.update(i)
# a=[]
# for i in c.values():
# if i not in a:
# a.append(i)
# print(a)
# def a(name):
# i=1
# num=""
# while i<=len(name):
# num=num+name[-i]
# i=i+1
# print(num)
# a("shalini chaturvedi")
def a(name):
i=1
num=""
while i<=len(name):
num=num+name[-i]
i=i+1
print(num)
a("shalini chaturvedi")
# num=[1,2,3,[4,5],6,7,[8,9],1,2,3,[4,5]]
# i=0
# sum=0
# while i<len(a):
# if type(a[i]==type(a)):
# j=0
# while j<len(a[i]):
# sum=sum+a[i][j]
# j=j+1
# else:
# sum=sum+a[i]
# i=i+1
# print(sum)
|
838dd102460259673e75338915bc80ed5f3dac59 | shalinichaturvedi20/decsonary | /question8.py | 257 | 3.625 | 4 | i=1
student=[]
marks=[]
while i<=10:
user=input("enter the student name")
student.append(user)
mark=int(input("enter the student marks"))
marks.append(mark)
i+=1
d=dict()
n=marks[0]
for i in student:
d[i]=n
n+=1
print(d)
|
4d6fbe8ee7aa616ebefb83152fc7aa1b2881b32f | Gregog/leetcode | /Python/0002.Add_two_numbers.py | 658 | 3.765625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
res = ListNode(0)
result_tail = res
buf = 0
while l1 or l2 or buf:
val1 = (l1.val if l1 else 0)
val2 = (l2.val if l2 else 0)
buf, r = divmod(val1 + val2 + buf, 10)
result_tail.next = ListNode(r)
result_tail = result_tail.next
l1 = (l1.next if l1 else None)
l2 = (l2.next if l2 else None)
return res.next
|
b68d03bff0977ea545db470ae975249fee1483dd | mwyciszczak/Laby- | /Lista_Zadań_Zaliczeniowa_Semestr_Zimowy/lz_zad3.py | 1,560 | 3.6875 | 4 | pytania = ["Czy python to język programowania?",
"Czy każdy komputer posiada zasilacz?",
"Czy 64 GB ramu w komputerze do dużo dla przeciętnego użytkownika?",
"Czy pierwszym językiem programowania był Polski język LECH?",
"Czy umiesz obsłużyć przeglądarkę internetową?(tak jest dobra i zła odpowiedź)",
"Czy github jest potrzebny programistom?",
"Czy 1 GB to więcej niż 1 Gb?",
"Czy posiadanie ciemnego motywu w swoim IDE jest obowiązkowe?",
"Czy każdy programista powinen mieć kota?",
"Czy Windows jest lepszy od Linuxa?"]
odpowiedzi = [True, True, True, False, True, True, True, True, True, True, True]
def quiz():
punkty = 0
for x in range(len(pytania)):
print(pytania[x])
while True:
wybor = input('Tak - "y" Nie - "n"')
if wybor == "y" or wybor == "Y":
odpowiedz = True
break
elif wybor == "n" or wybor == "N":
odpowiedz = False
break
else:
print('Proszę użyj liter "y" i "n"')
if odpowiedz == odpowiedzi[x]:
punkty += 1
print("Twój wynik to {} na {} punktów.".format(punkty, len(pytania)))
print("Witaj w quzie wiedzy informatycznej")
print("""
1.Quiz
2.Wyjście
""")
while True:
wybor_menu = input("Proszę wybierz opcję (1, 2): ")
if wybor_menu == "1":
quiz()
break
elif wybor_menu == "2":
exit()
else:
pass |
7512f2edb142237b941cc1290326052abf0dbce9 | mwyciszczak/Laby- | /Lab_2/lab2_zad8.py | 379 | 3.6875 | 4 | a = int(input("Podaj pierwszą przyprostokątną: "))
b = int(input("Podaj drugą przyprostokątną: "))
c = int(input("Podaj przeciwprostokątną: "))
a = a**2
b = b**2
wynik = a + b
if wynik == c**2:
print("Z podanych długości boków można utworzyć trójkąt prostokątny")
else:
print("Z podanych długości boków nie można utworzyć trójkąt prostokątny")
|
49c4b437462f6df2c325d898a9bd27c0c7ad1a6e | mwyciszczak/Laby- | /Lab_8/lab8_zad4.py | 415 | 3.578125 | 4 | dict = {}
ile = int(input("Podaj ile maili chcesz dopisać do słownika"))
plik = open("adresy.txt", "wt")
for x in range(ile):
imie = input("Podaj imię użytkownika: ")
mail = input("Podaj mail użytkownika: ")
dict[imie] = mail
dopliku = str(dict)
plik.write(dopliku)
#w ten sposób możemy przetrzymywać adresy mailowe w pliku txt i wykorzystać je w innym skrypcie który by te maile wysyłał |
95c9f96ee8fc963e301a828d5ca0143465c7dd46 | mwyciszczak/Laby- | /Lab_10/lab10_zad1.py | 1,607 | 3.859375 | 4 | a = '''Magia jest w opinii niektórych ucieleśnieniem Chaosu. Jest kluczem zdolnym otworzyć zakazane drzwi. Drzwi,
za którymi czai się koszmar, zgroza i niewyobrażalna okropność, za którymi czyhają wrogie, destrukcyjne
siły, moce czystego zła, mogące unicestwić nie tylko tego, kto drzwi te uchyli, ale i cały świat. A ponieważ
nie brakuje takich, którzy przy owych drzwiach manipulują, kiedyś ktoś popełni błąd, a wówczas zagłada świata
będzie przesądzona i nieuchronna. Magia jest zatem zemstą i orężem Chaosu. To, że po Koniunkcji Sfer ludzie
nauczyli posługiwać się magią, jest przekleństwem i zgubą świata. Zgubą ludzkości. I tak jest. Ci, którzy
uważają magię za Chaos, nie mylą się.'''
(print(a[:53].lower()))
(print(a[:53].swapcase()))
(print(a[107:134].capitalize()))
x = a[:53].replace("Magia","Wiedźmini")
b = x.replace("jest", "są")
c = b.replace("Chaosu", "zła")
print(c)
print(a[:99].lstrip("M"))
print(a[:99].rstrip("."))
lista = list(reversed(a[:5]))
print(lista)
ilość_a = lista.count("a")
ilość_i = lista.count("i")
print(f"W słowie magia są {ilość_a} litery 'a' i {ilość_i} litera 'i'")
słowo = a.find("Koniunkcji")
litera = a.find("d")
print(f"Słowo 'Koniunkcji' zaczyna się na {słowo} miejscu")
print(f"Pierwsza litera 'd' znajduje się na {litera} miejscu")
print(a.isalnum())
print(a[:5].isalnum())
print("----------------------")
print(a.startswith("Magia"))
print(a.startswith("przekleństwem"))
print("----------------------")
print(a.endswith("."))
print(a.endswith("się")) |
104c27ce9540454e75d58a52050a6d9043eacd44 | mwyciszczak/Laby- | /Lab_7/lab7_zad1.py | 162 | 4.03125 | 4 | tuple = (1, 2, 3, "a", "b", "c")
print(len(tuple))
print(id(tuple))
tuple = tuple + (2, "d")
print(tuple)
print(id(tuple))
tuple = list(tuple)
print(id(tuple))
|
c31bc4734ab732f235977dd33ef836dc9354da80 | mwyciszczak/Laby- | /Lab_4/lab4_zad10.py | 205 | 3.578125 | 4 | ostatnia = 0
sum = 0
while True:
podana = float(input("Podaj liczbę: "))
sum = sum + podana
if podana == ostatnia:
break
ostatnia = podana
print("Koniec, suma to {}".format(sum)) |
2ecd6d99e8d58bfbe5fc038e6b2d06f6827c0bd1 | mwyciszczak/Laby- | /Lab_6/lab6_zad6.py | 364 | 3.625 | 4 | import random
n = int(input("Podaj długość ciągu: "))
y = int(input("Podaj dolną granicę ciągu: "))
z = int(input("Podaj górną granicę ciągu: "))
tab = []
unikalne = []
for x in range(n):
tab.append(random.randint(y, z))
tab = list(dict.fromkeys(tab))
print("Unikalne elementy listy to {}, a jej długość to {}".format(sorted(tab), len(tab))) |
1cfefffa5f42d2b0cef526ee8e7b577507fd639f | mwyciszczak/Laby- | /Lab_2/lab2_zad5.py | 235 | 3.796875 | 4 | promile = float(input("Podaj ilość promili: "))
if promile >= 0.2 and promile <= 0.5:
print('Stan „wskazujący na spożycie alkoholu”.')
elif promile > 0.5:
print("Stan nietrzeźwości.")
else:
print("Trzeźwość.") |
46ad1ff1c606120fd5f869bda71d1896f229d7f3 | mwyciszczak/Laby- | /Lab_2/lab2_zad4.py | 237 | 3.796875 | 4 | l = float(input("Podaj liczbę: "))
if l == 0:
print("Liczba to 0.")
elif l > 0:
print("Liczba jest dodatnia.")
elif l < 0:
print("Liczba jest ujemna.")
if l % 2 != 0:
print("Liczba jest podzielna przez dwa z resztą.") |
b2efdc0cb8568a3a29b3d1ed5874f55e165dc201 | rakieu/python | /multa para excesso de peso.py | 280 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 11 16:09:02 2020
@author: raque
"""
a = int(input('a: '))
b = int(input('b: '))
c = int(input('c: '))
if a >= b and a >= c:
print (f'Maior: {a}')
elif b >= c:
print (f'Maior: {b}')
else:
print (f'Maior: {c: }')
input () |
13cfdb9005da7b58f23d631ee8617b37ef71aedc | rakieu/python | /imprimir de 1 ate um numero lido_2.py | 84 | 3.890625 | 4 | x = 1
fim = int(input('Fim: '))
while x <= fim:
print (x)
x = x + 2
input () |
9ed4b89fd12fd80ec4674639d9da1aff771b5f26 | rakieu/python | /mac_while_cont_potencia_2.py | 533 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
# ------
# este programa recebe um inteiro nao negativo n e calcula o fatorial de n
#definição de fatorial de n, denotado por n!
#0! = 1
# n! = n * (n-1)! = n (n-1) * (n-2) * ... * 2 * 1,
# ------
def main ():
n = int(input("Digit um número inteiro não-negativo: "))
fat = 1
k = 2
while k <= n:
fat = fat * k
k = k + 1
print ("\n O fatorial de", n, "é igual a", fat)
print ()
# ------
main () |
318a80ce77b542abc821fa8ff2983b0760da2838 | aaronstaclara/testcodes | /palindrome checker.py | 538 | 4.25 | 4 | #this code will check if the input code is a palindrome
print('This is a palindrome checker!')
print('')
txt=input('Input word to check: ')
def palindrome_check(txt):
i=0
j=len(txt)-1
counter=0
n=int(len(txt)/2)
for iter in range(1,n+1):
if txt[i]==txt[j]:
counter=counter+1
i=i+iter
j=j-iter
if counter==n:
disp="Yes! It is a palindrome!"
else:
disp='No! It is not a palindrome!'
return print(disp)
palindrome_check(txt)
|
f0754dfa5777cd2e69afa26e2b73b216d0ff5313 | sb1994/python_basics | /vanilla_python/lists.py | 346 | 4.375 | 4 | #creating lists
#string list
friends = ["John","Paul","Mick","Dylan","Jim","Sara"]
print(friends)
#accessing the index
print(friends[2])
#will take the selected element and everyhing after that
print(friends[2:])
#can select a range for the index
print(friends[2:4])
#can change the value at specified index
friends[0] = "Toby"
print(friends) |
4439d7172aa52d5be811fa29a2f621ea92ac1f8d | Vincetroid/learning-python | /rest_apis_with_flask_and_python/advanced-set-operations.py | 392 | 3.984375 | 4 | #difference
friends = {"Bob", "Anne", "Rolf"}
abroad = {"Bob", "Anne"}
local_friends = friends.difference(abroad)
print(local_friends)
#union
two_fruits = {"Orange", "Tangerine"}
one_fruit = {"Apple"}
shake = two_fruits.union(one_fruit)
print(shake)
#intersection
art = {"Bob", "Jen", "Rolf", "Charlie"}
science = {"Bob", "Jen", "Adam", "Anne"}
both = art.intersection(science)
print(both) |
d3c9b4e1093dcd93ee0bd9fb147d4bf97d8f1e95 | fernandosvicente/cursoemvideo-python | /PycharmProjects/CursoemVideo/aula06a.py | 773 | 3.953125 | 4 | n1 = int(input('digite um valor :'))
n2 = int(input('digite outro :'))
s = n1 + n2
# print('a soma entre', n1, ' e ',n2, ' vale ', s)
print('a soma entre {} e {} vale {}'.format(n1, n2, s))
n3 = float(input('digite um valor :'))
print(n3)
print(type(n3))
n4 = bool(input('digite um valor : '))
print(n4)
n5 = input('digite algo :')
print(n5.isnumeric())
n6 = input('digite algo : ')
print(n6.isalpha())
n7 = input('digite algo :')
print('o tipo primitivo desse valor é ', type(n7))
print('só tem espaços?', n7.isspace())
print('é um numero?', n7.isnumeric())
print('é alfabético?', n7.isalpha())
print('é alfanumérico?', n7.isalpha())
print('esta em maiuscula?', n7.isupper())
print('esta em minuscula', n7.islower())
print('esta capitalizada?', n7.istitle()) |
3a4de5aeaec57f0e58c8a8726b66289827c98da2 | fernandosvicente/cursoemvideo-python | /PycharmProjects/CursoemVideo/ex10.py | 3,980 | 3.765625 | 4 | #from time import sleep
#for cont in range(10, -1, -1):
# print(cont)
# sleep(0.5)
#for par in range(1, 51):
# # outra forma de escreve: print(par)
# if par % 2 == 0:
# print(' {} '.format(par), end='')
# sleep(0.2)
#print('acabou')
#for n in range(2, 51, 2):
# # outra forma de escreve: print(par)
# print(' {} '.format(n), end='')
# sleep(0.2)
#print('acabou')
#soma = 0
#cont = 0
#for c in range(1, 501, 2):
# if c % 3 == 0:
# # print(c, end=' '), para extrair os numeros
# cont = cont + 1 # outra sintaxe cont += 1
# soma = soma + c # outra sintaxe soma += c
#print('a soma dos numeros e {} e contamos {} numeros'.format(soma, cont))
#num = int(input('digite o numero para ver sua tabuada: '))
#for c in range(1, 11):
# print('{} x {:2} = {}'.format(num, c, num * c))
#soma = 0
#cont = 0
#for c in range(1, 7):
# num = int(input(' digite o {}º valor : '.format(c)))
# if num % 2 == 0:
# soma = soma + num # outra forma sintaxe, soma += num
# cont = cont + 1 # outra forma sintaxe, cont += 1
#print('voce informou {} numeros pares e a soma foi {}'.format(cont, soma))
#primeiro = int(input('primeiro termo '))
#razao = int(input('razao '))
#ultimo = int(input('ultimo termo'))
#ultimo = primeiro + (ultimo - 1)* razao
#for c in range(primeiro, ultimo + razao, razao):
# print('{} '.format(c), end=' -> ')
#print('acabaou')
#num = int(input('digite um numero :'))
#tot = 0
#for c in range(1, num + 1):
# if num % c == 0:
# print('\033[33m', end=' ')
# tot = tot + 1
# else:
# print('\033[31m', end=' ')
# print('{} '.format(c), end='')
#print(' \n\033[mo numero {}, foi divisivel {} vezes'.format(num, tot))
#if tot == 2:
# print(' E numero primo')
#else:
# print('E numero nao primo')
#frase = str(input('digite a frase ')).strip().upper()
#palavras = frase.split()
#junto = ''.join(palavras)
#print('vc digitou a frase : {} '.format(junto))
# forma 01 de resolver
#inverso = ''
#for letra in range(len(junto) -1, -1, -1):
# inverso = inverso + junto[letra]
# forma 02 de resolver
#inverso = junto[::-1]
#print('o inverso de {} e {} '.format(junto, inverso))
#if inverso == junto :
# print('palidromo')
#else:
# print('nao e palidromo')
#from datetime import date
#atual = date.today().year
#totmaior = 0
#totmenor = 0
#for pess in range(1, 8):
# nasc = int(input('em que ano a {}ª pessoa nasceu? '.format(pess)))
# idade = atual - nasc
# if idade >= 21:
# totmaior = totmaior + 1
# else:
# totmenor = totmenor + 1
#print('ao todo tivemos {} pessoas maiores de idade '.format(totmaior))
#print('ao todo tivemos {} pessoas menores de idade '.format(totmenor))
#maior = 0
#menor = 0
#for p in range(1, 6):
# peso = float(input('peso da {}ª pessoa: '.format(p)))
# if p == 1:
# maior = peso
# menor = peso
# else:
# if peso > maior:
# maior = peso
# if peso < menor:
# menor = peso
#print('o maior peso lido foi: {} '.format(maior))
#print('o menor peso lido foi: {} '.format(menor))
somaidade = 0
mediaidade = 0
maioridadehomem = 0
nomevelho = ''
totmulher20 = 0
for p in range (1, 5):
print('-------{}ª PESSOA ------'.format(p))
nome = str(input('nome: ')).strip()
idade = int(input('idade: '))
sexo = str(input('sexo [M/F]: ')).strip()
somaidade = somaidade + idade # ou somaidade += idade
if p == 1 and sexo in 'Mm':
maioridadehomem = idade
nomevelho = nome
if sexo in 'Mn' and idade > maioridadehomem:
maioridadehomem = idade
nomevelho = nome
if sexo in 'Ff' and idade < 20:
totmulher20 = totmulher20 + 1
mediaidade = somaidade / 4
print(' a media de idade do grupo e {} anos'.format(mediaidade))
print(' o homem mais velho tem {} anos e se chama {}'.format(maioridadehomem,nomevelho))
print(' ao todo sao {} mulheres menores de 20 anos'.format(totmulher20)) |
cf88677d861926a33f12434740118993107dfbed | fernandosvicente/cursoemvideo-python | /PycharmProjects/CursoemVideo/ex07a.py | 2,054 | 4.0625 | 4 | n = int(input('digite um numero: '))
a = n - 1
s = n + 1
d = n*2
t = n*3
r = n**(1/2)
q = n**2
c = n**3
print('analisando o valor {}, seu antecessor é {} e o sucessor é {}'.format(n,a,s))
print('o dobro de {} é : {}, o triplo de {} é : {} \n a raiz quadrada de {} é : {:.2f}'.format(n,d,n,t,n,r), end="")
print('o quadrado de {} é de: {}, o cubo de {} é de: {}'.format(n,q,n,c))
n1 = int(input('digite um valor: '))
print('analisando o valor {}, seu antecessor é {} e seu sucessor é {}'.format(n1,(n1-1),(n1+1)))
'ordem precedencia (), **, * / // %, + -'\
' + soma, - subtração, * multiplicação, / divisao, ** exponenciaçõ, //divisor inteiro, % resto inteiro'
'para quebrar pagina usar (\n)e para juntar usar (, end="")'
n1 = float(input('primeira nota do aluno: '))
n2 = float(input('segunda nota do aluno: '))
m = (n1 + n2)/2
print('a média entre {:.1f} e {:.1f} é igual a {:.1f}'.format(n1, n2, m))
medida = float(input('uma distância em metros: '))
'km hm dam m dm cm mm'
dm = medida*10
cm = medida*100
mm = medida*1000
dam = medida/10
hm = medida/100
km = medida/1000
print('a medida de {}m corresponde a {:.0f}dm , {:.0f}cm , {:.0f}mm'.format(medida, dm, cm, mm))
print('a medida de {}m corresponde a {}dam , {}hm , {}km'.format(medida, dam, hm, km))
num= int(input('digite um numero para ver sua tabuada: '))
print('-'*14)
print('{} x {:2} = {}'.format(num, 1, num*1))
print('{} x {:2} = {}'.format(num, 2, num*2))
print('-'*14)
real = float(input('digite o valor que vc tem na carteira? R$'))
dolar = real / 3.27
print('com R${:.2f} vc pode comprar U$${:.2f}'. format(real, dolar))
print('-'*20)
print('orcamento para pintar parede')
print('ponto importante: 01 litro de tinta para cada 02 m²')
c = float(input('digite a medida do comprimento da parede em metros: '))
alt = float(input('digite a medida da altura da parede em metros: '))
r = float(input('digite a taxa de rendimento para tinta: '))
t = (c * alt)/r
print('as medidas da parede são: {} m e {} m , vc irá usar no total {} l de tinta'.format(c, alt, t))
|
730e51e2fcb0b354cadf6b529593ef07d03c19d1 | vaziridev/euler | /009.py | 577 | 3.75 | 4 | #ProjectEuler: Problem 9
#Find the Pythagorean triplet for which a + b + c = 1000. Return product abc.
import time
def main():
start = time.time()
result = findProduct()
elapsed = time.time() - start
print("Product %s found in %s seconds" % (result, elapsed))
def findProduct():
a = 1
b = 2
while True:
c = 1000 - a - b
if c <= b:
a += 1
b = a + 1
continue
elif c*c == a*a + b*b:
product = a*b*c
break
else:
b += 1
return product
main()
|
e32b25c89cbbf63ecad715edf196de0daa994e3b | mullerpeter/authorstyle | /authorstyle/preprocessing/util.py | 1,300 | 3.71875 | 4 | from nltk.corpus import stopwords as nltk_stopwords
from nltk.tokenize import RegexpTokenizer
from nltk.stem import PorterStemmer
def make_tokens_alphabetic(text):
"""
Remove all non alphabetic tokens
:type text: str
:param text: The text
:rtype List of str
:returns List of alphabetic tokens
"""
tokenizer = RegexpTokenizer(r'\w+')
tokens = tokenizer.tokenize(text.lower()) # This step is needed to prevent hyphenate words from
# being filtered out
return [t for t in tokens if t.isalpha()]
def remove_stopwords(tokens, stopwords=nltk_stopwords.words('english')):
"""
Removes all stopwords from the document tokens
:type tokens: list of str
:param tokens: List of tokens
:type stopwords: list of str
:param stopwords: List of stopwords to be removed from the document tokens. (Default: Stopword List from nltk)
:rtype List of str
:returns List of tokens without stopwords
"""
return [t for t in tokens if t not in stopwords]
def stem_tokens(tokens):
"""
Stem all tokens in List
:type tokens: list of str
:param tokens: List of tokens
:rtype List of str
:returns List of stemmed tokens
"""
porter_stemmer = PorterStemmer()
return [porter_stemmer.stem(t) for t in tokens]
|
c1a9da5613f1e80447c73dbf34cbb2f3d9d7cd9c | manavsinghcs18/The-perfect-guess-Game | /The Purfect Guess.py | 690 | 3.90625 | 4 | import random
randNumber=random.randint(1,100)
userGuess=None
guesses=0
while (userGuess != randNumber):
userGuess=int(input("Enter your guess: "))
guesses+=1
if userGuess==randNumber:
print("You guessed it Right!")
else:
if(userGuess>randNumber):
print("You guessed it wrong! Enter a smaller number")
else:
print("You guessed it wrong! Enter a larger number")
print(f"Your gussed number in {guesses} guesses")
with open ("hiscore.txt","r") as f:
hiscore=int(f.read())
if(guesses<hiscore):
print("YOu have just broken the highscore!")
with open ("hiscore.txt","w") as f:
f.write(str(guesses))
|
6b71f866ea703c3ab8779cd1aa9032a704e63284 | AlexDharmaratne/CSC-part-2 | /main.py | 6,457 | 3.53125 | 4 |
from tkinter import *
import random
global questions_answers
names_list = []
asked =[]
score =0
question_answers = {
1: ["What must you do when you see blue and red flashing light behind you?",'Speed up to get out the way','Slow down and drive carefully','Slow down and stop','Drive on as usual','Slow down and drive',3],
2: ["You may stop on a motorway only",'if there is an emergency','To let down or pick up passengers','To make a U-turn','To stop and take a photo','If there is an emergency',1],
3: ["When coming up to a pedestrian crossing without a raised traffic island, what must you do?","Speed up before the predestrians cross",'Stop and give way to the pedestrians on any part of the crossing',"Sound the horn on your vehicle to warn the pedestrians","Slow down to 30 Kms",'Stop and give way to the pedestrians on any part of the crossing',2],
4: ["can you stop on a bus stop in a private motor vehicle", 'Only between midnight and 6am', "Under no circumstances", "When dropping off passengers", 'Only if it is less than 5 minutes', "Under no cirumstances", 2],
5: ["what is the maximum speed you can drive if you have a 'space saver wheel' fitted? (km/h)", '70 km/h', "100 km/h so you do not hold up traffic", "80 km/h and if the wheel spacer displays a lower limit that applies", "90 km/h", "80 km/h and if the wheel spacer displays a lower limit that applies",3],
6: ["When following another vehicle on a dusty road, You should?",'Speed up to get passed',"Turn your vehicle's windscreen wipers on","Stay back from the dust cloud",'Turn your vehicles headlights on',"Stay back from the dust cloud",3],
7: ["What does the sign containing the letters 'LSZ' mean", 'Low safety zone', "Low stability zone", "Lone star zone", 'Limited speed zone', 'Limited speed zone',4],
8: ["What speed are you allowed to pass a school bus that has stopped to let students on or off?", '20 km/h', "30 km/h", "70 km/h", '10 km/h','20 km/h',1],
9: ["What is the maximum distance a load may extend in front of a car?", '2 meters forward of the front seat', "4 meters forward of the front edge of the front seat", "3 meters forward of the front egde of the front seat", '2.5 meters forward of the front edge of the front seat', '3 meters forward of the front edge of the front seat',3],
10: ["To avoid being blinded by the headlights of another vehicle coming towards you what should you do?", 'Look to the left of the road', "Look to the centre of the road", "Wear sunglasses that have sufficient strength", 'Look to the right side of the road', 'Look to the left of the road',1],
}
def randomiser():
global qnum
qnum = random.randint(1,10)
if qnum not in asked:
asked.append(qnum)
elif qnum in asked:
randomiser()
class QuizStarter:
def __init__(self, parent):
background_color="deeppink"
#frame set up
self.quiz_frame=Frame(parent, bg = background_color, padx=100, pady=100)
self.quiz_frame.grid()
#widgets goes below
self.heading_label=Label(self.quiz_frame, text="NZ Road Rules", font=("TimesNewRoman","18" ,"bold"),bg=background_color)
self.heading_label.grid(row=0, padx=20)
self.var1=IntVar()
#label for username~
self.user_label=Label(self.quiz_frame, text="Please enter your username below: ", font=("Times New Roman","16"),bg=background_color)
self.user_label.grid(row=1, padx=20, pady=20)
#entry box
self.entry_box=Entry(self.quiz_frame)
self.entry_box.grid(row=2,padx=20, pady=20)
#continue button
self.continue_button = Button(self.quiz_frame, text="Continue", font=("Helvetica", "13", "bold"), bg="lightcyan", command=self.name_collection)
self.continue_button.grid(row=3, padx=20, pady=20)
#image
#log o = PhotoImage(file="road.gif")
#self.logo = Label(self.quiz_frame, image=logo)
#self.logo.grid(row=4,padx=20, pady=20)
def name_collection(self):
name=self.entry_box.get()
names_list.append(name) #add name to names list declared at the beginning
self.continue_button.destroy()
self.entry_box.destroy() #Destroy name frame then open the quiz runner
class Quiz:
def _init_(self, parent):
#color selection
background_color="deeppink"
self.quiz_frame=Frame(parent, bg = background_color, padx=40, pady=40)
self.quiz_frame.grid()
#question
self.question_label=Label(self.quiz_frame, text=questions_answers[qnum][0], font=("Tw Cen Mt","16"),bg=background_color)
self.question_label.grid(row=1, padx=10, pady=10)
#holds value of radio buttons
self.var1=IntVar()
#radio button 1
self.rb1= Radiobutton(self.quiz_frame, text=questions_asnwers[qnum][1], font=("Helvetica","12"), bg=background_color,value=1,padx=10,pady=10,
variable=self.var1, indicator = 0, background = "light blue")
self.rb1.grid(row=2, sticky=w)
# radio button 2
self.rb2= Radiobutton(self.quiz_frame, text=questions_asnwers[qnum][2], font=("Helvetica","12"), bg=background_color,value=2,padx=10,pady=10,
variable=self.var1, indicator = 0, background = "light blue")
self.rb2.grid(row=3, sticky=w)
#radio button 3
self.rb3= Radiobutton(self.quiz_frame, text=questions_asnwers[qnum][3], font=("Helvetica","12"), bg=background_color,value=3,padx=10,pady=10,
variable=self.var1, indicator = 0, background = "light blue")
self.rb3.grid(row=4, sticky=w)
# radio button 4
self.rb4= Radiobutton(self.quiz_frame, text=questions_asnwers[qnum][4], font=("Helvetica","12"), bg=background_color,value=4,padx=10,pady=10,
variable=self.var1, indicator = 0, background = "light blue")
self.rb4.grid(row=5, sticky=w)
#confirm button
self.quiz_instance= Button(self.quiz_frame, text="Confirm", font=("Helvetica", "13", "bold"), bg="SpringGreen3")
self.quiz_instance.grid(row=7, padx=5, pady=5)
#score label
self.score_label=Label(self.quiz_frame, text="SCORE", font=("Tw Cen MT","16"),bg=background_color,)
self.score_label.grid(row=8, padx=10, pady=1)
randomiser()
if __name__ == "__main__":
root = Tk()
root.title("NZ Road Rules Quiz")
quiz_ins = QuizStarter(root) #instantiation, making an instance of the class Quiz
root.mainloop()#so the frame doesnt dissapear
|
e3be05086d5147f13ea59b9751ffdabca26dc715 | Tikrong/sudoku | /board.py | 3,317 | 3.78125 | 4 | """
high level support for doing this and that.
"""
import pygame
from sudoku import *
pygame.init()
# colors
WHITE = (255,255,255)
BLACK = (0,0,0)
GREEN = (0,255,0)
RED = (255,0,0)
#fonts
numbers_font = pygame.font.SysFont('verdana', 24)
#screen size
screen_height = 600
screen_width = 450
# sizes
tile_size = 50
screen = pygame.display.set_mode((screen_width, screen_height))
#load sudoku assignment
sudoku = Sudoku("structure0.txt")
solver = SudokuSolver(sudoku)
initial_state = solver.grid(solver.sudoku.initial_assignment)
solution = solver.grid(solver.sudoku.initial_assignment)
status = ""
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# draw cells
for i in range(9):
for j in range(9):
rect = pygame.Rect(j*tile_size, i*tile_size, tile_size, tile_size)
pygame.draw.rect(screen, WHITE, rect, 1)
#print initial assignment
if initial_state[i][j]:
number = numbers_font.render(str(initial_state[i][j]), False, WHITE)
numberRect = number.get_rect()
numberRect.center = rect.center
screen.blit(number, numberRect)
elif solution[i][j]:
number = numbers_font.render(str(solution[i][j]), False, GREEN)
numberRect = number.get_rect()
numberRect.center = rect.center
screen.blit(number, numberRect)
# draw 3x3 red squares
for i in range(3):
for j in range(3):
rect = pygame.Rect(j*tile_size*3, i*tile_size*3, 3*tile_size, 3*tile_size)
pygame.draw.rect(screen, RED, rect, 1)
# draw main boundary
rect = pygame.Rect(0, 0, 9*tile_size, 9*tile_size)
pygame.draw.rect(screen, WHITE, rect, 1)
# UI
# Draw button
Solve_Button = pygame.Rect(3*tile_size, 10*tile_size, 3*tile_size, tile_size)
Solve_Text = numbers_font.render("SOLVE", False, GREEN)
Solve_Text_Rect = Solve_Text.get_rect()
Solve_Text_Rect.center = Solve_Button.center
pygame.draw.rect(screen, WHITE, Solve_Button, 1)
screen.blit(Solve_Text, Solve_Text_Rect)
# Draw status bar
Status_Text = numbers_font.render(status, False, WHITE)
Status_Text_Rect = Status_Text.get_rect()
#Status_Text_Rect.top = Solve_Button.bottom + tile_size * 0.5
#Status_Text_Rect.left = Solve_Button.left
Status_Text_Rect.center = Solve_Button.center
Status_Text_Rect.top = Status_Text_Rect.top + tile_size * 1
screen.blit(Status_Text, Status_Text_Rect)
# Check if button is clicked
click, _, _ = pygame.mouse.get_pressed()
if click == True:
mouse = pygame.mouse.get_pos()
if Solve_Button.collidepoint(mouse):
#send event that we need to solve the puzzle
assignment = solver.solve()
if assignment is None:
status = "NO SOLUTION"
else:
status = "SOLVED"
solution = solver.grid(assignment)
print(solver.counter)
# update everything on the screen
pygame.display.flip()
pygame.quit()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.