text
stringlengths 37
1.41M
|
---|
# abc_lower = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
# 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
# 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# abc_upper = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
# 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
# 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
first_sector = "A"
last_sector = input()
rows_first_sector = int(input())
seats_odd_row = int(input())
sectors_range = list(map(chr, range(ord("A"), ord(last_sector)+1)))
rows = rows_first_sector
odd_seats_range = list(map(chr, range(ord("a"), ord("a") + seats_odd_row)))
even_seats_range = list(map(chr, range(ord("a"), ord("a") + seats_odd_row + 2)))
total_seats = 0
for sector in sectors_range:
rows += 1
for row in range(1, rows):
if row % 2 != 0:
for seat in odd_seats_range:
total_seats += 1
print(f"{sector}{row}{seat}")
else:
for seat in even_seats_range:
total_seats += 1
print(f"{sector}{row}{seat}")
print(total_seats)
|
total_count = int(input())
colored_eggs = {'red': 0, 'orange': 0, 'blue': 0, "green": 0}
for _ in range(total_count):
color = input()
colored_eggs[color] += 1
max_color = 0
max_count = 0
for color, count in colored_eggs.items():
if count == max(colored_eggs.values()):
max_count = count
max_color = color
print(f"Red eggs: {colored_eggs['red']}\n"
f"Orange eggs: {colored_eggs['orange']}\n"
f"Blue eggs: {colored_eggs['blue']}\n"
f"Green eggs: {colored_eggs['green']}\n"
f"Max eggs: {max_count} -> {max_color}")
|
exam_hour = int(input())
exam_minute = int(input())
student_hour = int(input())
student_minute = int(input())
exam_time = exam_hour * 60 + exam_minute
student_time = student_hour * 60 + student_minute
time_difference = exam_time - student_time
abs_time_difference = abs(time_difference)
abs_hour_difference = 0
abs_minutes_difference = 0
if abs_time_difference < 60:
abs_minutes_difference = abs(time_difference)
else:
abs_hour_difference = int(abs_time_difference / 60)
abs_minutes_difference = abs_time_difference % 60
evaluation = 'On time'
if time_difference == 0:
print(evaluation)
elif 0 < time_difference <= 30:
print(evaluation)
print(f'{abs_minutes_difference} minutes before the start')
elif 30 < time_difference < 60:
evaluation = 'Early'
print(evaluation)
print(f'{abs_minutes_difference} minutes before the start')
elif time_difference >= 60:
evaluation = 'Early'
print(evaluation)
print(f'{abs_hour_difference}:{abs_minutes_difference:02d} hours before the start')
elif -60 < time_difference < 0:
evaluation = 'Late'
print(evaluation)
print(f'{abs_minutes_difference} minutes after the start')
elif time_difference <= -60:
evaluation = 'Late'
print(evaluation)
print(f'{abs_hour_difference}:{abs_minutes_difference:02d} hours after the start')
|
import sys
n = int(input())
max_num = -sys.maxsize
while n > 0:
n -= 1
num = int(input())
if num > max_num:
max_num = num
print(max_num)
|
class store_results:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
res = self.func(*args, **kwargs)
with open('results.txt', 'a') as file:
file.write(f"Function '{self.func.__name__}' was add called. Result: {res}\n")
# @store_results
# def add(a, b):
# return a + b
#
# @store_results
# def mult(a, b):
# return a * b
#
# add(2, 2)
# mult(6, 4)
|
string = input()
digits = []
letters = []
other = []
for char in string:
if char.isdigit():
digits.append(char)
elif char.isalpha():
letters.append(char)
else:
other.append(char)
print(''.join(digits))
print(''.join(letters))
print(''.join(other))
|
size = input()
color = input()
count = int(input())
prices = {"Large": {"Red": 16, "Green": 12, "Yellow": 9},
"Medium": {"Red": 13, "Green": 9, "Yellow": 7},
"Small": {"Red": 9, "Green": 8, "Yellow": 5}}
total_price = prices[size][color] * count * 0.65
print(f"{total_price:.2f} leva.")
|
import re
PATH = 'text.txt'
PATTERN = r"[-,!?'.]"
REPLACEMENT = '@'
def replace_bad_chars(line):
return re.sub(PATTERN, REPLACEMENT, line)
def get_even_lines(ll):
return [ll[i].rstrip().split() for i in range(len(ll)) if i % 2 == 0]
def reverse_order(ll):
return [line[::-1] for line in ll]
def print_output(ll):
for line in ll:
print(' '.join(line))
with open(PATH) as file:
lines = [replace_bad_chars(l) for l in file.readlines()]
even_lines = get_even_lines(lines)
reversed_lines = reverse_order(even_lines)
print_output(reversed_lines)
|
from abc import abstractmethod, ABC
class Shape(ABC):
@abstractmethod
def calc_area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def calc_area(self):
return self.width * self.height
class Triangle(Shape):
def __init__(self, b, h):
self.b = b
self.h = h
def calc_area(self):
return 1 / 2 * self.b * self.h
class AreaCalculator:
def __init__(self, shapes):
assert isinstance(shapes, list), "`shapes` should be of type `list`."
self.shapes = shapes
@property
def total_area(self):
return sum([shape.calc_area() for shape in self.shapes])
shapes = [Rectangle(1, 6), Triangle(2, 3)]
calculator = AreaCalculator(shapes)
print("The total area is: ", calculator.total_area)
|
def find_smallest_int(n1, n2, n3):
return min(n1, n2, n3)
number_1 = int(input())
number_2 = int(input())
number_3 = int(input())
print(find_smallest_int(number_1, number_2, number_3))
|
number_str = input()
for n in reversed(number_str):
num = int(n)
for i in range(num):
if num != 0:
char = chr(num+33)
print(char, end='')
if num == 0:
print('ZERO')
else:
print()
|
MATRIX = [
[11, 2, 4],
[4, 5, 6],
[10, 8, -12],
]
LOCAL_TEST = False
def get_matrix_input(is_test=False):
if is_test:
matrix = MATRIX
else:
rows = int(input())
matrix = []
for row in range(rows):
row = [int(x) for x in input().split(' ')]
matrix.append(row)
return matrix
def sum_matrix_elements(matrix):
res = 0
for r in range(len(matrix)):
res += matrix[r][r]
return res
matrix = get_matrix_input(LOCAL_TEST)
print(sum_matrix_elements(matrix))
|
phonebook = {}
the_input = None
while True:
the_input = input()
if the_input.isnumeric():
break
name, number = the_input.split('-')
phonebook[name] = number
n = int(the_input)
for _ in range(n):
contact = input()
if contact in phonebook:
print(f'{contact} -> {phonebook[contact]}')
else:
print(f'Contact {contact} does not exist.')
|
from math import sqrt
def calculate_distance_from_center(x, y):
d = sqrt((x ** 2) + (y ** 2))
return d
def check_closest_point(point1, point2):
x1, y1 = point1
x2, y2 = point2
distance_1 = calculate_distance_from_center(x1, y1)
distance_2 = calculate_distance_from_center(x2, y2)
if distance_1 <= distance_2:
point1 = int(x1), int(y1)
return point1
else:
point2 = int(x2), int(y2)
return point2
first_point = (float(input()), float(input()))
second_point = (float(input()), float(input()))
print(check_closest_point(first_point, second_point))
|
def min_number(*args):
return min(args)
def max_number(*args):
return max(args)
def sum_number(*args):
return sum(args)
def print_output(ll):
print(f'The minimum number is {min_number(*ll)}')
print(f'The maximum number is {max_number(*ll)}')
print(f'The sum number is: {sum_number(*ll)}')
print_output(list(map(int, input().split())))
|
#!/usr/bin/env python3
from math import log
num = int(input())
base = input()
if base == 'natural':
print(f'{log(num):.2f}')
else:
print(f'{log(num, int(base)):.2f}')
for i in base:
if i == '5':
print('wahts up')
else:
if not i:
if i == '1':
if i:
pass
|
import unittest
from project.vehicle import Vehicle
class VehicleTest(unittest.TestCase):
fuel = 50.0
horse_power = 100.0
def setUp(self) -> None:
self.v = Vehicle(self.fuel, self.horse_power)
def test_vehicle_init(self):
self.assertEqual(self.fuel, self.v.fuel)
self.assertEqual(self.v.fuel, self.v.capacity)
self.assertEqual(self.horse_power, self.v.horse_power)
self.assertEqual(1.25, self.v.fuel_consumption)
def test_drive_1_km__when_enough_fuel__should_decrement_fuel(self):
self.v.drive(1)
expected = self.fuel - 1.25
self.assertEqual(expected, self.v.fuel)
def test_drive_100_km__when_not_enough_fuel__should_raise_exception(self):
with self.assertRaises(Exception) as exc:
self.v.drive(100)
msg = "Not enough fuel"
self.assertEqual(msg, str(exc.exception))
def test_refuel__with_valid_fuel_10(self):
self.v.fuel = 10
self.v.refuel(10)
self.assertEqual(20, self.v.fuel)
def test_refuel_with_more_fuel_than_capacity(self):
with self.assertRaises(Exception) as exc:
self.v.refuel(100)
msg = "Too much fuel"
self.assertEqual(msg, str(exc.exception))
def test_vehicle_string_representation(self):
expected = "The vehicle has 100.0 horse power with 50.0 fuel left and 1.25 fuel consumption"
actual = self.v.__str__()
self.assertEqual(expected, actual)
if __name__ == '__main__':
unittest.main()
|
from math import ceil
count_of_students = int(input())
count_of_lectures = int(input())
initial_bonus = int(input())
all_bonuses = []
best_student = {"bonus": 0, "attendances": 0}
for student in range(count_of_students):
attendances = int(input())
bonus = attendances / count_of_lectures * (5 + initial_bonus)
if bonus > best_student["bonus"]:
best_student["bonus"] = bonus
best_student["attendances"] = attendances
max_bonus = ceil(best_student["bonus"])
max_attendances = best_student["attendances"]
print(f'Max Bonus: {max_bonus}.')
print(f'The student has attended {max_attendances} lectures.')
|
from collections import deque
BIGGEST_ORDER = 0
MIN_OREDER = 0
food_quantity = int(input())
orders_input = [int(s) for s in input().split(' ')]
orders = deque(orders_input)
if orders:
orders_copy = orders.copy()
best = MIN_OREDER
while orders_copy:
el = orders_copy.popleft()
if el >= best:
best = el
print(best)
while orders:
current = orders.popleft()
if current > food_quantity:
orders.appendleft(current)
break
food_quantity -= current
if orders:
orders_left = " ".join(map(str, orders))
print(f'Orders left: {orders_left}')
else:
print('Orders complete')
|
movie_title = input()
hall_type = input()
tickets_sold = int(input())
prices = {
"A Star Is Born": {"normal": 7.5, "luxury": 10.5, "ultra luxury": 13.5},
"Bohemian Rhapsody": {"normal": 7.35, "luxury": 9.45, "ultra luxury": 12.75},
"Green Book": {"normal": 8.15, "luxury": 10.25, "ultra luxury": 13.25},
"The Favourite": {"normal": 8.75, "luxury": 11.55, "ultra luxury": 13.95}
}
income = prices[movie_title][hall_type] * tickets_sold
print(f"{movie_title} -> {income:.2f} lv.")
|
from math import ceil, floor
rocket_price = float(input())
rocket_count = int(input())
sneakers_count = int(input())
sneakers_price = 1/6 * rocket_price
total = rocket_count * rocket_price + sneakers_count * sneakers_price
total += total * 0.2
novac_costs = 1/8 * total
sponsors_costs = 7/8 * total
print(f"Price to be paid by Djokovic {floor(novac_costs)}")
print(f"Price to be paid by sponsors {ceil(sponsors_costs)}")
|
def collect(inv, i):
if i not in inv:
inv.append(i)
return inv
def drop(inv, i):
if i in inv:
inv.remove(i)
return inv
def combine_items(inv, i):
old, new = i.split(":")
if old in inv:
inv.insert(inv.index(old) + 1, new)
return inv
def renew(inv, i):
if i in inv:
inv.remove(i)
inv.append(i)
return inv
inventory = input().split(", ")
data = input()
while not data == "Craft!":
command, item = data.split(" - ")
if command == "Collect":
inventory = collect(inventory, item)
elif command == "Drop":
inventory = drop(inventory, item)
elif command == "Combine Items":
inventory = combine_items(inventory, item)
elif command == "Renew":
inventory = renew(inventory, item)
data = input()
print(", ".join(inventory))
|
class Animal:
sound = ''
def make_sound(self):
return self.sound
class Cat(Animal):
sound = 'meow'
class Dog(Animal):
sound = 'bark'
class Lion(Animal):
sound = 'roar'
def animal_sound(animals: list):
for animal in animals:
print(animal.make_sound())
animals = [Cat(), Dog(), Lion()]
animal_sound(animals)
## добавете ново животно и рефакторирайте кода да работи без да се налага да се правят промени по него
## при добавяне на нови животни
# animals = [Animal('cat'), Animal('dog'), Animal('chicken')]
|
class MovieWorld:
def __init__(self, name: str):
self.name = name
self.customers = [] # list of customers objects
self.dvds = [] # list of dvd objects
def __repr__(self):
rep = ''
for customer in self.customers:
rep += f'{customer}\n'
for dvd in self.dvds:
rep += f'{dvd}\n'
return rep
@staticmethod
def dvd_capacity():
return 15
@staticmethod
def customer_capacity():
return 10
@staticmethod
def can_add(count, capacity):
return count < capacity
@staticmethod
def find_object(obj_id, collection):
for obj in collection:
if obj.id == obj_id:
return obj
def add_customer(self, customer):
if self.can_add(len(self.customers), self.customer_capacity()):
self.customers.append(customer)
def add_dvd(self, dvd):
if self.can_add(len(self.dvds), self.dvd_capacity()):
self.dvds.append(dvd)
def rent_dvd(self, customer_id: int, dvd_id: int):
customer = self.find_object(customer_id, self.customers)
dvd = self.find_object(dvd_id, self.dvds)
if dvd in customer.rented_dvds:
return f"{customer.name} has already rented {dvd.name}"
if dvd.is_rented:
return "DVD is already rented"
if customer.age < dvd.age_restriction:
return f"{customer.name} should be at least {dvd.age_restriction} to rent this movie"
customer.rented_dvds.append(dvd)
dvd.is_rented = True
return f"{customer.name} has successfully rented {dvd.name}"
def return_dvd(self, customer_id, dvd_id):
customer = self.find_object(customer_id, self.customers)
dvd = self.find_object(dvd_id, self.dvds)
if dvd not in customer.rented_dvds:
return f"{customer.name} does not have that DVD"
customer.rented_dvds.remove(dvd)
dvd.is_rented = False
return f"{customer.name} has successfully returned {dvd.name}"
|
def print_title(text):
print("<h1>")
print(f" {text}")
print("</h1>")
def print_content(text):
print("<article>")
print(f" {text}")
print("</article>")
def print_comment(text):
print("<div>")
print(f" {text}")
print("</div>")
title, content, comment = input(), input(), input()
print_title(title)
print_content(content)
while not comment == "end of comments":
print_comment(comment)
comment = input()
|
snowballs = int(input())
best_value = 0
best_snowball = {}
for snowball in range(snowballs):
snow = int(input())
time = int(input())
quality = int(input())
value = int((snow / time) ** quality)
if value > best_value:
best_value = value
best_snowball = {'best_snow': snow, 'best_time': time, 'best_value': value, 'best_quality': quality}
print(f"{best_snowball['best_snow']} : {best_snowball['best_time']} = {best_snowball['best_value']} ({best_snowball['best_quality']})")
|
def process_data(d):
"""Takes the input and returns processed values
for command, index and value."""
com, i, v = d.split()
return com, int(i), int(v)
def is_valid_index(index, t_list):
"""Checks if the given index is in the range of the list."""
if index in range(len(t_list)):
return True
def shoot(index, power, t_list):
"""Performs the 'shoot' command."""
if is_valid_index(index, t_list):
t_list[index] -= power
if t_list[index] <= 0:
t_list.pop(index)
return t_list
def add(index, val, t_list):
"""Performs the 'add' command."""
if is_valid_index(index, t_list):
t_list.insert(index, val)
else:
print("Invalid placement!")
return t_list
def strike(index, radius, t_list):
"""Performs the 'strike' command."""
start = index - radius
end = index + radius
if start >= 0 and end < len(t_list):
t_list = t_list[:start] + t_list[end + 1:]
else:
print("Strike missed!")
return t_list
def end(t_list):
"""Prints joined result list of mapped to string integers."""
print("|".join(map(str, t_list)))
def main():
targets = [int(s) for s in input().split()]
data = input()
while not data == "End":
command, index, value = process_data(data)
if command == "Shoot":
targets = shoot(index, value, targets)
elif command == "Add":
targets = add(index, value, targets)
elif command == "Strike":
targets = strike(index, value, targets)
data = input()
end(targets)
if __name__ == '__main__':
main()
|
string = input()
stack = []
for char in string:
stack.append(char)
result = ""
while stack:
result += stack.pop()
print(result)
# print(string[::-1])
|
#!/usr/bin/python3
# read in input data
data = []
group = []
with open("input.txt", "r") as f:
for line in f:
line = line.strip()
if line != "":
group.append(line)
else:
data.append(group)
group = []
data.append(group)
group = []
f.close()
# strategy:
# count every occurence of each character (= question answered with yes)
# if count for a specific char is equal to the amount of people in that group
# all of them answered yes to that question
sum_all_answers = 0
for group in data:
persons_in_group = len(group)
chars_in_group = {}
for person in group:
for char in person:
if char in chars_in_group:
chars_in_group[char] += 1
else:
chars_in_group[char] = 1
# if count of one char is equal to the amount of people
# then this question has been answered by all with yes
# -> add one to the overall count :-)
for char in chars_in_group:
if chars_in_group[char] == persons_in_group:
sum_all_answers += 1
print("Sum of all groups: {}".format(sum_all_answers))
|
#David Lupea
#IntroCS2 pd5
#HW34 -- End ofEndOfFiles
#2018-5-08
#Reads a .csv file consisting of 3 rows: a last name, a first name and an unknown number of letter grades:
#A being 4, B being 3, C being 2, D being 1 and F being 0 points. Computes and prints the grade point average
#of each student.
def gradepointAVG(filename):
fileIn = open(filename, 'rU')
names = []
grades = []
for line in fileIn:
data = line.strip().split(',')
names.append(data[1] + ' ' + data[0])
total = 0
num_grades = len(data[2])
for letter in data[2].upper():
if letter == 'A':
total += 4.0
elif letter == 'B':
total += 3.0
elif letter == 'C':
total += 2.0
elif letter == 'D':
total += 1.0
else:
total += 0.0
grades.append(total / num_grades)
fileIn.close()
for i in range(len(names)):
if grades[i] > 3.75:
print names[i] + ' ' +str(grades[i]) + ' *'
else:
print names[i] + ' ' +str(grades[i])
|
#Team David + Kevin
#David Lupea and Kevin Mesta
#IntroCS2 pd 5
#Labwork 07
#2018-02-12
#Checks if the given year is a leap year
def isLeapYr(year):
if (year % 400 == 0): #Checks if the century is one of a multiple of 400
return True
if (year % 4 == 0) and (year % 100 != 0): #checks to see that the year is one of every 4 but not a multiple of 100 like 700 or 900
return True
else:
return False #if th year does not fit any of the cases above then its not a leap year
#gives you the number of days in a given month given the month and year. cross references the isLeapYr function.
def daysInMonth(month, year):
if (month == 1) or (month == 3) or (month == 5) or (month == 7) or (month == 8) or (month == 10) or (month == 12): #all of these months have 31 days no matter what so if any of these months are chosen there is no need to check the year
return 31
if (month == 4) or (month == 6) or (month == 9) or (month == 11): #all of these months have 30 days no matter what so if any of these are chosen then there is no need to check the year
return 30
if (month == 2 and isLeapYr(year)): #month 2 is the only one with varying days so by using the function above if the month is 2 and if it is a leap year then there will be 29 days
return 29
else:
return 28 #if month 2 is chosen but its not a leap year then 28 will be what is returned
#Tells you whether or not to sleep in given true or false statements as to whether it is a weekday or vacation day
def sleep_in(weekday, vacation):
if vacation:
return True # if there is vacation then we will always sleep in no matter what regardless of whether or not its a weekday or weekend
if weekday:
return False #if the function reaches this point then it means that there is no vacation and then that means that if its a weekday we have school and we dont sleep in
else:
return True #this last case means that it is not a weekday so that means its the weekend and we will sleep in as well
#Tells you whether or not you're in trouble based on if the monkeys are smiling at you or not
def monkey_trouble(a_smiles, b_smiles):
if a_smiles == b_smiles: #because of the way the monkeys act, if they are both smiling or not smiling this means trouble so if they are equal to each other then it will return true
return True
else:
return False #if the test above returns false that means that the monkeys have different expressions and you are not in trouble so it will return false
#Tells you if two numbers make ten. This happens if either one number is ten or the two add up to ten
def makes10(a, b):
if (a == 10) or (b == 10): # if just one of the numbers are 10 then you will return true so thats why there is an or because it can be either
return True
if (a + b == 10): # this part means that the first case is false and that we have to check if the sum is equal to 10 which if its true it will return true
return True
else:
return False # this last part means that both of the cases above are not true so it will return false
#Challenge problem(using external libraries)
def external_dates_problem():
from datetime import date #Imports the datetime library to work with dates
year = int(raw_input('Enter year you were born: ')) #Asks you for the dates that the code will work with
month = int(raw_input ('Enter month you were born: '))
day = int(raw_input ('Enter day you were born: '))
tyear = int(raw_input('Enter year we are currently in: '))
tmonth = int(raw_input ('Enter month we are currently in: '))
tday = int(raw_input ('Enter day we are currently in: '))
bday = date(year, month, day) #Sets your birthday based on the given input as a date object
today = date(tyear, tmonth, tday) #Sets today's date based on the given input as a date object
total_days = today - bday #Finds the time between today and your birthday
days_old = total_days.days #total_days includes hours, minutes, seconds, etc. as well so we parse it for only the days
years_old = int((days_old / 365.25)) #Finds how old you are
print "You are", days_old, "days old" #Gives you the various outputs
print "You are", years_old, "years old"
#Challenge problem without using external features. Does not work with leap day. Cross references the daysInMonth function
def dates_problem():
year = int(raw_input('Enter year you were born: ')) #Asks you for the dates that the code will work with
month = int(raw_input ('Enter month you were born: '))
day = int(raw_input ('Enter day you were born: '))
tyear = int(raw_input('Enter year we are currently in: '))
tmonth = int(raw_input ('Enter month we are currently in: '))
tday = int(raw_input ('Enter day we are currently in: '))
days_old = 0 #Initializes days_old as a variable equal to zero. it will add over time
for cur_year in range (year + 1, tyear): #Iterates through each year and month betweeb your birthday and today. If your bday is April, 2002, and today is Feb, 2018. It iterates through all
#the days in 2003, 2004, 2005 ... 2017
for cur_month in range (1, 13):
days_old += daysInMonth(cur_month, cur_year) #Adds the number of days in each month to the days_old variable
days_old += (daysInMonth(month, year) - day) #Adds to the days_old variable the number of days between your birthday and the end of the month of your birthday
days_old += tday #Adds to the days_old variable the number of days betwen the start of the current month and today
for additional_months in range(month + 1, 13):
days_old += daysInMonth(additional_months, year) #Adds to the days_old variable the number of days in the months between your birthday and the end of the year.
#Ex: If you were born on June, 4, 2002 this will calculate the number of days in July, August... December of that year
for new_months in range(1, tmonth):
days_old += daysInMonth(new_months, year) #Adds to the days_old variable the number of days between the start of this year and the start of this month
#Ex: if today is July, 4, 2018 it will calculate the number of days in January, Febuary ... June of this year
years_old = int((days_old / 365.25)) #Finds how old you are
print "You are", days_old, "days old" #Gives you the various outputs
print "You are", years_old, "years old"
|
#David Lupea
#IntroCS2 pd<5
#HW7 -- PassJudgement
#2018-2-26
def pythTriple(a, b, c):
#Checks to see if they are all integers(all triples are integers)
if type(a) == int and type(b) == int and type(c) == int:
#Tries the three cases as to whether or not the sum of the square of the length of two sides equals the square of the length of the third
if (a ** 2) + (b ** 2) == (c ** 2):
return True
elif (a ** 2) + (c ** 2) == (b ** 2):
return True
elif (b ** 2) + (c ** 2) == (a ** 2):
return True
#If the sum of the squares of two sides are ot equal to the square of the third, it gives you false.
else:
return False
else:
return False
def gradeConnv(g):
#Runs through each of the letter grades to see which letter the score is on
if (g < 65) and (g >= 0):
return "F"
elif (g >=65) and (g < 70):
return "D"
elif (g >= 70) and (g < 80):
return "C"
elif (g >= 80) and (g < 90):
return "B"
elif (g >= 90) and (g <= 100):
return "A"
#If the score(g) is not in the range 0 <= g <= 100 it tells you the number is out of the accepted range
else:
return "Number out of range"
def passJudgement(letterGrade):
#Checks through each letter grade and gives it critiques based on it
if letterGrade == "F":
return "You did terrible, you failed. Did you even try!?"
elif letterGrade == "D":
return "You did very bad. Perhaps you should study next time?"
elif letterGrade == "C":
return "You did quite bad. Maybe a little more studying would have done the trick"
elif letterGrade == "B":
return "You did quite well. You were so close though. Review a bit better next time and you'll be at an A in no time"
#If all else is false then your grade must have been an A in which case it will tell you that you did great.
else:
return "Great job. I can tell that you are knowledgeable... or you just crammed the night before"
|
#Write code to swap the value of two numbers without using literals
x = 2
y = 3
print "x is equal to %s" %x, "y is equal to %s" %y
print "Switch"
#a = x
#b = y
#x = b
#y = a
x, y = y, x
print "x is equal to %s" %x, "y is equal to %s" %y
|
#David Lupea
#IntroCS2 pd5
#HW 8 -- Script Writing
#2018-02-27
#largest_odd.py
num1 = int(raw_input("Enter an integer: ")) #Takes in the inputs
num2 = int(raw_input("Enter another integer: "))
num3 = int(raw_input("Enter a final integer: "))
if num1 % 2 == 1 or num2 % 2 == 1 or num3 % 2 == 1: #Checks to see if all of them are even. If they are, it tells you none of them were odd
if num1 % 2 == 0: #Checks each number and if it is even sets it to None. This makes it so miniscule it is not accounted for in determining
num1 = None #the maximum value
if num2 % 2 == 0:
num2 = None
if num3 % 2 == 0:
num3 = None
print max(num1, num2, num3) #Prints the maximum value of the three numbers
else:
print "None of the numbers were odd"
#sort3.py
n1 = float(raw_input("Enter a number: ") #Takes in the inputs
n2 = float(raw_input("Enter another number: "))
n3 = float(raw_input("Enter a final number: "))
#With conditionals
if n1 >= n2 and n1 >= n3: #Checks if n1 is the biggest number
if n2 >= n3: #Chechs which number is the second biggest between n2 and n3
print n3, n2, n1
else:
print n2, n3, n1
elif n2 >= n1 and n2 >= n3: #Checks if n2 is the biggest number
if n1 >= n3: #Chechs which number is the second biggest between n1 and n3
print n3, n1, n2
else:
print n1, n3, n2
elif n3 >= n1 and n3 >= n2: #Checks if n3 is the biggest number
if n1 >= n2: #Chechs which number is the second biggest between n1 and n2
print n2, n1, n3
else:
print n1, n2, n3
#Without conditionals
minimum = min(n1, n2, n3)
middle = (n1 + n2 + n3 - max(n1, n2, n3) - min(n1, n2, n3))
maximum = max(n1, n2, n3)
print minimum, middle, maximum
|
#Mimics the bash command wc
# $wc filename -> number of lines, number of words, number of characters, filename
#filename
filename = 'Tom_Sawyer_Preface.txt'
#create a dile object to read from
fileIn = open(filename, 'r')
#Initialize variables
numlines, numwords, numchars = 0,0,0
for line in fileIn:
numlines += 1
numchars += len(line)
numwords += len(line.split())
#Print resullts
print numlines, numwords, numchars, filename
#Close connection
fileIn.close()
|
number = raw_input("Enter a number: ")
total = 0
for i in number:
x = int(i)
total += x
print total
|
text = 'Ala ma kota'
# for char in text:
# print(char)
#
length = len(text)
# for idx in range(length):
# print(text[idx])
# something something something
some_range = range(length)
print(some_range)
is_loop_done = False
for value in some_range:
print(value)
# the bad way, check forelse.py
if value == length - 1:
is_loop_done = True
if is_loop_done:
print('heeelo')
|
value = int(input('Podaj liczbe:'))
# value = int(value)
# @TODO: wyswietl kolejne liczby parzyste bez instrukcji warunkowych
start = 0
stop = value
step = 2
for idx in range(start, stop, step):
print(idx)
|
data = input('Podaj liczbe lub litere: ')
while not data.isalpha() and not data.isdigit():
print('Podales zle dane, podaj jeszcze raz')
data = input('Podaj liczbe lub litere: ')
if data.isdigit():
print('Podales liczbe')
elif data.isalpha():
print('Podales litere')
print('bye!')
|
#!/usr/local/bin/python3
from functools import reduce
from itertools import product
EMPTY = 'L'
FLOOR = '.'
OCCUPIED = '#'
class Seating(list):
@staticmethod
def from_file(input_file):
seating = Seating()
with open(input_file) as f:
for line in f.readlines():
seating.append(list(line.rstrip()))
return seating
"""an append-only seating map that maintains a hash of its contents"""
def occupied(self):
return reduce(lambda t, row: t + sum(1 for s in row if s == OCCUPIED), self, 0)
def shuffle(self):
"""returns a new Seating with seats shfited according to the rules"""
shuffled = Seating()
rows = len(self)
cols = len(self[0])
for i, row in enumerate(self):
shuffled_row = []
for j, spot in enumerate(row):
if self._empty_area((i, j)):
shuffled_row.append(OCCUPIED)
elif self._busy_area((i, j)):
shuffled_row.append(EMPTY)
else:
shuffled_row.append(row[j])
shuffled.append(shuffled_row)
return shuffled
def _look(self, origin, direction):
"""returns the state of the first seat seen by looking in the given direction"""
# this method is very slow but i am behind on AOC so sadly this will remain as-is
dx, dy = direction
x, y = origin[0] + dx, origin[1] + dy
while 0 <= x < len(self) and 0 <= y < len(self[0]):
spot = self[x][y]
if spot != FLOOR:
return spot
x += dx
y += dy
def _visible_from(self, seat):
"""returns the first seat visible in every direction from the given seat"""
directions = [d for d in product(range(-1, 2), range(-1, 2)) if d != (0, 0)]
return filter(None, map(lambda d: self._look(seat, d), directions))
def _empty_area(self, seat):
"""seat `seat` is empty and there are no adjacent occupied seats"""
return self[seat[0]][seat[1]] == EMPTY and not any(s == OCCUPIED for s in self._visible_from(seat))
def _busy_area(self, seat):
"""seat `seat` is occupied and five or more adjacents seats are also occupied"""
occupied_neighbors = sum(1 for n in self._visible_from(seat) if n == OCCUPIED)
return self[seat[0]][seat[1]] == OCCUPIED and occupied_neighbors >= 5
def solution(seating):
shuffled = seating.shuffle()
while shuffled != seating:
seating = shuffled
shuffled = shuffled.shuffle()
return shuffled.occupied()
if __name__ == '__main__':
print(solution(Seating.from_file('input.txt')))
|
import sys
def is_valid(args):
char, pos_1, pos_2, password = args
extracted = [password[p - 1] for p in [pos_1, pos_2]]
return extracted.count(char) == 1
def parse_line(line):
char_poses, char_colon, password = line.split()
pos_1, pos_2 = [int(i) for i in char_poses.split("-")]
char = char_colon.strip(":")
return char, pos_1, pos_2, password
lines = [line.strip() for line in sys.stdin if line.strip()]
valid_lines = [line for line in lines if is_valid(parse_line(line))]
print(len(valid_lines))
|
def validate_passports(input_string):
failed = 0
passports = input_string.split("\n\n")
required_fields = [
"byr:",
"iyr:",
"eyr:",
"hgt:",
"hcl:",
"ecl:",
"pid:",
# "cid",
]
for passport in passports:
for field in required_fields:
if field not in passport:
failed += 1
break
return len(passports) - failed
def validate_passports2(input_string):
failed = 0
passports = input_string.split("\n\n")
required_fields = [
"byr",
"iyr",
"eyr",
"hgt",
"hcl",
"ecl",
"pid",
# "cid",
]
for passport in passports:
passport_dict = {}
passport = passport.replace("\n", " ")
fieldstrings = passport.split(" ")
for i in fieldstrings:
if ":" in i:
key, value = i.split(":")
passport_dict[key] = value
for field in required_fields:
if field not in passport_dict:
failed += 1
break
if not validate(field, passport_dict[field]):
failed += 1
break
return len(passports) - failed
def validate(field, value):
if field == 'byr':
return 1920 <= int(value) <= 2002
elif field == 'iyr':
return 2010 <= int(value) <= 2020
elif field == 'eyr':
return 2020 <= int(value) <= 2030
elif field == 'hgt':
if 'cm' in value:
value = value.rstrip('cm')
return 150 <= int(value) <= 193
if 'in' in value:
value = value.rstrip('in')
return 59 <= int(value) <= 76
elif field == 'hcl':
if len(value) == 7:
value = value.lstrip('#')
try:
int(value)
return True
except ValueError:
return True
elif field == 'ecl':
if value in ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth',]:
return True
else:
return False
elif field == 'pid':
if len(value) == 9 and not any(c.isalpha() for c in value):
return True
else:
return False
else:
return False
|
def get_seat_id(code):
row = code[:7]
col = code[7:]
row = row.replace('F', '0').replace('B', '1')
col = col.replace('L', '0').replace('R', '1')
row = int(row, 2)
col = int(col, 2)
seat_id = row * 8 + col
return seat_id
def get_highest_seat_id(input):
highest = 0
for line in input.splitlines():
seat_id = get_seat_id(line)
if seat_id > highest:
highest = seat_id
return highest
def get_my_seat(input):
all_seats = list(range(0, 851))
print(all_seats)
for line in input.splitlines():
all_seats.remove(get_seat_id(line))
print(all_seats)
# 1-12 are invalid, 1*4+8seats per row
my_seat = [x for x in all_seats if 12 < x <= 842 ]
return my_seat[0]
|
'''
This file implements the platformer rules.
'''
import numpy as np
from numpy.random import uniform
from util import vector
def bound(value, lower, upper):
''' Clips off a value which exceeds the lower or upper bounds. '''
if value < lower:
return lower
elif value > upper:
return upper
else:
return value
def bound_vector(vect, xmax, ymax):
''' Bounds a vector between a negative and positive maximum range. '''
xval = bound(vect[0], -xmax, xmax)
yval = bound(vect[1], -ymax, ymax)
return vector(xval, yval)
WIDTH1 = 250
WIDTH2 = 275
WIDTH3 = 50
GAP1 = 225
GAP2 = 235
HEIGHT1 = 0.0
HEIGHT2 = 0.0
HEIGHT3 = 0.0
MAX_HEIGHT = max(1.0, HEIGHT1, HEIGHT2, HEIGHT3)
MAX_PLATWIDTH = max(WIDTH1, WIDTH2, WIDTH3)
PLATHEIGHT = 40.0
MAX_WIDTH = WIDTH1 + WIDTH2 + WIDTH3 + GAP1 + GAP2
MAX_GAP = max(GAP1, GAP2)
DT = 0.05
MAX_DX = 100.0
MAX_DY = 200.0
MAX_DX_ON = 70.0
MAX_DDX = (MAX_DX - MAX_DX_ON) / DT
MAX_DDY = MAX_DY / DT
ENEMY_SPEED = 30.0
LEAP_DEV = 1.0
HOP_DEV = 1.0
ENEMY_NOISE = 0.5
CHECK_SCALE = False
GRAVITY = 9.8
def scale_state(state):
''' Scale state variables between 0 and 1. '''
new_state = np.copy(state)
scaled = (new_state + SHIFT_VECTOR) / SCALE_VECTOR
if CHECK_SCALE:
for i in range(scaled.size):
if not 0 <= scaled[i] <= 1:
print i, scaled[i], new_state[i]
assert 0 <= scaled[i] <= 1
return scaled
def platform_features(state):
''' Compute the implicit features of the platforms. '''
xpos = state[0]
if xpos < WIDTH1 + GAP1:
pos = 0.0
wd1 = WIDTH1
wd2 = WIDTH2
gap = GAP1
diff = HEIGHT2 - HEIGHT1
elif xpos < WIDTH1 + GAP1 + WIDTH2 + GAP2:
pos = WIDTH1 + GAP1
wd1 = WIDTH2
wd2 = WIDTH3
gap = GAP2
diff = HEIGHT3 - HEIGHT2
else:
pos = WIDTH1 + GAP1 + WIDTH2 + GAP2
wd1 = WIDTH3
wd2 = 0.0
gap = 0.0
diff = 0.0
return [wd1 / MAX_PLATWIDTH, wd2 / MAX_PLATWIDTH, gap / MAX_GAP, pos / MAX_WIDTH, diff / MAX_HEIGHT]
class Platform:
''' Represents a fixed platform. '''
def __init__(self, xpos, ypos, width):
self.position = vector(xpos, ypos)
self.size = vector(width, PLATHEIGHT)
class Simulator:
''' This class represents the environment. '''
def __init__(self):
''' The entities are set up and added to a space. '''
self.xpos = 0.0
self.player = Player()
self.platform1 = Platform(0.0, HEIGHT1, WIDTH1)
self.platform2 = Platform(GAP1 + self.platform1.size[0], HEIGHT2, WIDTH2)
self.platform3 = Platform(self.platform2.position[0] +
GAP2 + self.platform2.size[0], HEIGHT3, WIDTH3)
self.enemy1 = Enemy(self.platform1)
self.enemy2 = Enemy(self.platform2)
self.states = []
def get_state(self):
''' Returns the representation of the current state. '''
if self.player.position[0] > self.platform2.position[0]:
enemy = self.enemy2
else:
enemy = self.enemy1
state = np.array([
self.player.position[0], #0
self.player.velocity[0], #1
enemy.position[0], #2
enemy.dx]) #3
return state
def on_platforms(self):
''' Checks if the player is on any of the platforms. '''
for platform in [self.platform1, self.platform2, self.platform3]:
if self.player.on_platform(platform):
return True
return False
def perform_action(self, action, dt=DT):
''' Applies for selected action for the given agent. '''
if self.on_platforms():
if action:
act, parameters = action
if act == 'jump':
self.player.jump(parameters)
elif act == 'run':
self.player.run(parameters, dt)
elif act == 'leap':
self.player.leap_to(parameters)
elif act == 'hop':
self.player.hop_to(parameters)
else:
self.player.fall()
def lower_bound(self):
''' Returns the lowest height of the platforms. '''
lower = min(self.platform1.position[1], self.platform2.position[1], self.platform3.position[1])
return lower
def right_bound(self):
''' Returns the edge of the game. '''
return self.platform3.position[0] + self.platform3.size[0]
def terminal_check(self, reward=0.0):
''' Determines if the episode is ended, and the reward. '''
end_episode = self.player.position[1] < self.lower_bound() + PLATHEIGHT
right = self.player.position[0] >= self.right_bound()
for entity in [self.enemy1, self.enemy2]:
if self.player.colliding(entity):
end_episode = True
if right:
reward = (self.right_bound() - self.xpos) / self.right_bound()
end_episode = True
return reward, end_episode
def update(self, action, dt=DT, interface = False):
''' Performs a single transition with the given action,
then returns the new state and a reward. '''
if interface:
self.xpos = self.player.position[0]
self.states.append([self.player.position.copy(),
self.enemy1.position.copy(),
self.enemy2.position.copy()])
self.perform_action(action, dt)
if self.on_platforms():
self.player.ground_bound()
if self.player.position[0] > self.platform2.position[0]:
enemy = self.enemy2
else:
enemy = self.enemy1
for entity in [self.player, enemy]:
entity.update(dt)
for platform in [self.platform1, self.platform2, self.platform3]:
if self.player.colliding(platform):
self.player.decollide(platform)
self.player.velocity[0] = 0.0
reward = (self.player.position[0] - self.xpos) / self.right_bound()
return self.terminal_check(reward)
def take_action(self, action):
''' Take a full, stabilised update. '''
end_episode = False
run = True
act, params = action
self.xpos = self.player.position[0]
step = 0
difft = 1.0
while run:
if act == "run":
reward, end_episode = self.update(('run', abs(params)), DT)
difft -= DT
run = difft > 0
elif act in ['jump', 'hop', 'leap']:
reward, end_episode = self.update(action)
run = not self.on_platforms()
action = None
if end_episode:
run = False
step += 1
state = self.get_state()
return state, reward, end_episode, step
class Enemy:
''' Defines the enemy. '''
size = vector(20.0, 30.0)
def __init__(self, platform):
''' Initializes the enemy on the platform. '''
self.dx = -ENEMY_SPEED
self.platform = platform
self.position = self.platform.size + self.platform.position
self.position[0] -= self.size[0]
def update(self, dt):
''' Shift the enemy along the platform. '''
right = self.platform.position[0] + self.platform.size[0] - self.size[0]
if not self.platform.position[0] < self.position[0] < right:
self.dx *= -1
self.dx += np.random.normal(0.0, ENEMY_NOISE*dt)
self.dx = bound(self.dx, -ENEMY_SPEED, ENEMY_SPEED)
self.position[0] += self.dx * dt
self.position[0] = bound(self.position[0], self.platform.position[0], right)
class Player(Enemy):
''' Represents the player character. '''
decay = 0.99
def __init__(self):
''' Initialize the position to the starting platform. '''
self.position = vector(0, PLATHEIGHT)
self.velocity = vector(0.0, 0.0)
def update(self, dt):
''' Update the position and velocity. '''
self.position += self.velocity * dt
self.position[0] = bound(self.position[0], 0.0, MAX_WIDTH)
self.velocity[0] *= self.decay
def accelerate(self, accel, dt=DT):
''' Applies a power to the entity in direction theta. '''
accel = bound_vector(accel, MAX_DDX, MAX_DDY)
self.velocity += accel * dt
self.velocity[0] -= abs(np.random.normal(0.0, ENEMY_NOISE*dt))
self.velocity = bound_vector(self.velocity, MAX_DX, MAX_DY)
self.velocity[0] = max(self.velocity[0], 0.0)
def ground_bound(self):
''' Bound dx while on the ground. '''
self.velocity[0] = bound(self.velocity[0], 0.0, MAX_DX_ON)
def run(self, power, dt):
''' Run for a given power and time. '''
if dt > 0:
self.accelerate(vector(power / dt, 0.0), dt)
def jump(self, power):
''' Jump up for a single step. '''
self.accelerate(vector(0.0, power / DT))
def jump_to(self, diffx, dy0, dev):
''' Jump to a specific position. '''
time = 2.0 * dy0 / GRAVITY + 1.0
dx0 = diffx / time - self.velocity[0]
dx0 = bound(dx0, -MAX_DDX, MAX_DY - dy0)
if dev > 0:
noise = -abs(np.random.normal(0.0, dev, 2))
else:
noise = np.zeros((2,))
accel = vector(dx0, dy0) + noise
self.accelerate(accel / DT)
def hop_to(self, diffx):
''' Jump high to a position. '''
self.jump_to(diffx, 35.0, HOP_DEV)
def leap_to(self, diffx):
''' Jump over a gap. '''
self.jump_to(diffx, 25.0, LEAP_DEV)
def fall(self):
''' Apply gravity. '''
self.accelerate(vector(0.0, -GRAVITY))
def decollide(self, other):
''' Shift overlapping entities apart. '''
precorner = other.position - self.size
postcorner = other.position + other.size
newx, newy = self.position[0], self.position[1]
if self.position[0] < other.position[0]:
newx = precorner[0]
elif self.position[0] > postcorner[0] - self.size[0]:
newx = postcorner[0]
if self.position[1] < other.position[1]:
newy = precorner[1]
elif self.position[1] > postcorner[1] - self.size[1]:
newy = postcorner[1]
if newx == self.position[0]:
self.velocity[1] = 0.0
self.position[1] = newy
elif newy == self.position[1]:
self.velocity[0] = 0.0
self.position[0] = newx
elif abs(self.position[0] - newx) < abs(self.position[1] - newy):
self.velocity[0] = 0.0
self.position[0] = newx
else:
self.velocity[1] = 0.0
self.position[1] = newy
def above_platform(self, platform):
''' Checks the player is above the platform. '''
return -self.size[0] <= self.position[0] - platform.position[0] <= platform.size[0]
def on_platform(self, platform):
''' Checks the player is standing on the platform. '''
ony = self.position[1] - platform.position[1] == platform.size[1]
return self.above_platform(platform) and ony
def colliding(self, other):
''' Check if two entities are overlapping. '''
precorner = other.position - self.size
postcorner = other.position + other.size
collide = (precorner < self.position).all()
collide = collide and (self.position < postcorner).all()
return collide
SHIFT_VECTOR = np.array([Player.size[0], 0.0, 0.0,
ENEMY_SPEED])
SCALE_VECTOR = np.array([MAX_WIDTH + Player.size[0], MAX_DX,
MAX_WIDTH, 2*ENEMY_SPEED])
STATE_DIM = Simulator().get_state().size
|
from queue import Queue
class ContactTracer:
def __init__(self):
self.contacts = {}
self.counts = {}
def addContact(self, num1, num2):
if num1 not in self.contacts:
self.contacts[num1] = {num2}
self.counts[num1] = 1
else:
if num2 not in self.contacts[num1]:
self.contacts[num1].add(num2)
self.counts[num1] += 1
def processLine(self, line):
num1, num2 = line.split('-')
self.addContact(num1, num2)
self.addContact(num2, num1)
def getHighestNumberOfContacts(self):
if not self.counts:
return 0
return max(self.counts.values())
def getNumberOfClusters(self):
numClusters = 0
visited = {c: False for c in self.contacts.keys()}
# Iterate through each number
for num in visited.keys():
# If not yet visited, traverse graph to visit all connected nodes
if not visited[num]:
visited[num] = True
numClusters += 1
# Construct queue
q = Queue()
for n in self.contacts[num]:
q.put(n)
# Traverse graph while queue is not empty
while not q.empty():
n = q.get()
visited[n] = True
for m in self.contacts[n]:
if not visited[m]:
q.put(m)
return numClusters
if __name__ == '__main__':
contactTracer = ContactTracer()
while True:
try:
line = input()
if line == 'Q1':
print(contactTracer.getHighestNumberOfContacts())
elif line == 'Q2':
print(contactTracer.getNumberOfClusters())
else:
contactTracer.processLine(line)
except:
break
|
def uneven_nums_gen(last_num):
for num in range(1, int(last_num) + 1, 2):
yield num
nums = uneven_nums_gen(input('Введите макс. значение генератора: '))
print(*nums)
|
"""
:type words: List[str]
:rtype: int
"""
words = ["gin", "zen", "gig", "msg"]
for x in range(97,123):
letter = chr(x)
alphabet = "" + letter
morseCode = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
dictionary = {}
iterator = 0
for x in range (97, 123):
letter = chr(x)
dictionary[letter] = morseCode[iterator]
iterator += 1
final = []
#convert
iterator = 0
for x in words:
word = ""
#append each character to the word
for y in x:
word += dictionary[y]
#if word is not in final then append
if word not in final:
final.append(word)
# reset the word
word = ""
print len(final)
|
# SOLUTION FOR QUESTION 5 BY ENG19CS0044
"""
5 A
Input :
3
1 2
2 2
8 7
2
3 3
4 4
So the error is that when the key does not exist in data 1, the key value pair is not added to it.
"""
# 5 B
def uniqueUpdate(data1, data2):
# Initially empty dictionary
dupKeys = {}
# Examine every (k, v2) pair in data2
for [k, v2] in data2:
# Check if there is a key-value pair with key = k in data1
if k in data1:
v1 = data1[k]
# (k, v1) in dict1 Check if v1 != v2
if v1 != v2:
# Add (k, [v1, v2]) to dictionary
dupKeys[k] = [v1, v2]
# Remove (k, v1) from data1
del data1[k]
else:
# Add (k, v2) to data1
data1[k] = v2
# After processing all (k, v2) in data2, return the dictionary
return dupKeys
## DO NOT MODIFY BELOW THIS LINE! ##
import sys
if name == 'main':
data1 = {}
n1 = int(input())
for _ in range(n1):
k, v = map(int, input().split())
if k in data1:
sys.exit("Illegal: data1")
data1[k] = v
data2 = []
n2 = int(input())
for _ in range(n2):
k, v = map(int, input().split())
for [k2, v2] in data2:
if k2 == k:
sys.exit("Illegal: data2")
data2.append([k, v])
dup = uniqueUpdate(data1, data2)
print(data1)
print(data2)
print(dup)
"""
5 C
Test Case 1
4
1 2
14 14
3 8
4 9
2
3 3
4 4
Test Case 2
4
1 2
2 2
3 3
4 19
2
3 3
4
1 9
Test Case 3
We can use the test case for 5A part
"""
|
"""
Desktop : Sudeep R Dodda
Date created : 09/15/2017
Description : Python script performs BLE advertisement scan and prints MAC address,
RSSI, Flags, UUID, Major, Minor and TX PWR.
Also defines two methods :
hexToInt(hexstr) & twos(hexstr) - commented later.
User inputs MAC address pattern used in BLE scan.
"""
from bluepy.btle import Scanner, DefaultDelegate
"""
##########################################################################
hexToInt(hexStr) - converts a hex string into its equivalent integer value
##########################################################################
"""
def hexToInt(hexstr):
hexSplit = [hexstr[2*i]+hexstr[2*i+1] for i in range(len(hexstr)/2)]
toBits = map(lambda x: "{0:08b}".format(int(x, 16)), hexSplit)
mergeBits = "".join(toBits)
bitsToInt = int(mergeBits, 2)
return bitsToInt
"""
#############################################################################
two(hexstr) - Performs two's complement on a hex string and returns the value
#############################################################################
"""
def twos(hexstr):
hexSplit = [hexstr[2*i]+hexstr[2*i+1] for i in range(len(hexstr)/2)]
toBits = map(lambda x: "{0:08b}".format(int(x, 16)), hexSplit)
compBits = ''
for i in toBits[0]:
if i == '0':
compBits += '1'
else:
compBits += '0'
return -1*(int(compBits,2)+1)
class ScanDelegate(DefaultDelegate):
def __init__(self):
DefaultDelegate.__init__(self)
"""def handleDiscovery(self, dev, isNewDev, isNewData):
if str(dev.addr)[0:4] == str("00:a"):
print "Found new LBeacon", dev.addr"""
BLEMac = raw_input("Enter the BLE mac address pattern: ")
scanner = Scanner().withDelegate(ScanDelegate())
devices = scanner.scan(1)
raw_data = []
for dev in devices:
if dev.addr[0:len(BLEMac)] == BLEMac:
print "Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi)
for (adtype, desc, value) in dev.getScanData():
if desc == "Flags":
a = value
elif desc == "Manufacturer":
b = value
UUID = b[8:16]+"-"+b[16:20]+"-"+b[20:24]+"-"+b[24:28]+"-"+b[28:40]
Major = hexToInt(b[40:44])
Minor = hexToInt(b[44:48])
TxPwr = twos(b[48:])
print "Flags\t=\t" + a
print "UUID\t=\t%s" %UUID
print "Major\t=\t%i" % Major
print "Minor\t=\t%i" % Minor
print "TX PWR\t=\t%idBs" % TxPwr
print "*********************************************************"
|
# Extracting Data from XML
# In this assignment you will write a Python program somewhat similar to http://www.pythonlearn.com/code/geoxml.py.
# The program will prompt for a URL, read the XML data from that URL using urllib and then parse and extract the
# comment counts from the XML data, compute the sum of the numbers in the file.
# We provide two files for this assignment. One is a sample file where we give you the sum for your testing and the
# other is the actual data you need to process for the assignment.
# Sample data: http://python-data.dr-chuck.net/comments_42.xml (Sum=2553)
# Actual data: http://python-data.dr-chuck.net/comments_243376.xml (Sum ends with 64)
# You do not need to save these files to your folder since your program will read the data directly from the URL.
# Note: Each student will have a distinct data url for the assignment - so only use your own data url for analysis.
# Data Format and Approach
# The data consists of a number of names and comment counts in XML as follows:
# <comment>
# <name>Matthias</name>
# <count>97</count>
# </comment>
# You are to look through all the <comment> tags and find the <count> values sum the numbers. The closest sample code
# that shows how to parse XML is geoxml.py. But since the nesting of the elements in our data is different than the
# data we are parsing in that sample code you will have to make real changes to the code.
# To make the code a little simpler, you can use an XPath selector string to look through the entire tree of XML for any
# tag named 'count' with the following line of code:
# counts = tree.findall('.//count')
# Take a look at the Python ElementTree documentation and look for the supported XPath syntax for details. You could also work
# from the top of the XML down to the comments node and then loop through the child nodes of the comments node.
# Sample Execution:
# $ python solution.py
# Enter location: http://python-data.dr-chuck.net/comments_42.xml
# Retrieving http://python-data.dr-chuck.net/comments_42.xml
# Retrieved 4204 characters
# Count: 50
# Sum: 2...
from urllib.request import urlopen
import xml.etree.ElementTree as ET
url = input('Enter location: ')
print ('Retrieving', url)
uh = urlopen(url)
data = uh.read()
print ('Retrieved',len(data),'characters')
tree = ET.fromstring(data)
lst = tree.findall('comments/comment')
print ('Count:', len(lst))
#print (lst)
total = 0
for item in lst:
num = int(item.find('count').text)
total = total + num
print ("Sum:", total)
|
##Write a function called middle that takes a list and returns a new list that
##contains all but the first and last elements.
mylist = [1,2,3,4]
def middle(mylist):
leng = len(mylist)
mylist.pop(leng-1)
mylist.pop(0)
return mylist
print (middle(mylist))
|
# The program prompts for a web address, then opens the web page, reads the data
# and passes the data to the BeautifulSoup parser, and then retrieves all of the
# anchor tags and prints out the href attribute for each tag.
# To run this, you can install BeautifulSoup
# https://pypi.python.org/pypi/beautifulsoup4
# Or download the file
# http://www.pythonlearn.com/code3/bs4.zip
# and unzip it in the same directory as this file
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
url = input('Enter - ')
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html, 'html.parser')
# Retrieve all of the anchor tags
tags = soup('a')
for tag in tags:
print(tag.get('href', None))
# Code: http://www.pythonlearn.com/code3/urllinks.py
|
##Write another program that prompts for a list of numbers as above
##and at the end prints out both the maximum and minimum of the numbers instead
##of the average.
count = 0
total = 0
max_num = None
min_num = None
while True:
inp = input('Enter a number: ')
if inp == 'done':
print (count, max_num, min_num)
break
try:
inp = float(inp)
count = count + 1
if max_num is None or inp > max_num:
max_num = inp
if min_num is None or inp < min_num:
min_num = inp
except:
print ('Invalid input')
continue
|
##Write a program to prompt the user for hours and rate per hour to
##compute gross pay.
hrs = input('Enter hours: ')
rate = input('Enter rate: ')
hrs = float(hrs)
rate = float(rate)
Pay = hrs*rate
print (Pay)
|
def factorize(num):
factors = []
for i in range(1,num/2+1):
if i > num / i:
break
if num % i == 0:
factors.append(i)
if num/i != i:
factors.append(int(num/i))
return sorted(factors)
def triangle_number_generator():
tri = 1
inc = 2
while True:
yield tri
tri = tri + inc
inc = inc + 1
for t in triangle_number_generator():
if len(factorize(t)) > 500:
print(t)
break
|
def max_solutions_for_triangle_perimeter_range(max_perimeter):
"""Returns the perimeter p that has the most integral side solutions for right triangles, for p <= max_perimeter"""
import euler009
import functools
perimeter_solutions = []
for p in range(1, max_perimeter+1):
perimeter_solutions.append((p,len(euler009.find_py_triples(p))))
def max_solutions_perimeter(a,b):
if a[1] > b[1]:
return a
return b
return functools.reduce(max_solutions_perimeter, perimeter_solutions)[0]
ans = max_solutions_for_triangle_perimeter_range(1000)
|
import math
import fractions
def find_closest_smaller_fraction(max_denom, target_fraction):
target_n,target_d = target_fraction
frac = target_n/target_d
ans = 0
for d in range(2,max_denom+1):
absolute = d * frac
min_num = math.floor(absolute)
max_num = math.ceil(absolute)
#print(absolute,min_num,max_num,'out of',d)
for n in range(min_num, max_num):
if n/d < frac:
ans = max(fractions.Fraction(n,d),ans)
return ans
ans = find_closest_smaller_fraction(1000000,(3,7)).numerator
|
def sqrt_two_gen(iterations):
d,n = 3,2
for i in range(iterations):
yield d,n
d,n = n + n + d, n + d
yield d,n
ans = sum([1 for n,d in sqrt_two_gen(1000) if len(str(n)) > len(str(d))])
|
x = int(input("please enter valid input x"))
if(x <0):
print("x is negative number")
elif(x >0):
print("x is positive number")
elif(x==0):
print("x is equal to zero ")
else:
print("x is not defined ")
if True:
print("PASS")
else:# dead code , never come inside
print("FAIL")
a = 100
b= 200
c= 400
if a >b and a >c:
print(" a is the biggest number")
elif b>c:
print("b is the biggest number")
elif a<c:
print("c is the biggest number")
y = int(input("please enter value of y "))
if(y >0):
print("y is positive number ")
print(y)
total= int(input("please enter total value"))
if(total< 100):
total = total + 20
elif(total>= 100 and total <= 400):
total= total + 100
else:
total = total+ 200
print("total=" + str(total)) # this is called str method
print(f'{"total value ="}{total}') # this is called f String formula
print(total) # must put in the specific line
|
name = "Avery"
subjects = ["English", "Science", "Math", "History", "French"]
print ("My name is " + name)
for i in subjects:
print("I take " + i + " as one of my classes.")
placesilove = ["Paris", "Punta Mita", "Gordes", "NYC", "Palm Beach", "Nantucket", "Cassis", "Fairlee", "Venice", "Croatia", "Nassau", "Greenwich"]
for i in placesilove:
if i == "Gordes":
print("Gordes is where I live part of the year")
elif i == "Greenwich":
print("Greenwich is where I live during the school year.")
foods = []
while True:
print("What are your favorite foods? Type 'end' to stop program")
answer = input()
if answer == "end":
break
else:
foods.append (answer)
for i in foods:
print (i + " is one of your favborite foods.")
|
#Lase kasutajal sisestada arvud ning salvesta need muutujasse, samuti muuda kohe stringid numbriteks - int()
number1 = int(input("Sisesta esimene number: "))
number2 = int(input("Sisesta teine number: "))
number3 = int(input("Sisesta kolmas number: "))
#kasutan andmetüüpi "array", et salvestada numbrid üheks muutujaks
numberArray = [number1, number2, number3]
#lisan summa funktsiooni "numberArray" listile ja salvestan need muutujasse "summary"
summary = sum(numberArray)
#kasutan tingimuslauset, et kontrollida, kas sisestatud andmed on võrdsed(tõene) või ei ole võrdsed(väär)
#kui tingimus on õige, siis prindi välja numbrite korrutis
if number1 == number2 and number1 == number3:
print((number1 * number2) * number3)
#kui tingimus on väär, siis prindi välja muutuja "summary", kus me tegime liitmise juba ära
else:
print(summary)
|
arr = [1, 23,3 ,434,54,545,65,54,54,45,23,54,23]
arr_1 = set(arr)
from collections import Counter
def counter(arr):
return Counter(arr).most_common(len(arr_1)) if Counter(arr).most_common(len(arr_1)) else None
for x in counter(arr):
print('{}出现的次数为{}'.format(x[0], x[1]))
|
from nltk.corpus import names
from nltk import NaiveBayesClassifier
from nltk import classify
from nltk import accuracy
from nltk import DecisionTreeClassifier
from nltk.classify.svm import SvmClassifier
import sklearn.svm
import random
import nltk
nltk.download('names')
gender = [(n,'Male') for n in names.words('male.txt')] + [(name,'FeMale') for name in names.words('female.txt')]
random.shuffle(gender)
gender_feature = lambda word: {'feature-set':word[-1]}
# The Above function is the same as
#def gender_feature(word):
#determine if a word is Gender or not
#this will return a feature-set or result-set or training-set
#the Last Letter of the Word.
# Next, we use the feature extractor to process the names data, and
# divide the resulting list of feature sets into a training set
# The training set is used to train a new "naive Bayes" classifier.
featuresets = [(gender_feature(name), predictor) for (name, predictor) in gender]
trainingSet, testSet = featuresets[500:], featuresets[0:500]
# print(featuresets)
# # print(trainingSet)
# # print(testSet)
name = input('Enter a Name:')
classifiers = int(input('Enter a Classifier:\n1:Naive Bayes Classifier\n2: Decision Tree\n3: Support Vector machine (SVM)'))
accuracies = []
trainNaiveBaseClassifier = lambda data: NaiveBayesClassifier.train(data)
decisionTreeBaseClassifier = lambda decision: DecisionTreeClassifier.train(decision)
supportVectorMachine = lambda svm: classify.SklearnClassifier(LinearSVC())
if classifiers == 1:
# naiveClassifier = NaiveBayesClassifier.train(trainingSet)
naiveBayesClassifier = trainNaiveBaseClassifier(trainingSet)
n =naiveBayesClassifier.classify(gender_feature(name))
print('*'*80)
print('Naive Bays Classifier')
print('*' * 80)
print(naiveBayesClassifier.show_most_informative_features())
#test the accuracy of the classifier using Naive Bayes
# Observe that these character names from The Matrix are correctly classified. Although this science fiction movie
# is set in 2199, it still conforms with our expectations about names and genders. We can systematically evaluate
# the classifier on a much larger quantity of unseen data:
#computing Accuracy:
naive_accuracy = classify.accuracy(naiveBayesClassifier, testSet)
accuracies.append(('Naive Bayes : ', naive_accuracy))
print('Naive Accuracy = ', naive_accuracy)
elif classifiers == 2:
# Decision tree learning is one of
# decision_tree = DecisionTreeClassifier.train(trainingSet)
decisionTree = decisionTreeBaseClassifier(trainingSet)
classifyDecisionTree =decisionTree.classify(gender_feature(name))
decision_tree_accuracy = classify.accuracy(decisionTree, testSet)
accuracies.append(('Decision Tree Accuracy : ', decision_tree_accuracy))
print('decision Tree Accuracy = ',decision_tree_accuracy,':', decisionTree)
print('*'*80)
elif classifiers == 3:
pass
# print('*'* 80)
# # Note
# # nltk.classify.svm was deprecated.For classification based on support vector
# # machines SVMs use nltk.classify.scikitlearn( or scikit - learn directly).For more details NLTK 3.0 documentation
# classifier = classify.SklearnClassifier(LinearSVC())
# classifier.train(trainingSet)
# c = classifier.classify(gender_feature(name))
# accuracy = classify.accuracy(classifier, testSet)
# print('Prediction:',name,' = ',c, 'Accuracy : ', accuracy)
# print('*'*80)
#
|
a=2
b=3
c=4
if b<a:
print("é menor")
elif a==b:
print("é igual")
else:
print("é maior")
print("è menor") if a < b else print("E maior")
if(a<b) and (b!=c):
print("Ok")
if(a<b) or (b!=c):
print("Não")
while(c<10):
print("Aumentando c")
c=c+1
minhaLista=["eu","realdo","justino"]
for x in minhaLista:
print("quem", x)
for x in "realdo":
print(x)
for x in range(5):
print(x)
for x in range(2,5):
print(x)
for x in range(5,50,5):
print(x)
|
def get_weight_kg_of_plastic(plastic_type):
if plastic_type == "film":
return 0.01
elif plastic_type == "textiles":
return 0.1
elif plastic_type == "rigid beverage container":
return 0.2
elif plastic_type == "rigid non-beverage container":
return 0.3
elif plastic_type == "other":
# TODO How do we decide the weight of "Other"
return 0.01
|
# -*- coding: utf-8 -*-
def select_unassigned_variable(csp):
"""Selects the next unassigned variable, or None if there is no more unassigned variables
(i.e. the assignment is complete).
For P3, *you do not need to modify this method.*
"""
return next((variable for variable in csp.variables if not variable.is_assigned()))
def order_domain_values(csp, variable):
"""Returns a list of (ordered) domain values for the given variable.
For P3, *you do not need to modify this method.*
"""
return [value for value in variable.domain]
def inference(csp, variable):
"""Performs an inference procedure for the variable assignment.
For P3, *you do not need to modify this method.*
"""
return True
def is_complete(csp):
"""Returns True when the CSP assignment is complete, i.e. all of the variables in the CSP have values assigned."""
variables = csp.variables
for variable in variables:
if not variable.is_assigned():
return False
return True
def is_consistent(csp, variable, value):
"""Returns True when the variable assignment to value is consistent, i.e. it does not violate any of the constraints
associated with the given variable for the variables that have values assigned.
For example, if the current variable is X and its neighbors are Y and Z (there are constraints (X,Y) and (X,Z)
in csp.constraints), and the current assignment as Y=y, we want to check if the value x we want to assign to X
violates the constraint c(x,y). This method does not check c(x,Z), because Z is not yet assigned."""
for constraint in csp.constraints[variable]:
if constraint.var2.is_assigned():
if not constraint.is_satisfied(value,constraint.var2.value):
return False
return True
def backtracking_search(csp):
"""Entry method for the CSP solver. This method calls the backtrack method to solve the given CSP.
If there is a solution, this method returns the successful assignment (a dictionary of variable to value);
otherwise, it returns None.
For P3, *you do not need to modify this method.*
"""
if backtrack(csp):
return csp.assignment
else:
return None
def backtrack(csp):
"""Performs the backtracking search for the given csp.
If there is a solution, this method returns True; otherwise, it returns False.
"""
# TODO implement this
if is_complete(csp)==True:
return True
unassigned=select_unassigned_variable(csp);
for i in order_domain_values(csp,unassigned):
if is_consistent(csp, unassigned, i)==True:
csp.variables.begin_transaction()
unassigned.assign(i)
csp.assignment[unassigned]=i
if backtrack(csp)==True:
return True
else:
csp.variables.rollback()
return False
|
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 13 15:18:31 2018
@author: RV
"""
class Car(object):
def __init__(self,position,direction):
self.position = position
self.direction = direction
self.crossMode = 0
self.alive = True
def __lt__(self, other):
return self.position[1] < other.position[1]
def getCar(self):
return self.position, self.direction, self.crossMode, self.alive
def getPosition(self):
return self.position
def setCar(self,position,direction,mode, isAlive):
self.position = position
self.direction = direction
self.crossMode = mode
self.alive = isAlive
def setIsAlive(self, isAlive):
self.alive = isAlive
def isAlive(self):
return self.alive
# update position 这是一个tick
def updatePosition(cars, trackMap):
roadCornor = ['\\','/','+']
for car in cars:
position,direction, crossMode, isAlive = car.getCar()
# 更新位置
position = [position[0] + direction[0], position[1]+direction[1]]
# 更新方向
rodState = trackMap[position[1]][position[0]]
if rodState in roadCornor:
if rodState == '\\':
direction[0], direction[1] = direction[1], direction[0]
elif rodState == '/':
direction[0], direction[1] = -direction[1], -direction[0]
elif rodState == '+':
if crossMode == 0 :
direction[0], direction[1] = direction[1], -direction[0]
elif crossMode == 2:
direction[0], direction[1] = -direction[1], direction[0]
crossMode = (crossMode+1) % 3
# 设置状态
car.setCar(position,direction,crossMode,isAlive)
# collsiion detection
def collisionDetection(cars, trackMap):
for index in range(len(cars)-1):
position1= cars[index].getPosition()
#print(position1)
for cp in range(index+1, len(cars)):
position2 = cars[cp].getPosition()
# print(position2)
if position1 == position2:
#print ("Collision pos: ", position1)
cars[index].setIsAlive(False)
cars[cp].setIsAlive(False)
siezAliveCars = len(cars)
for car in cars:
if not car.isAlive():
siezAliveCars -= 1
return siezAliveCars == 1
def main():
file = open("day13.txt","r")
direction = ['>','<','v','^']
trackMap = list()
cars = list()
row = 0
column = 0
for line in file:
trackMap.append(line.strip('\n'))
column = 0
for d in line:
if d in direction:
d = {'>':[1,0],'<':[-1,0],'v':[0,1],'^':[0,-1]}[d]
cars.append(Car([column,row],d))
column += 1 # j column
row +=1 # i row
cars.sort()
collision = False
tick = 0
while not collision:
collision = collisionDetection(cars, trackMap)
if collision :
for car in cars:
if car.isAlive():
print(car.getPosition())
break
else:
updatePosition(cars, trackMap)
tick += 1
if __name__ == '__main__':
main()
|
num1 = int(input("Enter 1st number:"))
num2 = int(input("Enter 2nd number:"))
def num_checker(num1,num2):
total = num1 + num2
if num1 == 3 or num2 == 3:
if '3' in str(total):
return True
else:
return False
else:
return False
print(num_checker(num1,num2))
|
class Controller:
'''
The Controller class is abstract class for implement basic command to play
MOBA game.
'''
pass
class HeroItem(Controller):
'''
Control hero about item.
Example:
1.Hero item using.
2.Hero item selling.
3.Hero item buying.
4.Hero item checking type item.
'''
def buy_cheap_item(self,item_list):
'''
Control hero to buy item which cheapest in item_list and hero can
buy. If hero can't buy it, this method will not buy and operate
next Instruction.
'''
pass
def buy_expensive_item(self,item_list):
'''
Control hero to buy item which most expensive in item_list and hero can
buy. If hero can't buy it, this method will not buy and operate
next Instruction.
'''
pass
def buy_item_order(self,item_list):
'''
Control hero to buy respectively item which in item_list and hero can
buy. If hero can't buy it, this method will not buy and operate
next Instruction.
'''
pass
def sell_item(self,item):
'''
Control hero to sell item which hero possess.
'''
pass
class Moving(Controller):
'''
Controlle hero about moving.
Example:
1.Hero move to required position.
2.Hero move to the base.
3.Hero stop moving.
'''
def move_hero(self,x,y):
'''
Control hero move to required position x and y.
'''
pass
def move_to_base(self):
'''
Control hero move to own base.
'''
pass
def stop_moving(self):
'''
Control hero stop moving.
'''
pass
class SkillUsing(Controller):
'''
Control hero about skill using.
Example:
1.hero using the skill which can use in the moment time.
2.hero using the damaged skill.
3.hero using the support skill.
4.hero using the *escape skill.
5.hero using order skill.
*escape skill about change position the hero
'''
def use_skill(skill):
pass
def order_using__skill():
pass
def order_upgrade_skill():
pass
class Attacking(Controller):
'''
Control hero about attacking.
'''
def SelectTarget(self,enemy):
'''
Control hero lock on target for attack.
'''
pass
def SelectTargetLowHp(self):
'''
This method find enemy which have lowest Hp in enemy list to be the target.
The enemy list is list of enemy which in the vision of hero.
'''
pass
def SelectTargetHightHp(self):
'''
This method find enemy which have highest Hp in enemy list to be the target.
The enemy list is list of enemy which in the vision of hero.
'''
pass
def SelectNearTarget(self):
'''
This method find nearest enemy to be the target.
'''
pass
|
"""
Draw a call stack for the Tower of Hanoi problem.
Assume that you start with a stack of three disks.
缺陷:不能显示栈的内容 只能显示数目
改进:可用list模拟栈
"""
from pythonds.basic.stack import Stack
#print('请输入汉诺塔的层数')
#N = int(input())
N = 3
global A, B, C, step
A = Stack()
B = Stack()
C = Stack()
x = []
step = 0
lst = list(range(1, N + 1))
lst.reverse()
for i in lst:
A.push(i)
print(A.size())
def tower(s1, s2, s3, N=-1): # 汉诺塔算法,借助s2,将s1的N层移动到s3
global step
if(N == -1):
N = s1.size()
if(N == 0):
return
elif(N == 1): # 判断栈的深度,如果栈深为1,则一次简单移动即可;若大于1,则需要进行递归操作
#move(s1, s3)
moveDisk(s1,s3)
s3.push(s1.pop())
print('%-20s %-20s %-20s' % (A.size(), B.size(), C.size())) # 为了方便展示结果,输出语句做了调整
step += 1
else:
tower(s1, s3, s2, N-1) # 从s1移到s2
#move(s1, s3)
moveDisk(s1,s3)
s3.push(s1.pop())
print('%-20s %-20s %-20s' % (A.size(), B.size(), C.size()))
step += 1
tower(s2, s1, s3, N-1) #从s2移到s3
return
def moveDisk(fromPole,toPole):
print('moving disk from',fromPole.size(),'to',toPole.size())
print(tower(A, B, C))
print('所需步数为%d' % step)
|
#Number guessing game
import random
salaNumero=random.randint(1, 20)
print('Arvaa oikein numero 1 ja 20 välillä')
#arvuutetaan kuusi kertaa
for arvaukset in range(1, 7):
print('Arvaa')
try:
arvaus=int(input())
if arvaus == salaNumero:
print('Oikein!')
print('Käytit ' + str(arvaukset) + ' arvausta.')
break
elif arvaus < salaNumero:
print('Vähän alakanttiin')
elif arvaus > salaNumero:
print('Liikaa')
except ValueError:
print('Kokeile numeroa')
if arvaus != salaNumero:
print('Et arvannut oikein')
|
data = raw_input("enter input: ")
a = data.split()
s = set(a)
data1 = list(s)
#print(data1)
output = sorted(data1)
print(output)
|
name1string = input("pls enter first name : ")
namestring = input("pls nter last name : ")
print(name1string[::-1] +" " + namestring[::-1])
a = int(input("enter first number: "))
b = int(input("enter second number: "))
sum = a + b
diff = a - b
mul = a * b
div = a / b
rem = a % b
print("sum:", sum)
print("diff:", diff)
print("mul:", mul)
print("div:", rem)
string = input("pls enter string : ")
digits=letters=0
for c in string:
if c.isdigit():
digits=digits+1
elif c.isalpha():
letters=letters+1
else:
pass
print("Letters", letters)
print("Digits", digits)
|
"""
Player class represents a player of the game
"""
class Player:
def __init__(self, name = "", totalMoney = 16):
self.name = name
self.totalMoney = totalMoney
self.currentPos = 0 # Each players current position represented as an index of the square the player is currently on
def getName(self):
return self.name
def getTotalMoney(self):
return self.totalMoney
def earnMoney(self, amt):
if ( amt >= 0 ):
self.totalMoney += amt
def spendMoney(self, amt):
if ( amt >= 0 ):
self.totalMoney -= amt
def setTotalMoney(self, amt):
self.totalMoney = amt
def isBankrupt(self):
return self.totalMoney <= 0
def getCurrPos(self):
return self.currentPos
def setCurrPos(self, index):
self.currentPos = index
def __repr__(self):
return "Name: " + self.name + ", Total Money: $" + str(self.totalMoney) + ", Current Position: " + str(self.currentPos)
def __eq__(self, other):
if other is None:
return False
return self.name == other.name and self.totalMoney == other.totalMoney and self.currentPos == other.currentPos
|
def partition(arr, low, high):
i = low - 1
pivot = arr[high]
for j in range(low, high):
if arr[j] < pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
def quickSort(arr, low, high):
if low < high:
pivot = partition(arr, low, high)
quickSort(arr, low, pivot - 1)
quickSort(arr, pivot + 1, high)
def display(arr):
for i in range(0, len (arr)):
print(arr[i], end= " ")
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
print("Unsorted Array")
display(arr)
print()
quickSort(arr, 0, len(arr) - 1)
print("Sorted Array")
display(arr)
print()
|
def CountSort(arr, expElem):
size = len(arr)
output = [0] * size
count = [0] * 10
for i in range(0, size):
index = (arr[i] // expElem)
count[int(index % 10)] += 1
for i in range(1, 10):
count[i] += count[i - 1]
i = size - 1
for i in range(size -1, -1, -1):
index = arr[i] // expElem
output[count[int(index % 10)] - 1] = arr[i]
count[int(index % 10)] -= 1
for i in range(0, size):
arr[i] = output[i]
def RadixSort(arr):
maxElem = max(arr)
exp = 1
while maxElem // exp > 0:
CountSort(arr, exp)
exp *= 10
def display(arr):
for i in range(len(arr)):
print(arr[i], end = " ")
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
print("Unsorted Array")
display(arr)
print()
RadixSort(arr)
display(arr)
print()
|
def ShellSort(arr):
size = len(arr)
gap = size // 2
while gap > 0:
for i in range(gap, size):
temp = arr[i]
j = i
while j >= gap and arr[j - gap] > temp:
arr[j] = arr[j - gap]
j -= gap
arr[j] = temp
gap //= 2
def display(arr):
for i in range(len(arr)):
print(arr[i], end = " ")
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
print("Unsorted Array")
display(arr)
print()
ShellSort(arr)
display(arr)
print()
|
def InsertionSort(arr):
size = len(arr)
for i in range(1, size):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j = j - 1
arr[j + 1] = key
def display(arr):
for i in range(len(arr)):
print(arr[i], end = " ")
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
print("Unsorted Array")
display(arr)
print()
InsertionSort(arr)
print("Sorted Array")
display(arr)
print()
|
#words = ["Lol", "Kek", "Cheburek"]
#print(sum(words))
#how work sum
# a=[1,2,3]
# temp = 0
# temp+=a[0]
# temp+=a[1]
# temp+=a[2]
x1= int(input())
y1= int(input())
x2= int(input())
y2= int(input())
if (x1+2 == x2 and y1+1==y2) or (x1+2 == x2 and y1-1==y2) or (x1-2 == x2 and y1+1==y2) or (x1-2 == x2 and y1-1==y2) or (x1+1 == x2 and y1+2==y2) or (x1+1 == x2 and y1-2==y2) or (x1-1 == x2 and y1+2==y2) or (x1-1 == x2 and y1-2==y2):
print("YES")
else:
print("NO")
|
#! /usr/bin/env python
# This converts a binary file into a text file written in hexadecimal with each
# byte on a single line.
# This is used to initialize memory.
#
# Usage: ./bin2hex.py <source> <dest>
import sys
infilename = sys.argv[1]
outfilename = sys.argv[2]
result = []
a = open(infilename, "rb")
for c in a.read():
h = format(ord(c), '02x')
result.append(h)
a.close()
fl = open(outfilename, "w")
for i in result:
fl.write(i+"\n")
fl.close()
|
#####
# bouncing_ball.py
#
# Creates a Scale and a Canvas. Animates a circle based on the Scale
# (c) 2013 PLTW
# version 11/1/2013
####
import Tkinter #often people import Tkinter as *
#####
# Create root window
####
root = Tkinter.Tk()
#####
# Create Model
######
speed_intvar = Tkinter.IntVar()
speed_intvar.set(3) # Initialize y coordinate
# radius and x-coordinate of circle
r = 10
x = 150
y = 150
direction = 0.5 # radians of angle in standard position, ccw from positive x axis
######
# Create Controller
#######
# Instantiate and place slider
speed_slider = Tkinter.Scale(root, from_=5, to=1, variable=speed_intvar,
label='speed')
speed_slider.grid(row=1, column=0, sticky=Tkinter.W)
# Create and place directions for the user
text = Tkinter.Label(root, text='Drag slider \nto adjust\nspeed.')
text.grid(row=0, column =0)
######
# Create View
#######
# Create and place a canvas
canvas = Tkinter.Canvas(root, width=600, height=600, background='#FFFFFF')
canvas.grid(row=0, rowspan=2, column=1)
# Create a circle on the canvas to match the initial model
circle_item = canvas.create_oval(x-r, y-r, x+r, y+r,
outline='#000000', fill='#00FFFF')
import math
def animate():
# Get the slider data and create x- and y-components of velocity
velocity_x = speed_intvar.get() * math.cos(direction) # adj = hyp*cos()
velocity_y = speed_intvar.get() * math.sin(direction) # opp = hyp*sin()
# Change the canvas item's coordinates
canvas.move(circle_item, velocity_x, velocity_y)
# Get the new coordinates and act accordingly if ball is at an edge
x1, y1, x2, y2 = canvas.coords(circle_item)
global direction
# If crossing left or right of canvas
if x2>canvas.winfo_width() or x1<0:
direction = math.pi - direction # Reverse the x-component of velocity
# If crossing top or bottom of canvas
if y2>canvas.winfo_height() or y1<0:
direction = -1 * direction # Reverse the y-component of velocity
# Create an event in 1 msec that will be handled by animate(),
# causing recursion
canvas.after(1, animate)
# Call function directly to start the recursion
animate()
#######
# Event Loop
#######
root.mainloop()
|
def mouse(x,y):
if x > 20 and x < 100 and y > 20 and y <100:
return "YAY you're smart"
else:
return "Try again"
def report_grade(percent):
if percent >= 80:
return "mastery"
else:
return "get good"
def vowel(guess,word):
if guess in word:
return "correct"
else:
return "wrong"
def hint(color):
secret = ['red','red','yellow','yellow','black']
if color in secret:
return "That color is in the secret sequence of colors."
else:
return "That color is NOT in the secret sequence of colors."
|
# Topic : what are the words used in bad reviews.
# For this research, you could add more juicy explorations such as
# "among the common bad words used in bad reviews, what are those worst words, and what are not that bad".
# To achieve this purpose, you could do a text classification to predict bad reviews using the
# existence of the bad words and report the most informative features.
import pandas as pd
import os
from textblob import TextBlob
import nltk
import nltk.data
from nltk.corpus import stopwords
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import string
from nltk.tokenize import word_tokenize
import re
import matplotlib.pyplot as plt
# 1. LOADING DATA CSV
path = 'C:/Users/Suchitra/Desktop/MSBA Subjects/BAN 675 Text Mining/Group Project'
os.chdir(path)
reviews = pd.read_csv('reviews.csv')
# 2. DATA PRE-PROCESSING
stop_words=stopwords.words("english")
def clean_text(text):
words=word_tokenize(text)
# lower case text, remove stop words, punctuations, check if alphabet
text = [word.lower() for word in words if word not in stop_words and word not in string.punctuation and word.isalpha()]
# remove words with only one letter
text = [t for t in text if len(t) > 1]
# join all
text = " ".join(text)
return(text)
# 3. DATA EXPLORATION
# Extract only the negative reviews
def sentiment_analysis(text):
review = TextBlob(text)
analyzer=SentimentIntensityAnalyzer() # Analyzing the intensity of the bad review
sent=analyzer.polarity_scores(review)
if sent['compound']<0: # bad review
return text
# Extract ajdectives from each bad review
def tag_adjectives(text):
words=nltk.word_tokenize(text)
tagged=nltk.pos_tag(words)
adjectives=[x for x,y in tagged if re.search('JJ',y) or re.search('JJR', y) or re.search('JJS', y)]
return(adjectives)
# Perform sentiment analysis for the first 500 reviews
adj = []
bad_words = []
all_bad_words = []
word_list = []
with open('negative-words.txt','r') as f:
all_bad_words = f.read().splitlines() # bad words reference
for i in range(0,100000): #10,000 rows
review = clean_text(reviews['text'][i]) # returns processed data
neg = sentiment_analysis(review) # returns the negative review words
if neg != None:
adj = tag_adjectives(neg) # contains all adjectives used in a review
bad_words = [bad for bad in adj if bad in all_bad_words]
word_list.append(bad_words) # This is a list of lists --> [[], [], []]
# Converting list of lists into a flat list containing all the bad words in the review csv
words_list = []
for sublist in word_list:
for item in sublist:
words_list.append(item)
a = set(words_list) # extracting only the unique bad words
words_list = list(a) # converting the set back to a list
print(words_list)
# Assigning negativity score to each bad word based on the star rating
negativity_score = {}
for word in words_list:
for i in range(0,100000):
if word in reviews['text'][i]:
a = []
a.append(reviews['stars'][i])
negativity_score[word] = (max(set(a), key = a.count)) # Storing the star rating (i.e negativity score)
# corresponding to each bad word
# Printing the bad word and how bad/negative each word is
for word in negativity_score:
print(word,negativity_score[word]) # {"bad_word":negativity score}
with open('Negativity_Score.txt','w') as f:
for word in negativity_score:
str_write = ''
str_write = word + ' : '+ str(negativity_score[word])+'\n'
f.write(str_write)
#####################################################################
r = clean_text(reviews['text'][223])
rr = TextBlob(r)
analyzer=SentimentIntensityAnalyzer() # Analyzing the intensity of the bad review
sent=analyzer.polarity_scores(rr)
print(tag_adjectives(r))
|
"""
给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。
字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
示例 1:
s = "abc", t = "ahbgdc"
返回 true.
示例 2:
s = "axc", t = "ahbgdc"
返回 false.
后续挑战 :
如果有大量输入的 S,称作S1, S2, ... , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码?
"""
import unittest
def is_sub_sequence(s, t):
st = t
for i in s:
if i not in st:
return False
st = st[st.index(i)+1:]
return True
class IsSubSequenceTestCase(unittest.TestCase):
def test_is_sub_sequence(self):
self.assertEqual(is_sub_sequence("abc", "ahbgdc"), True)
def test_is_sub_sequence1(self):
self.assertEqual(is_sub_sequence("axc", "ahbgdc"), False)
def test_is_sub_sequence2(self):
self.assertEqual(is_sub_sequence("acb", "ahbgdc"), False)
if __name__ == '__main__':
unittest.main()
|
"""
Input:5
Output: True
Explanation: 1*1 + 2*2
"""
def judgeSquareSum(number):
i, j = 0, number
while i <= j:
now = i*i + j*j
if now == number:
return True
elif now < number:
j -= 1
else:
i += 1
return False
|
import unittest
def fib(num :int) -> int:
if num == 0:
return 0
if num == 1:
return 1
fib_n_minus_one = 1
fib_n_minus_two = 0
fib_n = 0
for i in range(num-1):
fib_n = fib_n_minus_one + fib_n_minus_two
fib_n_minus_two = fib_n_minus_one
fib_n_minus_one = fib_n
return fib_n
class TestFib(unittest.TestCase):
def test_fib(self):
self.assertEqual(fib(1), 1)
self.assertEqual(fib(1), 1)
self.assertEqual(fib(1), 1)
self.assertEqual(fib(1), 1)
self.assertEqual(fib(1), 1)
if __name__ == "__main__":
unittest.main()
|
class TreeNode(object):
def __init__(self, name=None, parent=None, child=None, data=None):
super(TreeNode, self).__init__()
self.name = name
self.parent = parent
self.child = child if child else dict()
self.data = data
def get_child(self, name, defval=None):
return self.child.get(name, defval)
def add_child(self, name=None, edge=None, data=None, obj=None):
if obj and not isinstance(obj, TreeNode):
raise ValueError('TreeNode only add another TreeNode obj as child')
if not (name or edge):
raise ValueError('TreeNode must have a name or edge_name to put in childs')
if obj is None:
obj = TreeNode(name, data=data)
obj.parent = self
self.child[edge if edge else name] = obj
return obj
def del_child(self, name):
if name in self.child:
del self.child[name]
def find_child(self, path, create=False):
# convert path to a list if input is a string
path = path if isinstance(path, list) else path.split()
cur = self
for sub in path:
# search
obj = cur.get_child(sub)
if obj is None and create:
# create new node if need
obj = cur.add_child(sub)
# check if search done
if obj is None:
break
cur = obj
return obj
def is_leaf(self):
return len(self.child) == 0
|
# reference:-https://www.geeksforgeeks.org/python-program-to-create-bankaccount-class-with-deposit-withdraw-function/
class bankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit(self):
amount = float(input("Enter amount to be deposited: "))
self.balance += amount
print("\n Amount Deposited: ", amount, " and your balance: ", self.balance)
def withdraw(self):
amount = float(input("enter amount to be withdrawn: "))
if self.balance >= amount:
self.balance -= amount
print("\n You Withdraw: ", amount)
else:
print("Insufficient funds ")
def dispaly(self):
print("\n Net Available Balance", self.balance)
a = "a"
b = 10000
s = bankAccount(a, b)
s.deposit()
s.withdraw()
s.dispaly()
|
# -*- coding: utf-8 -*-
'''
Coral
Python 1 - DAT-119
Dice roller module example
'''
import random
def d4():
"""gives us a random number from 1-4"""
return random.randint(1, 4)
def d6():
"""gives us a random number from 1-6"""
return random.randint(1, 6)
def d8():
"""gives us a random number from 1-8"""
return random.randint(1, 8)
def d10():
"""gives us a random number from 1-10"""
return random.randint(1, 10)
def d12():
"""gives us a random number from 1-12"""
return random.randint(1, 12)
def d20():
"""gives us a random number from 1-20"""
return random.randint(1, 20)
def main():
print("4-sided die:", d4())
print("6-sided die:", d6())
print("8-sided die:", d8())
print("10-sided die:", d10())
print("12-sided die:", d12())
print("20-sided die:", d20())
if __name__ == "__main__":
main()
|
print("Giá căn nhà dự án 1")
d = float(input())
r = float(input())
print("Dài = ", str(d))
print("Rộng = ", str(r))
s = round(float(d) * float(r),2)
print("Diện tích = " + str(s))
print("---")
print("Nhập Công thức tính tiền mua nhà từ diện tích và giá nhà đã cung cấp: ")
print("Nhập giá nhà mặt tiền Quận 9: ")
p_q9 = float(input())
print("Giá nhà mặt tiền Quận 9: " + str(p_q9) + " triệu đồng/m2")
price = s * float(p_q9)
print("Số tiền mua nhà: " + str(price) + " triệu đồng")
print("---")
print("Thời gian hoàn vốn: ")
print("Nhập thu nhập hàng tháng cho dự án 1")
income = input()
print("Thu nhập cho thuê hàng tháng: " + str(income) + " triệu đồng")
Ttháng = round(float(price) / float(income),2)
print("Thời gian hoàn vốn tính theo tháng: " + str(Ttháng) + " tháng")
Tnăm = round((int(price) / (int(income) * 12)), 0)
print("Thời gian hoàn vốn tính theo năm: " + str(Tnăm) + "năm")
print("---")
print("Giá căn nhà dự án 2")
print("Nhập thu nhập hàng tháng cho dự án 2")
income2 = input()
print("Thu nhập hàng tháng cho dự án 2: " + str(income2) + " triệu đồng")
print("Nhập thời gian hoàn vốn dự tính")
Time2 = input()
print("Thời gian hoàn vốn dự tính: " + str(Time2) + " tháng")
price2 = round(float(Time2) * float(income2), 2)
print("Giá trị căn nhà từ dự án 2: " + str(price2) + " triệu đồng")
print("---")
print("So sánh thu nhập 2 dự án")
print("Nhập diện tích giả định S2: ")
S2 = input()
print("Diện tích nhà: " + str(S2) + " m2")
time3 = 144
print("Thời gian hoàn vốn: " + str(time3) + "tháng")
price1_new = float(S2) * float(p_q9)
print("Giá nhà mặt tiền với diện tích 50m2: " + str(price1_new) + " triệu đồng")
print("Nhập giá hẻm Quận 9: ")
p_hq9 = float(input())
print("Giá nhà mặt tiền Quận 9: " + str(p_hq9) + " triệu đồng/m2")
price2_new = float(S2) * float(p_hq9)
print("Giá nhà hẻm với diện tích 50m2: " + str(price2_new) + " triệu đồng")
print("Thu nhập hằng tháng của từng căn")
income1_new = float(price1_new) / 144
income2_new = float(price2_new) / 144
print("Thu nhập hằng tháng của nhà mặt tiền: " + str(income1_new) + " triệu đồng")
print("Thu nhập hằng tháng của nhà trong hẻm: " + str(income2_new) + " triệu đồng")
Ratio = round(float(income1_new) / float(income2_new), 2)
print("Tỷ lệ chênh lệch từ dự án cho thuê mặt tiền so với nhà trong hẻm: " + str(Ratio) + " lần")
if Ratio > 1.5:
print("Thu nhập hằng tháng từ căn nhà 1 bằng " + str(Ratio) + " lần thu nhập từ căn nhà 2")
else:
print("Thu nhập hằng tháng từ căn nhà 1 bằng" + str(Ratio) + " lần thu nhập từ căn nhà 2")
print("Nhập giá căn hộ và giá đất nền")
p_chq9 = float(input())
p_dnq9 = float(input())
dist9 = {
"Giá nhà mặt tiền (triệu đồng/m2) " : str(p_q9) ,
"Giá nhà hẻm (triệu đồng/m2) " : str(p_hq9) ,
"Giá căn hộ (triệu đồng/m2)" : str(p_chq9) ,
"Giá đất nền (triệu đồng/m2) " : str(p_dnq9)
}
print("---")
print(dist9["Giá đất nền (triệu đồng/m2) "])
print("Sửa giá nhà mặt tiền sau 7 năm")
dist9["Giá nhà mặt tiền (triệu đồng/m2) "] = float(p_chq9) * 3
print(dist9)
|
def addDB(dic,str1,str2):
if str1 in dic:
dic[str1] += [str2]
else:
dic[str1] = [str2]
if str2 in dic:
dic[str2] += [str1]
else:
dic[str2] = [str1]
def findDB(dic,key):
if key in dic:
return dic[key]
else:
return []
def removeDB(dic,str1,str2):
if str1 in dic:
if dic[str1] != []:
dic[str1].remove(str2)
else:
del dic[str1]
elif str2 in dic:
if dic[str2] != []:
dic[str2].remove(str1)
else:
del dic[str2]
def main():
command = input("-->")
alist = command.split()
dics = {}
while command != 'end':
if len(alist) == 3:
if alist[0] == 'add':
addDB(dics,alist[1],alist[2])
elif alist[0] == 'del':
removeDB(dics,alist[1],alist[2])
else:
print("Invalid Command")
elif len(alist) == 2:
if alist[0] == 'find':
print(findDB(dics,alist[1]))
else:
print("Invalid Command")
elif alist[0] == 'clear':
dics = {}
command = input("-->")
alist = command.split()
|
import random
class Bug:
def __init__(self,pos = 0):
self.position = pos
self.direction = 1
def move(self):
if self.position >= 0:
if self.direction == 1:
self.position += 1
else:
self.position -= 1
else:
self.position = self.position
def turn(self):
direction = random.randint(0,1)
if direction == 0:
self.direction = self.direction * -1
else:
self.direction = self.direction * 1
def display(self):
if self.direction == -1:
return "." * self.position + "<"
else:
return "." * self.position + ">"
def main():
""" Why it doesn't show the moves of bugs automatically when main is ran?
Also, is it supposed to be kept changing direction every move?
That saying, -1 +1 -1 +1 and so on?"""
"""
The answer on gitbut used it as private. Why? is that neccessary?
"""
abug = Bug(10)
print(abug)
for move in range(0,13):
abug.move()
abug.turn()
print(abug.display())
if __name__ == "__main__":
main()
|
import numpy as np
A = np.array([[1,2,3],[4,5,6],[7,8,9]])
B = np.array([[1,2,3],[4,5,6],[7,8,9]])
newmatrix = []
i = 0
while i < len(A):
eachrow = [np.sum(A[i]*B[:,j]) for j in range(len(A))]
i += 1
newmatrix.append(eachrow)
print(np.array(newmatrix))
print(np.dot(A,B))
|
import turtle
turtle.showturtle()
def Drawcircle(radius):
turtle.speed(0)
scaled_radius = radius/100
#bluecircle
turtle.penup()
turtle.left(180)
turtle.forward(300*scaled_radius)
turtle.left(90)
turtle.pensize(7)
turtle.pendown()
turtle.color("blue")
turtle.circle(radius)
#blackcircle
turtle.left(90)
turtle.penup()
turtle.forward(225*scaled_radius)
turtle.right(90)
turtle.color("black")
turtle.pendown()
turtle.circle(radius)
#redcircle
turtle.left(90)
turtle.penup()
turtle.forward(225*scaled_radius)
turtle.right(90)
turtle.color("red")
turtle.pendown()
turtle.circle(radius)
#yellocircle
turtle.right(90)
turtle.penup()
turtle.forward(240*scaled_radius)
turtle.left(90)
turtle.forward(100*scaled_radius)
turtle.right(90)
turtle.forward(100*scaled_radius)
turtle.left(90)
turtle.pendown()
turtle.color("yellow")
turtle.circle(radius)
#greencircle
turtle.left(90)
turtle.penup()
turtle.color("green")
turtle.forward(230*scaled_radius)
turtle.right(90)
turtle.pendown()
turtle.circle(radius)
Drawcircle(120)
|
class measure:
def __init__(self,feet = 0, inches = None):
if inches == None:
self.inches = feet
self.feet = 0
if feet >= 12:
self.feet = feet // 12
self.inches = feet % 12
else:
if inches < 12:
self.feet = feet
self.inches = inches
else:
self.feet = inches // 12 + feet
self.inches = inches % 12
def __str__(self):
if self.feet == 0 and self.inches == 0:
return str(0) + '"'
elif self.feet != 0 and self.inches == 0:
return str(self.feet) + "' "
else:
return str(self.feet) + "' " + str(self.inches) + '"'
def __add__(self,rhand):
return measure(self.feet + rhand.feet,self.inches + rhand.inches)
def __sub__(self,rhand):
sub_m = measure(self.feet - rhand.feet,self.inches - rhand.inches)
if sub_m.inches < 0:
sub_m.feet = sub_m.feet -1
sub_m.inches = sub_m.inches + 12
return sub_m
return sub_m
|
import os
import csv
def phonebook(menu):
if menu == 0:
return False
# Adding New address when menu = 1
elif menu == 1:
newName = input("Enter New Name: ")
newNum = int(input("Enter New Phone Number: "))
newAge = int(input("Enter New Age: "))
newAddress = input("Enter New Address: ")
new_info = [newName,newNum,newAge,newAddress]
mybook = open("addressbook.csv","a",newline = "")
adding = csv.writer(mybook)
adding.writerow(new_info)
print("Adding Completed!")
mybook.close()
# Searching information when menu = 2
elif menu == 2:
mydict = {"Name":"Enter the name: ",
"Phone":"Enter the number: ",
"Age":"Enter the age: ",
"Address":"Enter the address: "}
mybook = open("addressbook.csv","r",newline = "")
searching = csv.reader(mybook)
asList = list(searching)
header = asList[0]
category = input("Select searching method (Name/Phone/Age/Address): ")
details = input(mydict[category])
myindex = header.index(category)
for each_info in asList:
if str(each_info[myindex]) == details:
print(each_info)
mybook.close()
# Deleting the selected information when menu = 3
elif menu == 3:
mydict = {"Name":"Enter the name that you want to delete : ",
"Phone":"Enter the number that you want to delete : ",
"Age":"Enter the age that you want to delete : ",
"Address":"Enter the address that you want to delete : "}
mybook = open("addressbook.csv","r",newline = "")
searching = csv.reader(mybook)
asList = list(searching)
header = asList[0]
category = input("Select searching method (Name/Phone/Age/Address): ")
details = input(mydict[category])
myindex = header.index(category)
deleting_list = []
for each_info in asList:
if str(each_info[myindex]) == details:
deleting_list.append(each_info)
# deleting_list = [each_info if str(each_info[myindex]) == details for each_info in asList]
if len(deleting_list) == 0:
print("No information found")
elif len(deleting_list) == 1:
double_check1 = input("Do you really want to delete? (Y/N): ")
if double_check1 == "Y":
asList.remove(deleting_list[0])
else:
for j in deleting_list:
print(j)
double_check2 = int(input("Choose which one to delete (1 for 1st row, 2 for 2nd row..etc): "))
asList.remove(deleting_list[double_check2-1])
# Save the new lists over the existed one.
adding_change = open("addressbook.csv","w",newline = "")
adding = csv.writer(adding_change)
adding.writerows(asList)
mybook.close()
adding_change.close()
# Modifiying the selected information when menu = 4
elif menu == 4:
mybook = open("addressbook.csv","r",newline = "")
mydict = {"Name":"Enter the name to find which to modify : ",
"Phone":"Enter the number to find which to modify : ",
"Age":"Enter the age to find which to modify : ",
"Address":"Enter the to find which to modify : "}
mybook = open("addressbook.csv","r",newline = "")
searching = csv.reader(mybook)
asList = list(searching)
header = asList[0]
category = input("Select searching method (Name/Phone/Age/Address): ")
details = input(mydict[category])
myindex = header.index(category)
modifying_list = []
for each_info in asList:
if str(each_info[myindex]) == details:
modifying_list.append(each_info)
# modifying_list = [each_info if str(each_info[myindex]) == details for each_info in asList]
if len(modifying_list) == 0:
print("No information found")
else:
newName = input("Enter New Name: ")
newNum = int(input("Enter New Phone Number: "))
newAge = int(input("Enter New Age: "))
newAddress = input("Enter New Address: ")
new_info = [newName,newNum,newAge,newAddress]
if len(modifying_list) == 1:
modifying_index = asList.index(modifying_list[0])
asList[modifying_index] = new_info
else:
for j in modifying_list:
print(j)
double_check1 = int(input("Choose which one to modify (1 for 1st row, 2 for 2nd row..etc): "))
modifying_index = asList.index(modifying_list[double_check1-1])
asList[modifying_index] = new_info
# Save the new lists over the existed one.
adding_change = open("addressbook.csv","w",newline = "")
adding = csv.writer(adding_change)
adding.writerows(asList)
mybook.close()
adding_change.close()
# Print all information when menu = 5
elif menu == 5:
mybook = open("addressbook.csv","r",newline = "")
reading = csv.reader(mybook)
for eachrow in reading:
print(eachrow)
return True
def main():
# Check if there already is the csv file, otherwise the existed information will be gone everytime you run it
checking = os.path.isfile("addressbook.csv")
if checking == False:
# Creating new csv file if there hasn't been made one.
# Adding header for my csv file
mybook = open("addressbook.csv","w",newline = "")
book_obj = csv.writer(mybook)
book_obj.writerow(["Name","Phone","Age","Address"])
mybook.close()
keep_going = True
while keep_going == True:
print("1. Add information",
"\n2. Searh information",
"\n3. Delete information",
"\n4. Modify information",
"\n5. Print all information",
"\n0. Exit")
num = int(input("Enter your Menu number: "))
keep_going = phonebook(num)
if __name__ == "__main__":
main()
|
import random
import turtle
def direction():
d = random.randint(1,4)
if d == 1:
turtle.left(0)
turtle.forward(20)
elif d == 2:
turtle.left(90)
turtle.forward(20)
elif d == 3:
turtle.left(180)
turtle.forward(20)
elif d == 4:
turtle.left(270)
turtle.forward(20)
def CountSteps():
x_cord = 0
y_cord = 0
count = 0
while x_cord > -220 and x_cord < 220 and y_cord > -220 and y_cord < 220:
direction()
turtle.pos()
x_cord = round(turtle.xcor(), 0)
y_cord = round(turtle.ycor(), 0)
count += 1
turtle.stamp()
turtle.penup()
turtle.goto(0,0)
turtle.write("The number of counts of turns = " + str(count), True, align = 'center', font = ("Arial", 18, "normal"))
def main():
turtle.showturtle
turtle.speed(0)
turtle.setup (width = 440, height = 440, startx = 0, starty = 0)
CountSteps()
if __name__ == '__main__':
main()
|
def emul(a,b):
product = 0
if a < 0 and b < 0:
a = -1 * a
b = -1 * b
if a >= b:
big = a
small = b
else:
big = b
small = a
while small != 0:
if small%2 == 0:
product = product
else:
product += big
big *= 2
small //= 2
return product
elif a > 0 and b < 0:
a = 1 * a
b = -1 * b
if a >= b:
big = a
small = b
else:
big = b
small = a
while small != 0:
if small%2 == 0:
product = product
else:
product += big
big *= 2
small //= 2
return -1*product
elif a < 0 and b > 0:
a = -1 * a
b = 1 * b
if a >= b:
big = a
small = b
else:
big = b
small = a
while small != 0:
if small%2 == 0:
product = product
else:
product += big
big *= 2
small //= 2
return -1*product
elif a > 0 and b > 0:
if a >= b:
big = a
small = b
else:
big = b
small = a
while small != 0:
if small%2 == 0:
product = product
else:
product += big
big *= 2
small //= 2
return product
elif a == b == 0:
product = 0
return 0
def main():
a = int(input("Enter your first integer: "))
b = int(input("Enter your second integer: "))
print(emul(a,b))
if __name__ == "__main__":
main()
import turtle
import random
def race(a,b,c):
xcord_a = a.xcor()
xcord_b = b.xcor()
xcord_c = c.xcor()
while xcord_a <=500 and xcord_b <=500 and xcord_c <=500:
step_a = random.randint(1,15)
a.forward(step_a)
xcord_a = a.xcor()
step_b = random.randint(1,15)
b.forward(step_b)
xcord_b = b.xcor()
step_c = random.randint(1,15)
c.forward(step_c)
xcord_c = c.xcor()
def main():
turtle.speed(0)
scr = turtle.Screen()
scr.setworldcoordinates(0,0,500,500)
t1 = turtle.Turtle()
t1.hideturtle()
t1.shape("turtle")
t1.fillcolor(1,0,0)
t1.penup()
t1.goto(0,250)
t1.showturtle()
t2 = turtle.Turtle()
t2.hideturtle()
t2.shape("turtle")
t2.fillcolor(0,1,0)
t2.penup()
t2.goto(0,300)
t2.showturtle()
t3 = turtle.Turtle()
t3.hideturtle()
t3.shape("turtle")
t3.fillcolor(0,0,1)
t3.penup()
t3.goto(0,200)
t3.showturtle()
race(t1,t2,t3)
#race(t2)
#race(t3)
if __name__ == "__main__":
main()
|
import turtle
import random
import math
class Shape:
def __init__(self,x = 0,y = 0,col = "",fill = False):
self.x = x
self.y = y
self.color = col
self.fillcolor = fill
def setFillcolor(self,string):
self.color = string
def setFilled(self,bool):
self.color = True
def isFilled(self):
return self.fillcolor
class Circle(Shape):
def __init__(self,x,y,col,fill,rad = 1):
super().__init__(x,y,col,fill)
self.radius = rad
def draw(self,myt):
myt.penup()
myt.goto(self.x,self.y)
myt.pendown()
if self.fillcolor == True:
myt.fillcolor(self.color)
myt.begin_fill()
myt.circle(self.radius)
myt.end_fill()
else:
myt.circle(self.radius)
def isIN(self,x,y):
origin = (self.x,self.y + self.radius)
# Area = math.pi*(self.radius**2)
newR = ((x - origin[0])**2 + (y - origin[1])**2)**(0.5)
# newArea = math.pi*(newR**2)
if self.radius >= newR:
print("AAAAAA")
return True
return False
class Rectangle(Shape):
def __init__(self,x,y,col,fill,width,height):
super().__init__(x,y,col,fill)
self.width = width
self.height = height
def draw(self,myt):
myt.penup()
myt.goto(self.x,self.y)
myt.pendown()
myt.fillcolor(col)
myt.begin_fill()
for i in range(2):
myt.forward(width)
myt.right(90)
myt.forward(height)
myt.right(90)
myt.end_fill()
def isIN(self,x,y):
Area = self.height * self.width
newArea = abs(x - self.x) * abs(y - self.y)
if newArea <= Area:
return True
return False
class Display:
def __init__(self):
self.myt = turtle.Turtle()
self.scr = self.myt.getscreen()
self.elements = []
self.myt.speed(0)
self.myt.hideturtle()
self.scr.onclick(self.mouseEvent)
self.scr.listen()
def mouseEvent(self,x,y):
rad = random.randint(10,100)
color = ["blue","red"]
random.shuffle(color)
col = color[0]
mycircle = Circle(x,y,col,True,rad)
flag = True
"""
if element list is empty, nothing to remove but just add.
"""
if self.elements != []:
"""
Check every objects and its isIN method if my mouse click is in.
"""
flag2 = True
for shapes in self.elements:
print("Hello")
if shapes.isIN(x,y) and flag2:
"""
if it's in, remove the shape.
"""
self.remove(shapes)
"""
flag prevents from removing and drawing at the same time.
"""
flag = False
flag2 = False
"""
After all checking, if my click not in all objects, just draw new one.
"""
if flag:
self.add(mycircle)
else:
"""
First click must draw shape.
"""
self.add(mycircle)
if len(self.elements) == 10:
self.scr.bye()
# if self.elements != []:
# for shapes in self.elements:
# if shapes.isIN(x,y):
# flag = False
# self.remove(shapes)
# print("Not this one")
#
# if flag != False:
# print("NO at all!!!")
# self.add(mycircle)
#
# else:
# self.add(mycircle)
print(self.elements)
def add(self,shape):
self.elements.append(shape)
shape.draw(self.myt)
def remove(self,shape):
self.elements.remove(shape)
self.myt.clear()
if self.elements != []:
for shp in self.elements:
# the shp already have the information about the 'shape'
# just like what we did under mouseEvent: mycircle.draw(self.myt)
shp.draw(self.myt)
# print(self.elements)
def main():
D = Display()
if __name__ == "__main__":
main()
|
def slope(x1,x2,y1,y2):
y_d = y2 - y1
x_d = x2 - x1
if x_d != 0:
slope = y_d / x_d
return slope
else:
return 0
def main():
a = float(input(str("Enter first x value: ")))
c = float(input(str("Enter first y value: ")))
b = float(input(str("Enter second x value: ")))
d = float(input(str("Enter second y value: ")))
m = slope(a,b,c,d)
if m != 0:
y_intercept = d - m * b
print("y = " + str(m)+" x + " + str(y_intercept))
else:
print("Slope Not Exist")
if __name__ == "__main__":
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.