text
stringlengths 37
1.41M
|
---|
#Max.py
a=int(input('第一个数:'))
b=int(input('第二个数:'))
c=int(input('第三个数:'))
if a>b and a>c:
max=a
elif b>a and b>c:
max=b
else:
max=c
print(max)
|
def calculation():
while True:
count = 0
score = 0
while count < 2:
number = float(input())
if 0 <= number and number <= 10:
count += 1
score += number
else:
print("nota invalida")
print("media = {0:.2f}".format(score/2))
break
if __name__ == "__main__":
calculation()
x = 3
while (x != 1 or x != 2):
x = int(input())
print("novo calculo (1-sim 2-nao)")
if x == 1:
calculation()
elif(x == 2):
break
else:
continue
|
number = 0
count = 0
while count < 2:
n = float(input())
if n >= 0 and n <= 10:
number += n
count += 1
else:
print("nota invalida")
result = number / 2
print("media = {0:.2f}".format(result))
|
values = str(input(""))
number = values.split(" ")
A = int(number[0])
B = int(number[1])
C = int(number[2])
D = int(number[3])
if B > C and D > A and (C+D) > (A+B) and C > 0 and D > 0 and A % 2 == 0:
print("Valores aceitos");
else:
print("Valores nao aceitos");
|
import math
pi = 3.14159
R = float(input())
formula = (4/3.0)*pi*R**3
print('VOLUME = %.3f' %formula)
|
n = int(input())
number = []
for i in range(0, n):
num = int(input())
number.append(num)
for i in range(0, n):
if number[i] == 0:
print("NULL")
elif number[i] % 2 == 0:
if number[i] > 0:
print("EVEN POSITIVE")
else:
print("EVEN NEGATIVE")
elif number[i] % 2 == 1:
if number[i] > 0:
print("ODD POSITIVE")
else:
print("ODD NEGATIVE")
|
numbers_list = []
count = 0
for i in range(0,6):
number = float(input())
numbers_list.append(number)
if number > 0:
count +=1
print("%d valores positivos" %count)
|
# import dependencies
import csv
import os
# declaring file location
budget_csv_path = os.path.join("Resources /budget_data.csv")
with open(budget_csv_path) as csvfile:
csv_reader = csv.reader(csvfile, delimiter=",")
csv_header = next(csv_reader)
print(f"CSV Header: {csv_header}")
# Lists to iterate through specific rows
Pro_Los = []
months = []
M_P_C = []
# read through each row of data after the header
for row in csv_reader:
Pro_Los.append(int(row[1]))
months.append(row[0])
# Determining the change in profit/losses
for i in range (1, len(Pro_Los)):
M_P_C.append((int(Pro_Los[i]) - int(Pro_Los[i-1])))
# Calculate the average revenue change
average_change = [round(sum(M_P_C)/ len(M_P_C),2)]
# find the total length of months
total_months = len(months)
# determing the greater increase and decrease in revenue
greatest_increase = max(M_P_C)
greatest_decrease = min(M_P_C)
greatest_increase_months = months[M_P_C.index(max(M_P_C))+1]
greatest_decrease_months = months[M_P_C.index(min(M_P_C))+1]
#Print all results
print("```text")
print("Financial Analysis")
print(greatest_increase_months)
print("......................................")
print ("total months: " + str(total_months))
print(f"total: ${sum(Pro_Los)}")
print("Average Change: " + "$" + str(average_change))
print("Greatest Increase in Profits: " + greatest_increase_months + " " + "$" + str(greatest_increase))
print("Greatest Decrease in Profits: " + greatest_decrease_months + " " + "$" + str(greatest_decrease))
print("```") |
'''
stack-validation-example.py - a program by Nate Weeks to check for
properly closing parenthesis - February 2019
>>> parChecker('{{([][])}()}')
True
>>> parChecker('[{()]')
False
>>> parChecker('[({})]}')
False
>>> parChecker('[(]')
False
>>> parChecker('[(])')
False
'''
from LinkedStack import LinkedStack
def parChecker(symbolString):
s = LinkedStack()
balanced = True
index = 0
while index < len(symbolString) and balanced:
symbol = symbolString[index]
if symbol in "([{":
s.push(symbol)
else:
if s.isEmpty():
balanced = False
else:
top = s.pop()
if not matches(top,symbol):
balanced = False
index = index + 1
if balanced and s.isEmpty():
return True
else:
return False
def matches(open,close):
opens = "([{"
closers = ")]}"
return opens.index(open) == closers.index(close)
if __name__ == '__main__':
import doctest
doctest.testmod()
|
def are_anagrams(s1, s2, s3):
# definiuję funkcję tworzącą słownik znaków i ich powtórzeń występujących w łańcuchu
def dict_of_characters(x):
dict = {}
for i in x:
if i in dict:
dict[i] += 1
else:
dict[i] = 1
return dict
# sprawdzam czy długość każdego z łańcuchów jest nie większa niż 5
if all(len(s)<=5 for s in [s1, s2, s3]):
#sprawdzam czy wprowadzone łańcuchy znaków się nie powtarzają
if (s1!=s2 and s1!=s3 and s3!=s2):
# sprawdzam czy wprowadzone dane są anagramami
if (dict_of_characters(s1)==dict_of_characters(s2) and dict_of_characters(s1)==dict_of_characters(s3)):
ans = True
else:
ans = False
else:
ans = print("Wprowadzone łańcuchy powtarzają się")
else:
ans = print("Maksymalna długość znaków w łańcuchu wynosi 5!")
return ans |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def get_percentage(a, b):
"""This function is used to calcuate percentage. Given two data, the function will return the percentage of a and b
:param a: Denominator to calcuate the percentage
b: Numerator to calcuate the percentage
:return: the percentage of a/b
>>> a = 2
>>> b = 4
>>> get_percentage(a,b)
0.5
>>> a = 4
>>> b = 10
>>> get_percentage(a,b)
0.4
"""
perc = a/b
return perc
def state_abbrev(state_name):
"""This function will convert full state name to state abbreviation. Given a full state name, the function will return
abbreviation of the state.
:param state_name: full state name
:return: abbreviation for each state
>>> state_name = pd.Series(['Alabama', 'Alaska', 'Arizona'])
>>> state_abbrev(state_name)
0 AL
1 AK
2 AZ
dtype: object
>>> state_name = pd.Series(['Florida', 'Georgia', 'Hawaii', 'Iowa'])
>>> state_abbrev(state_name)
0 FL
1 GA
2 HI
3 IA
dtype: object
"""
us_state_abbrev = {'Alabama': 'AL', 'Alaska': 'AK', 'Arizona': 'AZ', 'Arkansas': 'AR',
'California': 'CA', 'Colorado': 'CO', 'Connecticut': 'CT', 'Delaware': 'DE',
'District of Columbia': 'DC', 'Florida': 'FL', 'Georgia': 'GA', 'Hawaii': 'HI',
'Idaho': 'ID', 'Illinois': 'IL', 'Indiana': 'IN', 'Iowa': 'IA', 'Kansas': 'KS',
'Kentucky': 'KY', 'Louisiana': 'LA', 'Maine': 'ME', 'Maryland': 'MD',
'Massachusetts': 'MA', 'Michigan': 'MI', 'Minnesota': 'MN', 'Mississippi': 'MS',
'Missouri': 'MO', 'Montana': 'MT', 'Nebraska': 'NE', 'Nevada': 'NV',
'New Hampshire': 'NH', 'New Jersey': 'NJ', 'New Mexico': 'NM', 'New York': 'NY',
'North Carolina': 'NC', 'North Dakota': 'ND', 'Northern Mariana Islands': 'MP',
'Ohio': 'OH', 'Oklahoma': 'OK', 'Oregon': 'OR', 'Palau': 'PW', 'Pennsylvania': 'PA',
'Puerto Rico': 'PR', 'Rhode Island': 'RI', 'South Carolina': 'SC', 'South Dakota': 'SD',
'Tennessee': 'TN', 'Texas': 'TX', 'Utah': 'UT', 'Vermont': 'VT', 'Virgin Islands': 'VI',
'Virginia': 'VA', 'Washington': 'WA', 'West Virginia': 'WV', 'Wisconsin': 'WI', 'Wyoming': 'WY',
}
return state_name.map(us_state_abbrev)
# read in csv file
df = pd.read_excel("data/Education.xls") # Education
poverty = pd.read_csv("data/poverty.csv", dtype={"Total":'Int64', "Number":"Int64"}) # Poverty
####### Assumption I
# modify columns
df['Total adults in 1970'] = df['Less than a high school diploma, 1970'] / (df['Percent of adults with less than a high school diploma, 1970']/100)
df['Total adults in 1980'] = df['Less than a high school diploma, 1980'] / (df['Percent of adults with less than a high school diploma, 1980'] / 100)
df['Total adults in 1990'] = df['Less than a high school diploma, 1990'] / (df['Percent of adults with less than a high school diploma, 1990']/100)
df['Total adults in 2000'] = df['Less than a high school diploma, 2000'] / (df['Percent of adults with less than a high school diploma, 2000']/100)
df['Total adults in 2013-17'] = df['Less than a high school diploma, 2013-17'] / (df['Percent of adults with less than a high school diploma, 2013-17']/100)
#### Analyze eduction for entire United States
FY = ['1970', '1980', '1990', '2000', '2013-17']
all = []
for i in FY:
less_than_high_school = get_percentage(df['Less than a high school diploma, ' + i].sum(), df['Total adults in ' + i].sum())
high_school = get_percentage(df['High school diploma only, ' + i].sum(), df['Total adults in ' + i].sum())
associate = get_percentage(df['Some college (1-3 years), ' + i].sum(), df['Total adults in ' + i].sum())
college = get_percentage(df['Four years of college or higher, ' + i].sum(),df['Total adults in ' + i].sum())
all.append([less_than_high_school, high_school, associate, college])
# visualize the education trends
all = np.asarray(all)
label = ['less than a high school', 'high school', ' some college(1-3 years)', 'four years of college or higher']
x = [1970, 1980, 1990, 2000, 2017]
for i in range(4):
plt.plot(x, all[:,i], label = label[i])
plt.legend()
plt.xlabel('Year')
plt.ylabel('Percentage')
plt.title('Percentage of People receive Degree from 1970 - 2017')
plt.show()
#### Analyze education by States
state = df.groupby('State').sum()[['Less than a high school diploma, 1970', 'High school diploma only, 1970', 'Some college (1-3 years), 1970', 'Four years of college or higher, 1970','Total adults in 1970',
'Less than a high school diploma, 1980', 'High school diploma only, 1980', 'Some college (1-3 years), 1980', 'Four years of college or higher, 1980','Total adults in 1980',
'Less than a high school diploma, 1990', 'High school diploma only, 1990', 'Some college (1-3 years), 1990', 'Four years of college or higher, 1990','Total adults in 1990',
'Less than a high school diploma, 2000', 'High school diploma only, 2000', 'Some college (1-3 years), 2000', 'Four years of college or higher, 2000','Total adults in 2000',
'Less than a high school diploma, 2013-17', 'High school diploma only, 2013-17', 'Some college (1-3 years), 2013-17', 'Four years of college or higher, 2013-17','Total adults in 2013-17']]
for i in FY:
state['Percentage less_than_high_school ' + i] = get_percentage(state['Less than a high school diploma, ' + i], state['Total adults in ' + i])
state['Percentage high_school ' + i] = get_percentage(state['High school diploma only, ' + i], state['Total adults in ' + i])
state['Percentage associate ' + i] = get_percentage(state['Some college (1-3 years), ' + i], state['Total adults in ' + i])
state['Percentage college ' + i] = get_percentage(state['Four years of college or higher, ' + i], state['Total adults in ' + i])
# Top 5 states with the highest percentage of people have college degree
asc_state_1970 = state.sort_values(by = 'Percentage college 1970', ascending=False)
asc_state_1980 = state.sort_values(by = 'Percentage college 1980', ascending=False)
asc_state_2000 = state.sort_values(by = 'Percentage college 2000', ascending=False)
asc_state_2017 = state.sort_values(by = 'Percentage college 2013-17', ascending=False)
print("Top 5 states with the highest percentage of people have college degree from 1970 - 2017")
print(asc_state_1970, asc_state_1980, asc_state_2000, asc_state_2017)
# Top 5 states with the highest percentage of people have less than high school degree
desc_state_1970 = state.sort_values(by = 'Percentage less_than_high_school 1970', ascending=True)
desc_state_1980 = state.sort_values(by = 'Percentage less_than_high_school 1980', ascending=True)
desc_state_1990 = state.sort_values(by = 'Percentage less_than_high_school 1990', ascending=True)
desc_state_2000 = state.sort_values(by = 'Percentage less_than_high_school 2000', ascending=True)
desc_state_2017 = state.sort_values(by = 'Percentage less_than_high_school 2013-17', ascending=True)
print("Top 5 states with the highest percentage of people have less than high school degree from 1970 - 2017")
print(desc_state_1970, desc_state_1980, desc_state_1980, desc_state_1990, desc_state_2000, desc_state_2017)
####### Assumption II
poverty['Percentage'] = get_percentage(poverty['Number'], poverty['Total'])
# visualize the relationship between poverty and education
year = [1980, 1990, 2000, 2010, 2017]
pov_perc = []
for y in year:
pov_perc.append(get_percentage(poverty[poverty['Year'] == y]['Number'].sum(),poverty[poverty['Year'] == y]['Total'].sum()))
plt.plot(year, pov_perc)
plt.xticks([1980, 1990, 2000, 2010, 2017])
plt.xlabel('Year')
plt.ylabel("Percentage")
plt.title('Percentage of Poverty Population 1980 - 2017')
plt.show()
#### Analyze the poverty from 2013-2017 for entire United States
FY13_17 = poverty[(poverty['Year'] >= 2013) &(poverty['Year'] <= 2017)]
# Poverty percentage histogram
FY13_17['Perc'] = FY13_17.loc[:,'Number'] / FY13_17.loc[:,'Total']
plt.hist(FY13_17['Perc'], 20, facecolor='blue', alpha=0.5)
plt.axvline(FY13_17['Perc'].mean(), color='k', linestyle='dashed', linewidth=1)
plt.xlabel('Poverty Percentage')
plt.ylabel('Occurance')
plt.title('Poverty Percentage Histogram')
plt.show()
#### Analyze the poverty from 2013-2017 by States
poverty_state = FY13_17.groupby('STATE').agg('sum')[['Total', 'Number']]
poverty_state['perc'] = get_percentage(poverty_state['Number'],poverty_state['Total'])
# change full state name to abbreviation
poverty_state['State'] = poverty_state.index
poverty_state['abbre'] = state_abbrev(poverty_state['State'])
poverty_state = poverty_state.set_index('abbre').sort_index(axis = 0)
edu_perc = state[['Percentage less_than_high_school 1970', 'Percentage high_school 1970',
'Percentage associate 1970', 'Percentage college 1970',
'Percentage less_than_high_school 1980', 'Percentage high_school 1980',
'Percentage associate 1980', 'Percentage college 1980',
'Percentage less_than_high_school 1990', 'Percentage high_school 1990',
'Percentage associate 1990', 'Percentage college 1990',
'Percentage less_than_high_school 2000', 'Percentage high_school 2000',
'Percentage associate 2000', 'Percentage college 2000',
'Percentage less_than_high_school 2013-17',
'Percentage high_school 2013-17', 'Percentage associate 2013-17',
'Percentage college 2013-17']]
edu_perc = edu_perc.drop(['PR', 'US'])
# visualize the relationship between poverty and different degrees.
plt.scatter(poverty_state['perc'], edu_perc['Percentage college 2013-17'])
plt.xlabel('Poverty Percentage')
plt.ylabel('College Degree Percentage')
plt.title("Plot Poverty by College Degree")
plt.show()
plt.scatter(poverty_state['perc'], edu_perc['Percentage less_than_high_school 2013-17'])
plt.xlabel('Poverty Percentage')
plt.ylabel('Less than High School Degree Percentage ')
plt.title("Plot Poverty by Less than High School Degree")
plt.show()
plt.scatter(poverty_state['perc'], edu_perc['Percentage associate 2013-17'])
plt.xlabel('Poverty Percentage')
plt.ylabel('Associate Degree Percentage ')
plt.title("Plot Poverty by Associate Degree")
plt.show()
plt.scatter(poverty_state['perc'], edu_perc['Percentage high_school 2013-17'])
plt.xlabel('Poverty Percentage')
plt.ylabel('High School Degree Percentage ')
plt.title("Plot Poverty by High School Degree")
plt.show()
from scipy.stats import pearsonr
print(pearsonr(poverty_state['perc'], edu_perc['Percentage high_school 2013-17']))
print(pearsonr(poverty_state['perc'], edu_perc['Percentage less_than_high_school 2013-17']))
print(pearsonr(poverty_state['perc'], edu_perc['Percentage college 2013-17']))
print(pearsonr(poverty_state['perc'], edu_perc['Percentage associate 2013-17'])) |
#!/usr/bin/env python3
from collections import deque
"""
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
result = []
queue = deque()
if root:
queue.append([root, 0])
while queue:
node, level = queue.popleft()
if level >= len(result):
result.append([])
result[level].append(node.val)
for child in node.children:
queue.append([child, level + 1])
return result
|
#!/usr/bin/env python3
class Solution:
def removeOuterParentheses(self, S: str) -> str:
result = ''
count = 0
for s in S:
count += 1 if s == '(' else -1
if s == '(' and count > 1 or s == ')' and count > 0:
result += s
return result
|
#!/usr/bin/env python3
from collections import Counter
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
counter = Counter(arr)
occurs = [counter[k] for k in counter]
return len(occurs) == len(set(occurs))
|
#!/usr/bin/env python3
class Solution:
def reverseOnlyLetters(self, S: str) -> str:
S, i, j = list(S), 0, len(S) - 1
while True:
while i < len(S) and not S[i].isalpha():
i += 1
while j >= 0 and not S[j].isalpha():
j -= 1
if i >= j:
break
S[i], S[j] = S[j], S[i]
i, j = i + 1, j - 1
return ''.join(S)
|
""" https://docs.opencv.org/master/d6/d6e/group__imgproc__draw.html#ga07d2f74cadcf8e305e810ce8eed13bc9
void cv::rectangle ( InputOutputArray img,
Point pt1,
Point pt2,
const Scalar & color,
int thickness = 1,
int lineType = LINE_8,
int shift = 0
)
Python:
img = cv.rectangle( img, pt1, pt2, color[, thickness[, lineType[, shift]]] )
img = cv.rectangle( img, rec, color[, thickness[, lineType[, shift]]] )
#include <opencv2/imgproc.hpp>
Draws a simple, thick, or filled up-right rectangle.
The function cv::rectangle draws a rectangle outline or a filled rectangle whose two opposite corners are pt1 and pt2.
Parameters
img Image.
pt1 Vertex of the rectangle.
pt2 Vertex of the rectangle opposite to pt1 .
color Rectangle color or brightness (grayscale image).
thickness Thickness of lines that make up the rectangle. Negative values, like FILLED, mean that the function has to draw a filled rectangle.
lineType Type of the line. See LineTypes
shift Number of fractional bits in the point coordinates.
"""
//Draws a rectangle on the image provided.
//Destructive to the image provided, recommended to clone / copy first.
void cv::rectangle() |
class BellmanFord(object):
def calculateShortestPath(self, graph, start):
dist = [float("inf") for x in range(graph.V)]
dist[start]=0.0
#calculate shortest paths from start vertex to all other vertices
self.calc(graph, dist, False)
#rerun algorithm to find vertices which are part of a negative cycle
self.calc(graph, dist, True)
return dist
def calc(self, graph, dist, findNegativeCycle):
numVertices = graph.V
numEdges = len(graph.edges)
for i in range(0, numVertices-1):
for j in range (numEdges):
for edge in graph.getEdge(j):
minDist = dist[edge.targetVertex]
newDist = dist[edge.startVertex] + edge.weight
if newDist < minDist:
if findNegativeCycle==True:
dist[edge.targetVertex] = float("-inf")
else:
dist[edge.targetVertex] = newDist
return dist |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 14 22:10:52 2019
@author: jigyasa
"""
'''Syntax of if statement:
if expression:
statement(s)
-----------------------------
Syntax of if-else
if exp:
statement(s)
else:
statement(s)
----------------------------
Syntax of elif statement
if ex1:
statements
elif ex2:
statement(s)
elif ex3:
statement(S)
else:
statement(s)
'''
# Program to check whether a number is even.
num=int(input('Enter the number:'))
if num%2==0:
print('%d is Even'%(num))
# Program to check which number is greater.
num=int(input('Enter 1st number:'))
num1=int(input('Enter 2nd number:'))
if num>num1:
print('%d is greater than %d'%(num,num1))
else:
print('%d is greater than %d'%(num1,num))
# Program to check grade of a student using percentage.
marks=int(input('Enter the percentage:'))
if marks>85 and marks<=100:
print('Congrats! Grade A')
elif marks>60 and marks<=85:
print('Grade B')
elif marks>40 and marks<=60:
print('Grade C')
elif marks>30 and marks<=40:
print('Grade D')
else:
print('Fail!')
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x = np.array([1,2,3,4,5,6,7])
y = x*2+5
plt.bar(x,y)
plt.title("bar plot")
plt.xlabel("x cubugu")
plt.ylabel("y cubugu")
plt.show() |
import Draw
import random
#Set the Canvas
canvasSize = 1000
Draw.setCanvasSize(canvasSize, canvasSize)
#Global variables representing the starting point of the frog
startingPointX = canvasSize//2
startingPointY = canvasSize - 300
#Functions to Draw the board
def drawWater():
WATER = Draw.color(100, 130, 250) #Water color
Draw.setColor(WATER)
Draw.filledRect(0, 445, canvasSize, 145)
def drawRoad():
ROAD = Draw.color(170, 170, 170)
Draw.setColor(ROAD)
Draw.filledRect(0, 95, canvasSize, 250)
Draw.setColor(Draw.WHITE)
for i in range (10, canvasSize, 120):
Draw.filledRect(i, 150, 60, 10)
for i in range (10, canvasSize, 120):
Draw.filledRect(i, 250, 60, 10)
#Draw the frog
def drawfrog(curX, curY):
Draw.setColor(Draw.DARK_GREEN)
Draw.filledOval(curX, curY, 25, 35) #Body
Draw.line(curX+2, curY+10, curX-5, curY+25) #Front Left Leg
Draw.line(curX-5, curY+25, curX-3, curY+27)
Draw.line(curX+22, curY+10, curX+30, curY+25) #Front Right Leg
Draw.line(curX+30, curY+25, curX+28, curY+27)
Draw.line(curX+2, curY+25, curX-5, curY+40) #Back Left Leg
Draw.line(curX-5, curY+40, curX-3, curY+42)
Draw.line(curX+22, curY+25, curX+30, curY+40) #Back Right Leg
Draw.line(curX+30, curY+40, curX+28, curY+42)
Draw.setColor(Draw.GREEN)
Draw.filledOval(curX+6, curY+5, 5, 5) #Eyes
Draw.filledOval(curX+15, curY+5, 5, 5)
Draw.setColor(Draw.BLACK)
Draw.filledOval(curX+7, curY+6, 2, 2)
Draw.filledOval(curX+16, curY+6, 2, 2)
########### Functions for the moving elements of the water ###############
#Pass through the list w to draw all the floats according to their type
def drawFloats(w):
for lanes in w:
for floaty in lanes:
if floaty[2] == "log":
drawLogs(floaty)
elif floaty[2] == "pad":
drawPads(floaty)
elif floaty[2] == "log":
drawLogs(floaty)
#How to draw each float
def drawLogs(floaty):
sizeOfLogX = 90
sizeOfLogY = 25
BROWN = Draw.color(120, 90, 90)
Draw.setColor(BROWN)
Draw.filledRect(floaty[0], floaty[1], sizeOfLogX, sizeOfLogY)
Draw.filledOval(floaty[0] - sizeOfLogY//2, floaty[1], sizeOfLogY, sizeOfLogY)
Draw.filledOval(floaty[0] + sizeOfLogX - sizeOfLogY//2, floaty[1], sizeOfLogY, sizeOfLogY)
Draw.setColor(Draw.BLACK)
Draw.line(floaty[0], floaty[1] +7, floaty[0]+20, floaty[1]+7)
Draw.line(floaty[0] + 40, floaty[1] + 10, floaty[0]+80, floaty[1]+10)
Draw.line(floaty[0] + 10, floaty[1] + 15, floaty[0]+50, floaty[1]+15)
def drawPads (floaty):
sizeOfPad = 60
padGreen = Draw.color(100, 190, 100)
Draw.setColor(padGreen)
Draw.filledOval(floaty[0]+8, floaty[1], sizeOfPad//2, sizeOfPad//2)
Draw.filledOval(floaty[0], floaty[1]+10, sizeOfPad//2, sizeOfPad//2)
Draw.filledOval(floaty[0]+ sizeOfPad//4, floaty[1]+10, sizeOfPad//2, sizeOfPad//2)
#How to move the floats for level 1
def moveFloatsLevel1(w, sizeOfLogX, sizeOfLogY, curX, curY, sizeOfPad):
for lanes in w:
for floaty in lanes:
floaty[0] += floaty[3] ##XCoord += the float's speed
if floaty[2] == "log":
if curX +30 >= floaty[0] and curX <= floaty[0] + sizeOfLogX and curY == floaty[1]: ##if the frog is on the object, move frog with the object
curX += floaty[3]
if floaty[2] == "pad":
if curX +30 >= floaty[0] and curX <= floaty[0] + 30 and curY == floaty[1]:
curX += floaty[3]
if lanes[len(lanes)-1][2] == "log": ##if the last float has reached its specified clearance, amend a new float to the list
if lanes[len(lanes)-1][0] <= lanes[len(lanes)-1][4]:
lanes.append([canvasSize+20, lanes[len(lanes)-1][1], lanes[len(lanes)-1][2], lanes[len(lanes)-1][3], lanes[len(lanes)-1][4] ])
elif lanes[len(lanes)-1][2] == "pad":
if lanes[len(lanes)-1][0] >= lanes[len(lanes)-1][4]:
lanes.append([-20, lanes[len(lanes)-1][1], lanes[len(lanes)-1][2], lanes[len(lanes)-1][3], lanes[len(lanes)-1][4] ])
return curX, curY
#How to move the floats for level 2
##essentially the same as level 1, except it is randomized
def moveFloatsLevel2(w, sizeOfLogX, sizeOfLogY, curX, curY, sizeOfPad):
for lanes in w:
for floaty in lanes:
floaty[0] += floaty[3] ##XCoord += the speed
if floaty[2] == "log":
if curX +30 >= floaty[0] and curX <= floaty[0] + sizeOfLogX and curY == floaty[1]:
curX += floaty[3]
if floaty[2] == "pad":
if curX +30 >= floaty[0] and curX <= floaty[0] + 30 and curY == floaty[1]:
curX += floaty[3]
if w[0][-1][0] <= w[0][-1][4]: ##if the last float has reached its specified clearance, randomly select the components of a new float and amend it to the list
w[0].append([canvasSize+20, w[0][-1][1], random.choice(["log", "pad"]), w[0][-1][3], w[0][-1][4] ])
if w[1][-1][0] >= w[1][-1][4]:
w[1].append([-50, w[1][-1][1], random.choice(["log", "pad"]), w[1][-1][3], w[1][-1][4] ])
if w[2][-1][0] <= w[2][-1][4]:
w[2].append([canvasSize+30, w[2][-1][1], random.choice(["log", "pad"]), w[2][-1][3], w[2][-1][4] ])
return curX, curY
#This function allows the program to evaluate if the frog is in the water but not on a float
def seeFrogInWater(w, curX, curY, sizeOfLogX, sizeOfLogY, lives):
if curY >= 445 and curY <=580: ##if the frog is in the water and on a float, no changes made. Otherwise, subtract a life and start over.
for lanes in w:
for floaty in lanes:
if floaty[2] == "log":
if curX +20 >= floaty[0] and curX <= floaty[0] + sizeOfLogX and curY == floaty[1]: return lives, curX, curY
if floaty[2] == "pad":
if curX +20 >= floaty[0] and curX <= floaty[0] + 30 and curY == floaty[1]: return lives, curX, curY
lives -= 1
drawSplash(curX, curY, 10)
curX = startingPointX
curY = startingPointY
return lives, curX, curY
############# Functions for all vehicles ################
#Pass through the list v and draw each vehicle according to its type
def drawVehicles(v):
for lanes in v:
for vehicle in lanes:
if vehicle[2] == "truck":
drawTrucks(vehicle)
elif vehicle[2] == "car":
drawCars(vehicle)
elif vehicle[2] == "bus":
drawBusses(vehicle)
#Pass though the list motor and draw each motorcycle
def drawAllMotorcycles(motor):
for lanes in motor:
for vehicle in lanes:
drawMotorcycle(vehicle)
#How to draw each type of vehicle
def drawCars(vehicle):
sizeOfCar = 30
sizeOfWheel = 10
TORQUISE = Draw.color(0,180, 180)
Draw.setColor(TORQUISE)
Draw.filledOval(vehicle[0], vehicle[1], sizeOfCar+10, sizeOfCar)
Draw.setColor(Draw.RED)
Draw.filledOval(vehicle[0] + 5, vehicle[1]+ (sizeOfCar-5) , sizeOfWheel, sizeOfWheel)
Draw.filledOval(vehicle[0] + 22, vehicle[1]+ (sizeOfCar-5), sizeOfWheel, sizeOfWheel)
Draw.setColor(Draw.BLACK)
Draw.oval(vehicle[0], vehicle[1], sizeOfCar+10, sizeOfCar)
Draw.filledOval(vehicle[0]+sizeOfCar-2, vehicle[1]+5, 10, 10)
Draw.line(vehicle[0] +6, vehicle[1] + (sizeOfCar//2), vehicle[0]+10, vehicle[1]+(sizeOfCar//2))
Draw.line(vehicle[0] +20, vehicle[1] + (sizeOfCar//2), vehicle[0]+25, vehicle[1]+(sizeOfCar//2))
Draw.oval(vehicle[0] + 5, vehicle[1]+ (sizeOfCar-5) , sizeOfWheel, sizeOfWheel)
Draw.oval(vehicle[0] + 22, vehicle[1]+ (sizeOfCar-5), sizeOfWheel, sizeOfWheel)
def drawTrucks(vehicle):
sizeOfTruckX = 50
sizeOfTruckY = 30
sizeOfWheel = 10
Draw.setColor(Draw.ORANGE)
Draw.filledRect(vehicle[0], vehicle[1], sizeOfTruckX, sizeOfTruckY)
Draw.filledRect(vehicle[0]+sizeOfTruckX, (vehicle[1] + sizeOfTruckY//2)-5, 10, (sizeOfTruckY//2)+5)
Draw.setColor(Draw.BLACK)
Draw.rect(vehicle[0], vehicle[1], sizeOfTruckX, sizeOfTruckY)
Draw.rect(vehicle[0]+sizeOfTruckX, (vehicle[1] + sizeOfTruckY//2)-5, 10, (sizeOfTruckY//2)+5)
Draw.setColor(Draw.PINK)
Draw.filledOval(vehicle[0] + 5, vehicle[1] + (sizeOfTruckY -5), sizeOfWheel, sizeOfWheel)
Draw.filledOval(vehicle[0] + 20, vehicle[1] + (sizeOfTruckY -5), sizeOfWheel, sizeOfWheel)
Draw.filledOval(vehicle[0] + 35, vehicle[1] + (sizeOfTruckY -5), sizeOfWheel, sizeOfWheel)
Draw.setColor(Draw.BLACK)
Draw.oval(vehicle[0] + 5, vehicle[1] + (sizeOfTruckY -5), sizeOfWheel, sizeOfWheel)
Draw.oval(vehicle[0] + 20, vehicle[1] + (sizeOfTruckY -5), sizeOfWheel, sizeOfWheel)
Draw.oval(vehicle[0] + 35, vehicle[1] + (sizeOfTruckY -5), sizeOfWheel, sizeOfWheel)
def drawBusses(vehicle):
sizeOfBusX = 55
sizeOfBusY = 25
sizeOfWheel = 10
Draw.setColor(Draw.YELLOW)
Draw.filledRect(vehicle[0], vehicle[1], sizeOfBusX, sizeOfBusY)
Draw.setColor(Draw.BLACK)
Draw.rect(vehicle[0], vehicle[1], sizeOfBusX, sizeOfBusY)
Draw.filledOval(vehicle[0] + 10, vehicle[1] + (sizeOfBusY -5), sizeOfWheel, sizeOfWheel)
Draw.filledOval(vehicle[0] + 30, vehicle[1] + (sizeOfBusY -5), sizeOfWheel, sizeOfWheel)
for i in range(2, 61, 12):
Draw.filledRect(vehicle[0]+i, vehicle[1] + 5, 6, 6)
def drawMotorcycle(motor):
Draw.setColor(Draw.BLACK)
Draw.filledOval(motor[0] +15, motor[1], 20, 18)
Draw.filledOval(motor[0], motor[1], 20, 7)
Draw.line(motor[0] +43, motor[1]+10, motor[0] +35, motor[1]-7)
Draw.line(motor[0] +42, motor[1]+10, motor[0] +34, motor[1]-7)
Draw.line(motor[0] +41, motor[1]+10, motor[0] +33, motor[1]-7)
Draw.line(motor[0] +40, motor[1]+10, motor[0] +32, motor[1]-7)
Draw.filledOval(motor[0] +22, motor[1]-2, 15, 7)
NAVY = Draw.color(0, 0, 50)
Draw.setColor(NAVY)
DARK_RED = Draw.color(100, 0, 0)
Draw.setColor(DARK_RED)
Draw.filledOval(motor[0] , motor[1]+5, 20, 20)
Draw.filledOval(motor[0] +35, motor[1]+10, 15, 15)
#How to move the vehicles for level 1
def moveVehiclesLevel1(v, curX, curY, sizeOfTruckX, sizeOfTruckY,sizeOfWheel, sizeOfBusX, sizeOfBusY, sizeOfCar, lives):
for lanes in v:
for vehicle in lanes:
vehicle[0] += vehicle[3] ##XCoord += the speed
if vehicle[2] == "truck": ##if frog hits the vehicle, subtract a life and start over
if curX +20 >= vehicle[0] and curX <= vehicle[0] + sizeOfTruckX and curY >= vehicle[1] and curY <= vehicle[1] + sizeOfTruckY+sizeOfWheel:
lives -=1
drawSplat(curX, curY,20)
curX = startingPointX
curY = startingPointY
elif vehicle[2] == "car":
if curX +20 >= vehicle[0] and curX <= vehicle[0] + sizeOfCar and curY >= vehicle[1] and curY <= vehicle[1] + sizeOfCar+sizeOfWheel:
lives -= 1
drawSplat(curX, curY,10)
curX = startingPointX
curY = startingPointY
elif vehicle[2] == "bus":
if curX +20 >= vehicle[0] and curX <= vehicle[0] + sizeOfBusX and curY >= vehicle[1] and curY <= vehicle[1] + sizeOfBusY + sizeOfWheel:
lives -= 1
drawSplat(curX, curY,10)
curX = startingPointX
curY = startingPointY
if lanes[len(lanes)-1][0] >= lanes[len(lanes)-1][4]: ##(X coordinate of the last vehicle in the list is greater than clearance)
lanes.append([-15, lanes[len(lanes)-1][1], lanes[len(lanes)-1][2], lanes[len(lanes)-1][3], lanes[len(lanes)-1][4] ]) ##copy a new vehicle list at X=0
return lives,curX,curY
#How to move the vehicles for level 2
##essentially the same as level 1, but randomized
def moveVehiclesLevel2(v, curX, curY, sizeOfTruckX, sizeOfTruckY,sizeOfWheel, sizeOfBusX, sizeOfBusY, sizeOfCar, lives):
for lanes in v:
for vehicle in lanes:
vehicle[0] += vehicle[3] ##XCoord += the speed
if vehicle[2] == "truck": ##if frog hits a vehicle, subtract a life and start over
if curX +20 >= vehicle[0] and curX <= vehicle[0] + sizeOfTruckX and curY >= vehicle[1] and curY <= vehicle[1] + sizeOfTruckY+sizeOfWheel:
lives -=1
drawSplat(curX, curY,20)
curX = startingPointX
curY = startingPointY
elif vehicle[2] == "car":
if curX +20 >= vehicle[0] and curX <= vehicle[0] + sizeOfCar and curY >= vehicle[1] and curY <= vehicle[1] + sizeOfCar+sizeOfWheel:
lives -= 1
drawSplat(curX, curY,10)
curX = startingPointX
curY = startingPointY
elif vehicle[2] == "bus":
if curX +20 >= vehicle[0] and curX <= vehicle[0] + sizeOfBusX and curY >= vehicle[1] and curY <= vehicle[1] + sizeOfBusY + sizeOfWheel:
lives -= 1
drawSplat(curX, curY,10)
curX = startingPointX
curY = startingPointY
if lanes[len(lanes)-1][0] >= lanes[len(lanes)-1][4]: ##if the last vehicle in the list reached its clearance, randomly select the attributes of a new vehicle
lanes.append([-15, lanes[len(lanes)-1][1], random.choice(["truck", "bus", "car"]), lanes[len(lanes)-1][3], random.choice([350, 300, 250, 200] )] )
##append that new vehicle to the list
return lives,curX,curY
#How to move motorcycles
def moveMotorcycle(motor, curX, curY, lives):
for lanes in motor:
for vehicle in lanes:
vehicle[0] += vehicle[3] ##XCoord += the speed
if curX +20 >= vehicle[0] and curX <= vehicle[0] + 60 and curY >= vehicle[1] and curY <= vehicle[1] + 40: ##if frog hits a motorcycle, lose life, start over
lives -= 1
drawSplat(curX, curY,10)
curX = startingPointX
curY = startingPointY
if vehicle[0] >= canvasSize-20:
lanes.append([-550, lanes[len(lanes)-1][1], "motorcycle", 10])
return lives, curX, curY
#How to draw a "splat" when frog hits a vehicle
def drawSplat(curX, curY, i):
Draw.setColor(Draw.YELLOW)
Draw.filledPolygon([curX, curY,
curX + i, curY +i*2,
curX + i*2, curY +i*2,
curX +i, curY +i*3,
curX +i*2, curY +i*4,
curX , curY +i*3,
curX -i*2, curY +i*4,
curX -i, curY +i*3,
curX -i*2, curY +i*2,
curX -i, curY +i*2])
Draw.setColor(Draw.ORANGE)
Draw.polygon([curX, curY,
curX + i, curY +i*2,
curX + i*2, curY +i*2,
curX +i, curY +i*3,
curX +i*2, curY +i*4,
curX , curY +i*3,
curX -i*2, curY +i*4,
curX -i, curY +i*3,
curX -i*2, curY +i*2,
curX -i, curY +i*2])
#How to draw a "splash" when frog falls in the water
def drawSplash(curX, curY, i):
Draw.setColor(Draw.WHITE)
Draw.filledPolygon([curX, curY,
curX + i, curY +i*2,
curX + i*2, curY +i*2,
curX +i, curY +i*3,
curX +i*2, curY +i*4,
curX , curY +i*3,
curX -i*2, curY +i*4,
curX -i, curY +i*3,
curX -i*2, curY +i*2,
curX -i, curY +i*2])
Draw.filledOval(curX - 15, curY+5, 9, 9)
Draw.filledOval(curX - 15, curY-3, 5, 5)
Draw.filledOval(curX - 27, curY+1, 5, 5)
Draw.filledOval(curX + 10, curY+7, 9, 9)
Draw.filledOval(curX + 15, curY-3, 5, 5)
Draw.filledOval(curX + 27, curY+1, 5, 5)
Draw.filledOval(curX , curY+35, 5, 5)
Draw.filledOval(curX-20, curY+45, 5, 5)
Draw.filledOval(curX+20, curY+45, 5, 5)
#This function is responsible for tracking and displaying the status of the game
def status(lives, curX, curY):
Draw.setColor(Draw.RED) ##display lives remaining
Draw.setFontSize(18)
Draw.string("Lives Remaining: " + str(lives), 100, 10)
Draw.setFontBold(True)
Draw.setFontSize(20) ##display the back button
Draw.string("< BACK", canvasSize - 100, 10)
if curY <= 95: ##if the frog crosses sucessfully, give the player an option to play again or quit
Draw.setColor(Draw.MAGENTA)
Draw.setFontSize(80)
Draw.string("PHEW!", 400, 200)
GREY = Draw.color(170, 170, 170)
for i in range (340, 500, 100):
Draw.setColor(GREY)
Draw.filledRect(400, i, 200, 60)
Draw.setColor(Draw.BLACK)
Draw.rect(400, i, 200, 60)
Draw.setColor(Draw.BLACK)
Draw.setFontSize(20)
Draw.string("Play Again?", 450, 360)
Draw.string("Quit", 460, 460)
if Draw.mousePressed(): ##respond to user clicks: return or start over
if Draw.mouseX() >= canvasSize-100 and Draw.mouseX() <= canvasSize and Draw.mouseY() <= 30:
playGame()
if curY <= 95 and Draw.mouseX() >= 400 and Draw.mouseX() <= 600 and Draw.mouseY() >= 340 and Draw.mouseY() <= 400:
curX = startingPointX
curY = startingPointY
elif curY <= 95 and Draw.mouseX() >= 400 and Draw.mouseX() <= 600 and Draw.mouseY() >= 440 and Draw.mouseY() <= 500:
playGame()
return curX, curY
#Function for level 1
def Level1():
LIGHT_BLUE = Draw.color(190, 200, 250)
Draw.setBackground(LIGHT_BLUE)
GameOn = True
lives = 3
#The following are 3-D lists that contain the attributes of each car or float in a lane: [X-coorinate, Ycoordinate, type, velocity, clearance]
v = [ [ [710, 100, "truck", 5, 300], [310, 100, "truck", 5, 350], [10, 100, "truck", 5, 300] ], #lane 1
[ [600, 200, "car", 8, 250], [350, 200, "car", 8, 250], [100, 200, "car", 8, 250] ], #lane 2
[ [660, 300, "bus", 5, 300], [360, 300, "bus", 5, 300], [60, 300, "bus", 5, 300] ] ] #lane 3
w = [ [ [10, 550, "log", -1, canvasSize-200], [210, 550, "log", -1, canvasSize-200], [410, 550, "log", -1, canvasSize-200], [610, 550, "log", -1, canvasSize-200], \
[810, 550, "log", -1, canvasSize-200] ], #lane 1
[ [780, 500, "pad", 1, 250], [530, 500, "pad", 1, 250], [280, 500, "pad", 1, 250], [30, 500, "pad", 1, 250] ], #lane 2
[ [50, 450, "log", -1, canvasSize-200], [250, 450, "log", -1, canvasSize-200], [450, 450, "log", -1, canvasSize-200], [650, 450, "log", -1, canvasSize-200],\
[850, 450, "log", -1, canvasSize-200] ] ] #lane 3
#initialize size of moving vehicles and floats, and position of the frog
sizeOfCar = 30
sizeOfWheel = 10
sizeOfTruckX = 50
sizeOfTruckY = 30
sizeOfBusX = 55
sizeOfBusY = 25
sizeOfLogX = 90
sizeOfLogY = 25
sizeOfPad = 60
curX = startingPointX
curY = startingPointY
while GameOn:
if Draw.hasNextKeyTyped(): #Respond to user buttons
newKey = Draw.nextKeyTyped()
if newKey == "Up":
curY -= 50
elif newKey == "Down":
curY += 50
elif newKey == "Right":
curX += 50
elif newKey == "Left":
curX -= 50
if lives == 0:
GameOn = False
Draw.clear()
#draw the board, floats, vehicles, status, and frog
drawRoad()
drawWater()
drawFloats(w)
drawVehicles(v)
drawfrog(curX, curY)
curX, curY = status(lives, curX, curY)
lives, curX, curY = seeFrogInWater(w, curX, curY, sizeOfLogX, sizeOfLogY, lives)
lives, curX, curY = moveVehiclesLevel1(v, curX, curY, sizeOfTruckX, sizeOfTruckY,sizeOfWheel, sizeOfBusX, sizeOfBusY, sizeOfCar, lives)
curX, curY = moveFloatsLevel1(w, sizeOfLogX, sizeOfLogY, curX, curY, sizeOfPad)
Draw.show()
#Function for level 2
def Level2():
DARK_PURPLE = Draw.color(220, 180, 240)
Draw.setBackground(DARK_PURPLE)
#The following are 3-D lists that contain the attributes of each car, float, or motorcycle in a lane: [X-coorinate, Ycoordinate, type, velocity, clearance]
##list of vehicles:
v = [ [ [710, 100, "bus", 8, 300], [310, 100, "truck", 8, 350], [10, 100, "car", 8, 300] ], #lane 1
[ [600, 200, "truck", 5, 250], [350, 200, "car", 5, 250], [100, 200, "truck", 5, 250] ], #lane 2
[ [660, 300, "truck", 5, 300], [360, 300, "bus", 5, 300], [60, 300, "car", 5, 300] ] ] #lane 3
##list of floats
w = [ [ [10, 550, "pad", -1, canvasSize-200], [210, 550, "log", -1, canvasSize-200], [410, 550, "log", -1, canvasSize-200], [610, 550, "pad", -1, canvasSize-200], \
[810, 550, "log", -1, canvasSize-200] ], #lane 1
[ [780, 500, "pad", 1, 200], [530, 500, "log", 1, 200], [280, 500, "pad", 1, 200], [30, 500, "log", 1, 200] ], #lane 2
[ [50, 450, "log", -1, canvasSize-200], [250, 450, "log", -1, canvasSize-200], [450, 450, "pad", -1, canvasSize-200], [650, 450, "log", -1, canvasSize-200], \
[850, 450, "pad", -1, canvasSize-200] ] ] #lane 3
##list of motorcycles
motor = [ [ [canvasSize-300, 150, "motorcycle", 10] ], #lane 1
[ [-50, 250, "motorcycle", 10] ] ] #lane 2
GameOn = True
lives = 3
#initialize size of vehicles and floats, and position of frog
sizeOfCar = 30
sizeOfWheel = 10
sizeOfTruckX = 50
sizeOfTruckY = 30
sizeOfBusX = 55
sizeOfBusY = 25
curX = startingPointX ##Initialize Position of the frog
curY = startingPointY
sizeOfLogX = 90
sizeOfLogY = 25
sizeOfPad = 60
while GameOn:
if Draw.hasNextKeyTyped(): #Respond to user buttons
newKey = Draw.nextKeyTyped()
if newKey == "Up":
curY -= 50
elif newKey == "Down":
curY += 50
elif newKey == "Right":
curX += 50
elif newKey == "Left":
curX -= 50
if lives == 0:
GameOn = False
#Draw board, vehicles, cloats, motorcycles, frog, and status
Draw.clear()
drawRoad()
drawWater()
drawFloats(w)
drawVehicles(v)
drawAllMotorcycles(motor)
drawfrog(curX, curY)
curX, curY = status(lives, curX, curY)
(lives, curX, curY) = seeFrogInWater(w, curX, curY, sizeOfLogX, sizeOfLogY, lives)
lives, curX, curY = moveVehiclesLevel2(v, curX, curY, sizeOfTruckX, sizeOfTruckY,sizeOfWheel, sizeOfBusX, sizeOfBusY, sizeOfCar, lives)
curX, curY = moveFloatsLevel2(w, sizeOfLogX, sizeOfLogY, curX, curY, sizeOfPad)
lives, curX, curY = moveMotorcycle(motor, curX, curY, lives)
Draw.show()
#The main function
def playGame():
while True:
Draw.clear()
x = 200
l = 0
#Draw Play Game and Level options
colors = [Draw.YELLOW, Draw.BLUE, Draw.RED, Draw.GREEN, Draw.ORANGE]
Draw.setBackground(Draw.BLACK)
Draw.setFontBold(False)
Draw.setFontSize(80)
Draw.setColor(Draw.YELLOW)
for i in "PLAY GAME":
x += 60
Draw.setColor(random.choice(colors))
Draw.string(i, x, 200)
GREY = Draw.color(170, 170, 170)
for i in range (340, 500, 100):
Draw.setColor(GREY)
Draw.filledRect(400, i, 200, 60)
Draw.setColor(Draw.BLACK)
Draw.setFontSize(20)
l += 1
Draw.string("LEVEL " + str(l), 455, i +20)
if Draw.mousePressed(): #Respond to user buttons
if Draw.mouseX() >= 400 and Draw.mouseX() <= 600 and Draw.mouseY() >= 340 and Draw.mouseY() <= 400:
Level1()
elif Draw.mouseX() >= 400 and Draw.mouseX() <= 600 and Draw.mouseY() >= 440 and Draw.mouseY() <= 500:
Level2()
Draw.show(100) #slow down the flashing
playGame()
|
'''
Harshad Number.
If a number is divisible by the sum of its digits, then it will be known as
a Harshad Number.
For example:
The number 156 is divisible by the sum (12) of its digits (1, 5, 6 ).
some of harshad numbers:-->10,12,18,20,120,140,152,156,198,200
'''
num=int(input())
sum_of_digits=0
temp=num
while num:
r=num%10
sum_of_digits+=r
num=num//10
if temp%sum_of_digits==0:
print('Harshad Number')
else:
print('Not a Harshad Number')
|
#! /usr/bin/env python
"""
wallpaper - finds a random picture and sets it as wallpaper
you need another program (this uses bsetbg) for actually
setting the wallpaper
In a unix/linux/bsd system, you can schedule this to run regularly
using crontab. For example, I run this every hour. So I go
to a shell and run
crontab -e
This opens up my crontab file. I add the following line:
01 * * * * /usr/local/bin/wallpaper > /dev/null
learn more about cron format at
http://www.uwsg.iu.edu/edcert/slides/session2/automation/crontab5.html
Written by "Babu"
"""
# all the folders you want to scan
folders = [
'~/backgrounds/1024x768',
'~/backgrounds/800x600',
]
# these are the valid image types - case sensitive
use_types = ['.jpg', '.gif', '.png']
# The command to execute for setting wallpaper. %s will be
# substituted by the image path
cmd = "bsetbg -f %s"
# ---------------- main routine ------------------------------
import os
from random import choice
# initialize a list to hold all the images that can be found
imgs = []
# for each item in folders
for d in folders:
# is it a valid folder?
if os.path.exists(d) and os.path.isdir(d):
# get all files in that folder
for f in os.listdir(d):
# splitext[1] may fail
try:
# is that file of proper type?
if os.path.splitext(f)[1] in use_types:
# if so, add it to our list
imgs.append(d + os.sep + f)
except:
pass
# get a random entry from our list
wallpaper = choice( imgs )
print cmd % wallpaper
# execute the command
os.system( cmd % wallpaper )
|
import matplotlib.pyplot as plt
def f(i):
if i % 2 == 0:
return int(i / 2)
else:
return 3 * i + 1
# начальные значения -- числа [3..31]
xs = list(range(3, 32))
n = len(xs)
# сгенерируем случайные цвета
# Lehmer RNG, 97 - простое,
# число 40 пораждает полную последовательность
randoms = []
s = 18 # seed
for i in range(n):
s = 40 * s % 97
randoms.append(s / 97)
# (r, g, b)
colors = [(r, 0.8, 1 - r) for r in randoms]
xll = xs[0]
for i in range(n):
xarr = []
yarr = []
j = 0
y = xs[i]
while y != 1:
xarr.append(j)
yarr.append(y)
j += 1
y = f(y)
print(i, j) # какое из i "проживет" дольше всех?
# 24 живет 111 шагов
plt.plot(xarr, yarr, "o-", color = colors[i], markeredgewidth=0)
plt.xlabel(r"$n$")
plt.ylabel(r"$(f^n)(x)$")
plt.savefig("collatz.png")
|
while True:
print("Current Room Temperature: " + input.temperature(TemperatureUnit.FAHRENHEIT) + "°F" + " - " + input.temperature(TemperatureUnit.CELSIUS) + "°C")
if input.temperature(TemperatureUnit.FAHRENHEIT) >= 130:
light.set_all(light.rgb(255,0,0))
elif input.temperature(TemperatureUnit.FAHRENHEIT) <120 :
light.set_all(light.rgb(0,255,0))
elif input.temperature(TemperatureUnit.FAHRENHEIT) <130>80 :
light.set_all(light.rgb(255,0,255)) |
jumsu = int(input())
score = ""
if jumsu >= 90:
score = "A"
elif jumsu >= 80:
score = "B"
elif jumsu >= 70:
score = "C"
elif jumsu >= 60:
score = "D"
else:
score = "F"
print(score) |
'''
Exercicio:
Criar um formulário que pergunte o nome, cpf, endereço, idade, altura e telefone
e imprima em um relatório organizado.
'''
nome = input("Digite seu nome: ")
cpf = input("digite seu CPF: ")
endereco = input("Digite seu endereço: ")
idade = input("Digite sua idade: ")
altura = input("Digite sua altura: ")
telefone = input("Digite seu telefone: ")
print("Nome:", nome,
"Idade:", idade,"\n"
"CPF:", cpf,"\n"
"Altura:",altura,"\n"
"Endereço:", endereco,"\n"
"Telefone:", telefone) |
import queue
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class rightSideView:
def solution(self, root: TreeNode) -> List[int]:
if root == None:
return []
res = []
q1 = queue.Queue()
q1.put(root)
while not q1.empty():
size = q1.qsize()
for i in range(size):
temp = q1.get()
if temp.left != None:
q1.put(temp.left)
if temp.right != None:
q1.put(temp.right)
if i == size - 1:
res.append(temp.val)
return res
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class middleNode:
def solution(self, head):
p1 = head
p2 = head
p2Forward = True
while p1:
p1 = p1.next
p2Forward = not p2Forward
if p2Forward:
p2 = p2.next
return p2
node = ListNode(1)
node1 = ListNode(2)
node2 = ListNode(3)
node3 = ListNode(4)
node4 = ListNode(5)
node5 = ListNode(6)
node.next = node1
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
head = node
str1 = ""
while head:
str1 = str1 + str(head.val) + "->"
head = head.next
print(str1)
obj = middleNode()
res = obj.solution(node)
str2 = ""
while res:
str2 = str2 + str(res.val) + "->"
res = res.next
print(str2)
|
class reverseWords:
def solution(self, s: str) -> str:
word = s.split()
str1 = " ".join(word[::-1])
return str1 |
#!/usr/bin/python
import os
import sys
def mean(a):
return sum(a)/len(a)
if __name__ == '__main__':
one = []
two = []
four = []
six = []
eight = []
ten = []
thou = []
tthou = []
for x in sys.argv[1:]:
print x
with open(x,"r") as f:
for line in f:
if '#' in line:
continue
sline = line.split()
num = sline[0]
val = float(sline[1])
if num == "0.001":
one.append(val)
if num == "0.01":
two.append(val)
if num == "0.1":
four.append(val)
if num == "1.0":
six.append(val)
if num == "10.0":
eight.append(val)
if num == "100.0":
ten.append(val)
if num == "1000.0":
thou.append(val)
if num == "10000.0":
tthou.append(val)
one.sort()
two.sort()
four.sort()
six.sort()
eight.sort()
ten.sort()
thou.sort()
tthou.sort()
print("X\tmin\tmean\tmax")
print("0.001\t%f\t%f\t%f"%(min(one),mean(one),max(one)))
print("0.01\t%f\t%f\t%f"%(min(two),mean(two),max(two)))
print("0.1\t%f\t%f\t%f"%(min(four),mean(four),max(four)))
print("1.0\t%f\t%f\t%f"%(min(six),mean(six),max(six)))
print("10.0\t%f\t%f\t%f"%(min(eight),mean(eight),max(eight)))
print("100.0\t%f\t%f\t%f"%(min(ten),mean(ten),max(ten)))
print("1000.0\t%f\t%f\t%f"%(min(thou),mean(thou),max(thou)))
print("10000.0\t%f\t%f\t%f"%(min(tthou),mean(tthou),max(tthou)))
|
# n=12
# name = 'Rinshu'
# print(f"Name is {name.upper()} and no is {n}")
# print("name is {} and no is {}".format(name,n))
# x='refactor'
# print(x[-1:-4:-1])
#List comprehension
# list = [num*2 for num in range(10)]
# print(list)
#map()
def even(num):
return num*2
l = [1, 2, 3, 4, 5, 6 ,7 , 8, 9, 10]
# result = list(map(even,l))
#lamda
result = list(map(lambda x:x*x,l))
print(result)
#filter
# fil = list(filter(lambda x : x%2==0,l))
# print(fil)
#
# fil = list(filter(lambda x : x%2==0,l))[1]
# print(fil)
print(list(filter(lambda x : x%2==0,l))[1])
|
import cv2
import numpy as np
# Class of functions used for simple image processing
class Functions:
def createCircle(w, h):
# creates distance img for creating circular crops
X, Y = np.ogrid[:w, :h]
CenterX, CenterY = w / 2, h / 2
img = ((X - CenterX) ** 2 + (Y - CenterY) ** 2)
return img
def centerCrop(img, w, h):
# crops around center
maxY, maxX = img.shape[0], img.shape[1]
x1, y1 = int(maxX / 2 - w / 2), int(maxY / 2 - h / 2)
x2, y2 = int(maxX / 2 + w / 2), int(maxY / 2 + h / 2)
crop = img[y1:y2, x1:x2]
return crop
def rescale_frame(res, percent=75):
# rescales image
width = int(res.shape[1] * percent / 100)
height = int(res.shape[0] * percent / 100)
dim = (width, height)
return cv2.resize(res, dim, interpolation=cv2.INTER_AREA) |
import matplotlib.pyplot as plt
#from matplotlib import pyplot plt
plt.bar([0.25,1.25,2.25,3.25,4.25],[50,40,70,80,20],label="BMW",color='b', width= .5)
plt.bar([0.25,1.05,2.75,3.75,4.75],[80,20,20,50,60],label="Audi",color= 'g', width= .5)
plt.legend()
plt.xlabel("Days")
plt.ylabel("Distance (KM's)")
plt.title("Information")
plt.show()
#PieChart
days=[1,2,3,4,5]
Sleeping=[7,8,6,11,7]
Eating=[2,3,4,3,2]
Working=[7,8,7,2,2]
Playing=[8,5,7,8,13]
Slices=[7,2,2,13]
Activities=["Sleeping","Eating","Working","Playing"]
cols = ['g','c','gray','y']
plt.pie( Slices, labels = Activities,colors=cols,startangle= 90,shadow=True,explode=(0,0.1,0,0),autopct='%1.1f%%')
plt.title("PIE PLOT")
plt.show() |
num = int(input("Enter Number : "))
factorial = 1
if num < 0:
print("Enter Positive Number")
elif num == 0:
print("Factorial is = 1 ")
else:
for i in range(1, num + 1):
factorial = factorial * i
print(factorial)
|
# _ _
# ((\o/))
# .-----//^\\-----.
# | /`| |`\ |
# | | | |
# | | | |
# | | | |
# '------===------'
def process_line(line):
line = line.strip().split('x')
line = [int(i) for i in line]
line.sort()
a1_and_slack = (3*line[0]*line[1])
a2 = (2*line[0]*line[2])
a3 = (2*line[1]*line[2])
return a1_and_slack + a2 + a3
total = 0
with open('input.txt') as f:
for line in f:
total += process_line(line)
print("Square footage needed: " str(total))
|
"""Задача №3
Написать программу, которая генерирует в указанных пользователем границах:
a. случайное целое число,
b. случайное вещественное число,
c. случайный символ.
Для каждого из трех случаев пользователь задает свои границы диапазона.
Например, если надо получить случайный символ от 'a' до 'f', то вводятся эти символы.
Программа должна вывести на экран любой символ алфавита от 'a' до 'f' включительно.
"""
from random import random
m1 = int(input("Введите первое целое число: "))
m2 = int(input("Введите второе целое число: "))
n = int(random() * (m2 - m1 + 1)) + m1
print(n)
m1 = float(input("Введите первое дробное число: "))
m2 = float(input("Введите второе дробное число: "))
n = random() * (m2 - m1) + m1
print(round(n, 3))
m1 = ord(input("Введите первую букву: "))
m2 = ord(input("Введите вторую букву: "))
n = int(random() * (m2 - m1 + 1)) + m1
print(chr(n)) |
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'maxStreak' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER m
# 2. STRING_ARRAY data
#
def maxStreak(m, data):
max_conse = 0
current_conse = 0
for attendance in data:
#iterate through each day's record
if 'N' in attendance:
if(current_conse>max_conse):
max_conse = current_conse
current_conse = 0
else:
current_conse +=1
if(current_conse>max_conse):
max_conse = current_conse
return max_conse
print(maxStreak(4,['NNNN','YNYY','YYYY','YNYN','YYYY','YYYY','YYYY','YYNY','YYYY','NYYN']))
|
email_dict = {}
def getEmailThreads(emails):
thread_num = 1
result = []
for comma in emails:
first = comma.find(",")+1
second = comma[first:].find(",")+1
text=comma[first+second:].strip()
print(text)
#text = email[2]
index = text.rfind("---") #find last index
print(index)
if index>-1:
text = text[index+3:]
print("key: ")
print(text)
email_dict[text][1]+=1 #increment thread count
else:
#start a new thread
#increment thread num
email_dict[text]=[thread_num,1]
thread_num += 1
x =[]
x.append(email_dict[text][0])
x.append(email_dict[text][1])
result.append(x)
return result
r = getEmailThreads(['[email protected], [email protected], hello x, how are you?',
'[email protected], [email protected], did you take a look at the event?',
'[email protected], [email protected], i am great. how are you?---hello x, how are you?'])
print(r)
|
def binary_search(arr, x):
l = 0
m = 0
r = len(arr) - 1
while l <= r:
m = (l + r) // 2
if arr[m] == x:
return m
if arr[m] < x:
l = m + 1
continue
if arr[m] > x:
r = m - 1
continue
return -1
|
class Binary:
def __init__(self, key):
self.data = key
self.left = None
self.right = None
def height(A):
if A == None:
return 0
else:
ldepth = height(A.left)
rdepth = height(A.right)
if(ldepth > rdepth):
return 1+rdepth
return 1+ldepth
root = Binary(1)
root.left = Binary(2)
root.right = Binary(3)
root.left.left = Binary(4)
root.left.right = Binary(5)
root.left.left.left = Binary(7)
root.right.right = Binary(8)
print(height(root))
|
def max_sum_SubArray(arr):
current_sum = 0
max_so_far = arr[0]
for i in range(len(arr)):
current_sum = current_sum + arr[i]
if max_so_far < current_sum:
max_so_far = current_sum
elif current_sum < 0:
current_sum = 0
return max_so_far
arr = [4, -3, -2, 2, 3, 1, -2, -3, 6, -6, -4, 2, 1]
print(max_sum_SubArray(arr)) |
def sort_colour(arr):
red = 0
blue = 0
for i in range(len(arr)):
if arr[i] == 1:
red+=1
elif arr[i] == 2:
blue+=1
return [1]*red + [2]*blue + [3]*(len(arr) - red - blue)
a = [1, 2, 3, 1, 3, 2, 1, 2, 3, 1]
print(sort_colour(a)) |
def odd_even(l):
whole = []
odd = []
even = []
for items in l:
if items % 2 == 0:
even.append(items)
else:
odd.append(items)
whole = [odd, even]
return whole
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(odd_even(list1)) |
import numpy as py
r = int(input("Enter the number of rows : "))
c = int(input("Enter the number of columns : "))
arr = py.zeros((r, c), dtype = int)
length = len(arr)
for i in range(length):
for j in range(len(arr[i])):
x = int(input("Enter the elements : "))
arr[i][j] = x
for i in range((length)):
for j in range(len(arr[i])):
print(arr[i][j], end = " ")
print()
print(arr)
|
def length():
string = input("Enter the stirng : ").split()
last_word = len(string[-1])
print(last_word)
length() |
class Phone:
def __init__(self, brand, model_name, price):
self.brand = brand
self.model_name = model_name
self.price = price
def full_name(self):
return f"This phone is {self.brand} {self.model_name}"
def make_a_call(self, number):
return f"Dialling {number}..."
class Smartphone(Phone):
def __init__(self, brand, model_name, price, ram, internal_memory, rear_camera):
super().__init__(brand, model_name, price)
# Phone.__init__(self, brand, model_name, price)
self.ram = ram
self.internal_memory = internal_memory
self.rear_camera = rear_camera
def full_name(self):
return f"This phone is {self.brand} {self.model_name} and it has a rear camera of {self.rear_camera}"
class Flagshipphone(Smartphone):
def __init__(self, brand, model_name, price, ram, internal_memory, rear_camera, front_camera):
super().__init__(brand, model_name, price, ram, internal_memory, rear_camera)
self.front_camera = front_camera
def full_name(self):
return f"This phone is {self.brand} {self.model_name} and it has a front camera of {self.front_camera}"
def __str__(self):
return f"{self.brand} {self.model_name}"
def __repr__(self):
return f"{self.brand} {self.model_name}"
def __len__(self):
return len(self.full_name())
def __add__(self, other):
return int(self.price) + int(other.price)
S1 = Flagshipphone("OnePlus", "8 Pro", "75000", "8GB", "256GB", "64MP", "32MP")
S2 = Flagshipphone("OnePlus", "7 Pro", "76000", "8GB", "256GB", "64MP", "32MP")
# S2 = Flagshipphone("OnePlus", "8 Pro", "75000", "8GB", "256GB", "64MP", "32MP")
# print(S2.full_name())
# print(help(Smartphone))
# print(S1.__repr__())
# print(str(S1))
print(S1.__len__())
print(S1 + S2) |
# Enter your code here. Read input from STDIN. Print output to STDOUT
number = int(raw_input().strip())
l = []
for i in range (number):
inp = raw_input().split(" ")
command = inp[0]
if command == "insert":
l.insert(int(inp[1]),int(inp[2]))
elif command == "print":
print (l)
elif command == "remove":
l.remove(int(inp[1]))
elif command == "append":
l.append(int(inp[1]))
elif command == "sort":
l.sort()
elif command == "pop":
l.pop()
elif command == "reverse":
l.reverse()
|
# get_bin_value.py
'''
This standalone program converts the letters A through G (and P for decimal point)
to their respective binary value for a common-anode seven segment display.
'''
output = ''
flags = {
"a": 0,
"b": 1,
"c": 2,
"d": 3,
"e": 4,
"f": 5,
"g": 6,
"p": 7
}
def main():
value = input("Please enter flags to build your binary value\n")
global output
binary_val = 0x00
for c in value:
binary_val |= 1<<flags[c]
binary_val = 0x00FF & ~binary_val
output += ' 0b'+format(binary_val, '08b') # Prints 8-bit numbers, separated by a space.
if __name__ == "__main__":
try:
while True:
main()
except KeyboardInterrupt: # This program only quits when the user inputs "CTRL+C"
print ("Output:")
print(output)
|
from collections import deque
import random
class DeckEmptyError(Exception):
# Constructor or Initializer
def __init__(self, value):
self.value = value
# __str__ is to print() the value
def __str__(self):
return(repr(self.value))
class Cards(object):
shades =('Green','Red','Yellow' )
def __init__(self):
"""initializes deck of cards as pair of ('shade','number') where shades are
in ['Green','Red','Yellow' ] and number ranges from 1 to 13 inclusive"""
self.deck_of_cards= deque([(y,x) for x in range(1,14) for y in Cards.shades])
def shuffle(self):
"""Shuffles the deck of cards"""
random.shuffle(self.deck_of_cards)
return self.deck_of_cards
def get_top_card(self):
"""Retruns top of the card"""
if len(self.deck_of_cards)==0:
raise DeckEmptyError("Invalid operation: No more elements in Deck")
else:
return self.deck_of_cards.pop()
def sort(self,color_list):
"""Sorts the deck of cards in order of color_list parameter and number of the
card. For example If the deck has a card contains with following order
(red, 1), (green, 5), (red, 0), (yellow, 3), (green, 2)
Sort cards([yellow, green, red]) will return the cards with following order
(yellow, 3), (green, 0), (green, 5), (red, 0), (red, 1)"""
sorted_list= deque()
if len(color_list)==0:
print("Invalid input, expecting non-empty color list")
return
for x in color_list:
if x not in Cards.shades:
print("Invalid Input, invalid color given as input")
return
for x in color_list:
sort1=deque()
for y in self.deck_of_cards:
if x == y[0]:
sort1.append(y)
sort1=sorted(sort1,key=lambda x:x[1])
sorted_list.extend(sort1)
self.deck_of_cards = sorted_list
return self.deck_of_cards
class GameInterface(object):
"""Game Interface to be inherited by concrete game classes"""
def play(self):
"""Play game."""
pass
def reset(self):
"""Reset and restart the game."""
pass
def stop(self):
"""Stop the game."""
pass
def display_winner(self):
"""Display 1st winner."""
pass
def print_player_rank(self):
"""Display 1st winner."""
pass
def print_player_rank_and_points(self):
"""Display player rank and corresponding points"""
pass
def display_player_points():
"""Display player points in order"""
pass
class DrawCardsGame(GameInterface):
'''This is a drawing cards game which takes as input number of users and
lets users pick 3 cards by taking turns and after all the draws it calculates
winner as below:
Whoever has the high score wins the game. (color point calculation,
red = 3, yellow =2, green = 1) the point is calculated by
color point * number in the card.'''
#Dictionary with card color as key and corresponding value as points.
shades_points_dict = {'Green': 1,'Red': 3,'Yellow' : 2}
#Number of turns per player till finish of game.
num_turns = 3
def __init__(self):
self.cards = Cards()
self.player_points = {}
self.player_draws = {}
self.num_players=0
def _initialize_player_stats(self):
"""initialize player points and stats"""
self.reset()
for x in range(self.num_players):
self.player_draws[f'{x}']=[]
self.player_points[f'{x}']= 0
def _rank(self):
"""sort the player points dictionary with key as the points of each
player in desending order and return the sorted list"""
return sorted(self.player_points.items(),key=lambda x:x[1],reverse=True)
def determine_winner(self,list1,list2):
""" Determines the winner for 2 player games, takes as input the list
of all the draws for for both the players"""
points_player1=0
points_player2=0
if len(list1) !=DrawCardsGame.num_turns or\
len(list2) !=DrawCardsGame.num_turns:
print(f"Invalid Input, please make {DrawCardsGame.num_turns} draws for each player")
return f"Invalid Input, please make {DrawCardsGame.num_turns} draws for each player"
for x in list1:
points_player1+=DrawCardsGame.shades_points_dict[x[0]] * x[1]
for x in list2:
points_player2+=DrawCardsGame.shades_points_dict[x[0]] * x[1]
if points_player1>points_player2:
print("Congratulations!!!,Winner is player1")
return "Winner player1"
elif points_player2>points_player1:
print("Congratulations!!!,Winner is player2")
return "Winner player2"
else:
print("Its a draw")
return "Its a draw"
def play(self):
""" Makes player play the game. After the game is done winner is determined"""
self.num_players = int(input("Welcome to card drawing game, Please enter number of players:"))
#contains all the draws from different players as list of draws per player.
#with player number as key
print(f"Num players:{self.num_players}")
#initialize player points and draws
self._initialize_player_stats()
for y in range(DrawCardsGame.num_turns):
for x in range(self.num_players):
input(f"Press enter for turn no {y+1} to draw for player {x+1}:")
card_drawn = self.cards.get_top_card()
self.player_draws[f'{x}'].append(card_drawn)
print(f"card_drawn {card_drawn}")
self.player_points[f'{x}']+= DrawCardsGame.shades_points_dict[card_drawn[0]] * card_drawn[1]
print(f"player_points {self.player_points}")
print(repr(self.player_draws))
print(repr(self.player_points))
self.determine_winner(self.player_draws['0'],self.player_draws['1'])
self.determine_winner1()
def Reset(self):
"""Resets player stats and game state information"""
self.player_draws.clear()
self.player_points.clear()
self.num_players=0
self.cards.shuffle()
def stop(self):
"""Stops/aborts the game and reset player stats"""
print("Thank you for playing the game, hope you had fun!!!")
self.reset()
def determine_winner1(self):
"""prints player rank in sorted order starting with rank 1st. Works for
any number of players"""
sorted_player_rank = self._rank()
print(f"sorted player rank: {sorted_player_rank}")
print(f"winner is player {sorted_player_rank[0]}: with points {sorted_player_rank[0][1]}")
my_cards = DrawCardsGame()
print(str(my_cards.cards))
print(my_cards.cards.sort(['Yellow','Red','Green']))
print(str(my_cards.cards.sort(['Yellow','Red','Blue'])))
print(str(my_cards.cards.sort([])))
#if __name__ == '__main__':
# try:
# for x in range (1,50):
# print(str(my_cards.cards.get_top_card()))
# except Exception as e:
# print(e)
print(str(my_cards.cards.shuffle()))
my_cards.determine_winner([('Green',1),('Green',2),('Green',3)],[('Red',1),('Red',2),('Red',3)])
my_cards.determine_winner([('Red',1),('Red',2),('Red',3)],[('Green',1),('Green',2),('Green',3)])
my_cards.determine_winner([('Green',1),('Green',2),('Green',3)],[('Green',1),('Green',2),('Green',3)])
my_cards.determine_winner([('Green',1),('Green',2)],[('Green',1),('Green',3)])
my_cards.determine_winner([('Green',1),('Green',2),('Green',3)],[('Green',2),('Green',3)])
my_cards.determine_winner([('Green',2),('Green',3)],[('Green',1),('Green',2),('Green',3)])
import unittest
class TestStringMethods(unittest.TestCase):
def test_determine_winner(self):
mycards = DrawCardsGame()
self.assertEqual(my_cards.determine_winner([('Green',1),('Green',2),('Green',3)],[('Red',1),('Red',2),('Red',3)])
, "Winner player2")
self.assertEqual(my_cards.determine_winner([('Red',1),('Red',2),('Red',3)],[('Green',1),('Green',2),('Green',3)])
, "Winner player1")
self.assertEqual(my_cards.determine_winner([('Green',1),('Green',2),('Green',3)],[('Green',1),('Green',2),('Green',3)])
, "Its a draw")
self.assertEqual(my_cards.determine_winner([('Green',1),('Green',2)],[('Green',1),('Green',3)])
, "Invalid Input, please make 3 draws for each player")
self.assertEqual(my_cards.determine_winner([('Green',1),('Green',2),('Green',3)],[('Green',2),('Green',3)])
, "Invalid Input, please make 3 draws for each player")
self.assertEqual(my_cards.determine_winner([('Green',2),('Green',3)],[('Green',1),('Green',2),('Green',3)])
, "Invalid Input, please make 3 draws for each player")
def test_sort(self):
my_cards= Cards()
self.assertEqual(my_cards.sort([]),None)
self.assertEqual(my_cards.sort(['Yellow','Red','Green']),deque([('Yellow', 1), ('Yellow', 2), ('Yellow', 3), ('Yellow', 4), ('Yellow', 5), ('Yellow', 6), ('Yellow', 7), ('Yellow', 8), ('Yellow', 9), ('Yellow', 10), ('Yellow', 11), ('Yellow', 12), ('Yellow', 13), ('Red', 1), ('Red', 2), ('Red', 3), ('Red', 4), ('Red', 5), ('Red', 6), ('Red', 7), ('Red', 8), ('Red', 9), ('Red', 10), ('Red', 11), ('Red', 12), ('Red', 13), ('Green', 1), ('Green', 2), ('Green', 3), ('Green', 4), ('Green', 5), ('Green', 6), ('Green', 7), ('Green', 8), ('Green', 9), ('Green', 10), ('Green', 11), ('Green', 12), ('Green', 13)]))
self.assertEqual(my_cards.sort(['Yellow','Red','Blue']),None)
def test_get_top_card(self):
my_cards= Cards()
self.assertEqual(my_cards.get_top_card(), ('Yellow', 13))
if __name__ == '__main__':
#unittest.main()
my_cards.play() |
import re
def long_repeat(line):
"""
length the longest substring that consists of the same char
"""
result = 0
for letter in set(line):
for match in re.findall(letter + "+", line):
if len(match) > result:
result = len(match)
return result |
#! /usr/bin/env python
from copy import deepcopy
d = {}
d['names'] = ['Alfred', 'Bertrand']
c = d.copy()
dc = deepcopy(d)
d['names'].append('Clive')
print c
#{'names': ['Alfred', 'Bertrand', 'Clive']}
print dc
#{'names': ['Alfred', 'Bertrand']}
print '\n\n\n\n\n'
x = {'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
y = x.copy()
y['username'] = 'mlh'
y['machines'].remove('bar')
print y
#{'username': 'mlh', 'machines': ['foo', 'baz']}
print x
#{'username': 'admin', 'machines': ['foo', 'baz']} |
#! /usr/bin/env python
class Polymorphism:
"""
This class is an example of polymorphism
"""
#def run_account(self, *args):
def run_account(self, *args):
"""polymorphism example in method overloading
"""
print" ".join(args)
# creating instance of a class, create an object obj of a class Ploymorphism
obj = Polymorphism()
# passing parameter to a class
obj.run_account("one")
obj.run_account("one", "two")
obj.run_account("one", "two", "three")
"""
print 'abcada'.count('a')
print [1, 3, 4, 2, 2, 1, 2].count(1)
""" |
#練習09 うるう年の判定 (ex09.py)
#うるう年というのは、四年に一度、二月が29日まである年のことをいうと思われていますが、正確にはもっと複雑です。西暦の年に対して、
#年が400で割り切れるなら、うるう年です。
#そうではなくて年が100で割り切れるならば、うるう年ではありません。
#そうでもなくて年が4で割り切れるならば、うるう年です。
year = int(input("西暦で年を入力して下さい >"))
if year % 400 == 0:
print(year,"年はうるう年です")
elif year % 100 == 0:
print(year,"年はうるう年ではありません")
elif year % 4 == 0:
print(year,"年はうるう年です")
else:
print(year,"年はうるう年ではありません")
|
#金額を入力するとその金額を出来るだけ少ない枚数の貨幣を使って支払えるように貨幣の枚数を数えるプログラムを書きなさい。貨幣は、{1万円札、五千円札、千円札、五百円玉、百円玉、五十円玉、十円玉、五円玉、一円玉}とする(余り使わないので2千円札は除く)。
money = int(input("金額(円) >"))
print(money,"円")
maisu =money // 10000
money = money % 10000
print("一万円札= ",maisu,"枚")
maisu =money // 5000
money = money % 5000
print("五千円札= ",maisu,"枚")
maisu =money // 1000
money = money % 1000
print("千円札 = ",maisu,"枚")
maisu =money // 500
money = money % 500
print("五百円玉= ",maisu,"枚")
maisu =money // 100
money = money % 100
print("百円玉 = ",maisu,"枚")
maisu =money // 50
money = money % 50
print("五十円玉= ",maisu,"枚")
maisu =money // 10
money = money % 10
print("十円玉 = ",maisu,"枚")
maisu =money // 5
money = money % 5
print("五円玉 = ",maisu,"枚")
print("一円玉 = ",money,"枚")
|
print('Hello,Welcome to Quiz:')
ans=input('You Want to play (yes/no):')
score=0
total_q=4
if ans.lower() == 'yes':
ans=input('1.What is Best Programming language:Option=[java],[python] ')
if ans=='python':
score +=1
print('correct Answer')
else:
print('incorrect Answer')
ans = input('2.Who is india Prime Minister:Option=[Modi],[rahul] ')
if ans.lower()== 'narendra Modi' or ans=='modi':
score += 1
print('correct Answer')
else:
print('incorrect Answer')
ans = input('3.What is 3+6+3 ? :Option=[12],[11] ')
if ans == '12':
score += 1
print(' correct Answer')
else:
print('incorrect Answer')
ans = input('4.which Year corona virus war introduce:Option=[2020],[2019] ')
if ans == '2020':
score += 1
print('correct Answer')
else:
print('incorrect Answer')
print('Thank for playing this game , You got',score,"question correct")
mark=(score/total_q) * 100
print("mark",mark)
print("good bye")
|
from queue import PriorityQueue as pq
from collections import defaultdict
from pprint import pprint as pp
class Graph:
def __init__(self, vertices):
self.vertexLbl = {vertex: pos for pos, vertex in enumerate(vertices)}
self.vertices = vertices
self.adjMat = [[-1] * len(vertices) for vertex in vertices]
def add_edge(self, src, dest, w=0):
self.adjMat[self.vertexLbl[src]][self.vertexLbl[dest]] = w
self.adjMat[self.vertexLbl[dest]][self.vertexLbl[src]] = w
def prims(self):
mst = defaultdict(list)
cost = 0
visited = set()
q = pq()
q.put((0, (0, 0)))
while not q.empty() and len(mst) < len(self.vertexLbl):
weight, (src, dest) = q.get()
if src != dest and dest not in visited:
mst[self.vertices[src]].append((self.vertices[dest], weight))
mst[self.vertices[dest]].append((self.vertices[src], weight))
cost += weight
print(f'{self.vertices[src]} -> {self.vertices[dest]} ({weight} ({cost}))')
visited.add(dest)
for adjVertex in range(len(self.adjMat[dest])):
if adjVertex not in visited and dest != adjVertex and self.adjMat[dest][adjVertex] >= 0:
q.put((self.adjMat[dest][adjVertex], (dest, adjVertex)))
pp(mst)
return cost
|
from typing import List
class ListNode:
def __init__(self, x, next=None):
self.val = x
self.next = next
class LinkedList:
def __init__(self, vals: List[int] = []):
cur_node = None
self.head = None
self.d = dict()
for i in range(len(vals)):
node = None
if vals[i] in self.d:
node = self.d[vals[i]]
else:
node = ListNode(vals[i])
self.d[vals[i]] = node
if cur_node:
cur_node.next = node
cur_node = node
if not self.head:
self.head = cur_node
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if not head:
return False
fast, slow = head, head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
return True
return False
ll: LinkedList = LinkedList([1,2,3,1])
node: ListNode = ll.head
sol = Solution()
print(sol.hasCycle(node))
ll: LinkedList = LinkedList([1,2,3])
node: ListNode = ll.head
sol = Solution()
print(sol.hasCycle(node))
ll: LinkedList = LinkedList([1,2,3,4,5,6,3])
node: ListNode = ll.head
sol = Solution()
print(sol.hasCycle(node))
|
'''
286. Walls and Gates
You are given a m x n 2D grid initialized with these three possible values.
-1 - A wall or an obstacle.
0 - A gate.
INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647.
Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with INF.
Example:
Given the 2D grid:
INF -1 0 INF
INF INF INF -1
INF -1 INF -1
0 -1 INF INF
After running your function, the 2D grid should be:
3 -1 0 1
2 2 1 -1
1 -1 2 -1
0 -1 3 4
'''
from typing import List
from collections import deque
from pprint import pprint
class Solution:
def wallsAndGates(self, rooms: List[List[int]]) -> None:
"""
Do not return anything, modify rooms in-place instead.
"""
queue = deque()
"Find Gates and add it to queue with distance 0"
for rpos, r in enumerate(rooms):
for cpos, c in enumerate(r):
if rooms[rpos][cpos] == 0:
queue.append((rpos, cpos, 0))
nformulas = [(0, -1), (0, 1), (-1, 0), (1, 0)]
level = 0
INF = pow(2, 31) - 1
"Update neighbor empty rooms with distance from gate"
while len(queue) > 0:
gr, gc, level = queue.popleft()
for nformula in nformulas:
nr, nc = tuple(sum(x) for x in zip((gr, gc), nformula))
if nr >= 0 and nr < len(rooms) and nc >= 0 and nc < len(rooms[nr]) and rooms[nr][nc] == INF:
rooms[nr][nc] = level+1
queue.append((nr, nc, level+1))
rooms = [
[2147483647, -1, 0, 2147483647],
[2147483647, 2147483647, 2147483647, -1],
[2147483647, -1, 2147483647, -1],
[0, -1, 2147483647, 2147483647]
]
sol = Solution()
sol.wallsAndGates(rooms)
pprint(rooms)
|
'''
Graph is valid tree when it has no cycle and all nodes are connected
'''
from typing import List
visited:set
graph:List[List[int]]
def is_valid_tree(graph: List[List[int]]) -> bool:
visited = set()
# DFS
has_cycle = DFS(0, graph, visited)
is_connected = len(visited) == len(graph)
if not has_cycle and is_connected:
return True
else:
return False
def DFS(node, graph, visited):
if node in visited:
# has_cycle = True
return True
visited.add(node)
for child_node in range(len(graph[node])):
if graph[node][child_node] == 1:
if DFS(child_node, graph, visited):
return True
return False
|
from typing import List
from sys import maxsize
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
return self.check_node(root, -maxsize, maxsize)
def check_node(self, node:TreeNode, min_val:int, max_val:int) -> bool:
if node == None:
return True
if node.val >= min_val and node.val <= max_val and self.check_node(node.left, min_val, node.val) and self.check_node(node.right, node.val, max_val):
return True
return False
def get_tree(self, tree_nodes:List[int], i):
if i >= len(tree_nodes):
return
cur_node = TreeNode(tree_nodes[i])
cur_node.left = self.get_tree(tree_nodes, (i*2)+1)
cur_node.right = self.get_tree(tree_nodes, (i*2)+2)
return cur_node |
import unittest
from closest_two_sum import find_closest_pair
class TestClosestTwoSum(unittest.TestCase):
def test_find_closest_two_sum(self):
array = [10, 22, 28, 29, 30, 40]
n = len(array)
target = 54
self.assertEqual(find_closest_pair(array, n, target), (22, 30))
if __name__ == '__main__':
unittest.main() |
'''
Quick Sort is divide and conqure algorithm with recursion
* In-Place sorting
* Best time O(N log N)
* Worst time O(N^2) if array is already sorted
'''
from typing import List
class QuickSort:
def sort(self, nums):
self.quickSort(nums, 0, len(nums)-1)
def quickSort(self, nums, l , h):
if l < h:
# Partitiion and find privot
pivot = self.partition(nums, l, h)
self.quickSort(nums, l, pivot - 1)
self.quickSort(nums, pivot + 1, h)
def partition(self, nums, l, h):
'''Move lower values to left of pivot and move higher values to right side of pivot'''
# Take first element as Pivot
pivot_value = nums[l]
i = l + 1
j = h
while i <= j:
# Find first larger number than pivot from left
while i <= j and nums[i] <= pivot_value:
i += 1
#Find first smaller number from right
while j >= i and nums[j] >= pivot_value:
j -= 1
# Move smaller number to left and larger number to right
if i < j:
self.swap(nums, i, j)
# Move pivot to cutting place
self.swap(nums, l, j)
# Return new pivot location
return j
def swap(self, nums, i, j):
print(f'{nums[i]} {nums[j]}')
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
nums = [3,2,1,5,6,4]
print(nums)
qs = QuickSort()
qs.sort(nums)
print(nums)
|
from typing import List
from collections import defaultdict
class Solution:
@staticmethod
def alienOrder(words: List[str]) -> str:
i = 1
adj_list = defaultdict(list)
while i < len(words):
word = words[i-1]
nextWord = words[i]
for charW1, charW2 in zip(word, nextWord):
if charW1 != charW2:
adj_list[charW1].append(charW2)
topSorter = TopologicalSorter(adj_list)
lettersOrder = topSorter.sort()
return ''.join(lettersOrder)
class TopologicalSorter:
self.visited = set()
self.stack = []
def __init__(self, adjList: defaultdict[str,List[str]]) -> str:
self.graph = adjList
def sort(self) -> List[str]:
for vertex in self.graph:
if vertex not in self.visited:
self.top_sort(vertex)
res = []
while len(self.stack) > 0:
res.append(self.stack.pop())
return res
def top_sort(self, vertex):
self.visited.add(vertex)
for adjVertex in self.graph[vertex]:
top_sort(adjVertex)
self.stack.append(vertex)
|
class Solution:
def calculate_fibonacci(self, n) -> int:
# 0th fibonacci number is 0
if n == 0:
return 0
# 1st fibonacci number is 1
if n == 1:
return 1
if n == 2:
return 1
return self.calculate_fibonacci(n-1) + self.calculate_fibonacci(n-2)
def calculate_fibonacci_dp(self, n) -> int:
if n < 2:
return n
n1, n2 = 0, 1
for i in range(2, n+1):
temp = n1 + n2
n1, n2 = n2, temp
return n2
sol = Solution()
assert sol.calculate_fibonacci(0) == 0
assert sol.calculate_fibonacci(1) == 1
assert sol.calculate_fibonacci(2) == 1
assert sol.calculate_fibonacci(5) == 5
assert sol.calculate_fibonacci(6) == 8
assert sol.calculate_fibonacci_dp(0) == 0
assert sol.calculate_fibonacci_dp(1) == 1
assert sol.calculate_fibonacci_dp(2) == 1
assert sol.calculate_fibonacci_dp(5) == 5
assert sol.calculate_fibonacci_dp(6) == 8
|
'''
261. Graph Valid Tree
Medium
942
32
Add to List
Share
Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
Example 1:
Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]]
Output: true
Example 2:
Input: n = 5, and edges = [[0,1], [1,2], [2,3], [1,3], [1,4]]
Output: false
Note: you can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0,1] is the same as [1,0] and thus will not appear together in edges.
Accepted
121,910
Submissions
293,130
'''
from typing import List
class Solution:
def validTree(self, n: int, edges: List[List[int]]) -> bool:
if not edges and n == 1:
return True
parents = [-1 for i in range(n)]
for node1, node2 in edges:
set1 = self.get_parent(parents, node1)
set2 = self.get_parent(parents, node2)
if set1 == set2:
return False
else:
self.union(parents, set1, set2)
return True if len([p for p in parents if p < 0]) == 1 else False
def get_parent(self, parents, node):
i = node
while parents[i] != -1:
i = parents[i]
return i
def union(self, parents, set1, set2):
if set1 != set2:
parents[set2] = set1
sol: Solution = Solution()
print(sol.validTree(5, [[0,1], [0,2], [0,3], [1,4]]))
print(sol.validTree(5, [[0,1], [1,2], [2,3], [1,3], [1,4]]))
|
'''
336. Palindrome Pairs
Hard
1253
147
Add to List
Share
Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.
Example 1:
Input: ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]]
Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]
Example 2:
Input: ["bat","tab","cat"]
Output: [[0,1],[1,0]]
Explanation: The palindromes are ["battab","tabbat"]
'''
from typing import List
from pprint import pprint
class Solution:
def palindromePairs(self, words: List[str]) -> List[List[int]]:
if not words or len(words) == 0:
return
reversed_words = {w[::-1]:i for i, w in enumerate(words)} # Create reverse dictionary
results: List[List[int]] = []
for wi in range(len(words)): # For each word in words
word = words[wi]
i = len(word) - 1
if len(word) == 1:
continue
if word in reversed_words: # check reverse of whole word present
results.append([wi, reversed_words[word]])
while i >= 0:
prefix = word[0:i]
suffix = word[i:len(word)]
# print(f'prefix {prefix}; suffix {suffix}')
if self.is_palindrome(prefix) and suffix in reversed_words: # if prefix is palindrome check for suffix
results.append([reversed_words[suffix], wi])
if self.is_palindrome(suffix) and prefix in reversed_words: # if suffix is palindrome check for prefix
results.append([wi, reversed_words[prefix]])
i -= 1
return results
def is_palindrome(self, word) -> bool:
if not word or len(word.strip()) == 0:
return False
if len(word) == 1:
return True
i, j = 0, len(word) - 1
while i <= j:
if word[i] != word[j]:
return False
i += 1
j -= 1
return True
sol: Solution = Solution()
assert sol.is_palindrome('madam') == True
assert sol.is_palindrome('abcd') == False
assert sol.is_palindrome('a') == True
print(sol.palindromePairs(["abcd","dcba","lls","s","sssll"]))
print(sol.palindromePairs(["bat","tab","cat"]))
# ["abcd","dcba","lls","s","sssll"]
|
from collections import defaultdict, deque
from pprint import pformat
from typing import List
class Graph:
def __init__(self, vertices: List[str]):
self.adj_list = {vertex: defaultdict(int) for vertex in vertices}
def add_edge(self, src, dest):
self.adj_list[src][dest] = 1
def breadth_first_search(self, start: str):
queue = deque([start])
visited = {vertex: False for vertex, val in self.adj_list.items()}
visited[start] = True
res = []
while len(queue) > 0:
current_vertex = queue.popleft()
for child_key, child_value in self.adj_list[current_vertex].items():
if not visited[child_key]:
queue.append(child_key)
visited[child_key] = True
res.append(current_vertex)
return " ".join(res)
def __str__(self):
return pformat(self.adj_list)
|
'''Disjoint Set data structure to group edges of a graph into sets
Union Find is the algorithm on disjoint set which continously does union operation
Collapsing Find is another name for Union Find
Can find cycle in Undirected Graph applying Union Find on Disjoint Set'''
class Graph:
def __init__(self, vertices, directed = False):
self.adj_mat = [[0]*len(vertices) for _ in vertices]
self.vertex_lbl = {vertex: pos for pos,
vertex in enumerate(vertices)}
self.directed = directed
def add_edge(self, src, dest):
self.adj_mat[self.vertex_lbl[src]][self.vertex_lbl[dest]] = 1
if not self.directed:
self.adj_mat[self.vertex_lbl[dest]][self.vertex_lbl[src]] = 1
def union_find_cycle(self) -> bool:
self.parent = [-1] * len(self.vertex_lbl)
visitedEdges = {}
for src in range(len(self.vertex_lbl)):
for dest in range(len(self.vertex_lbl)):
if self.adj_mat[src][dest] == 1 and (visitedEdges.get(src) == None or visitedEdges.get(src) != dest):
src_parent: int = self.get_parent(src)
dest_parent: int = self.get_parent(dest)
if src_parent == dest_parent:
return True
else:
if abs(self.parent[src_parent]) >= abs(self.parent[dest_parent]):
self.parent[dest_parent] = src_parent
self.parent[src_parent] -= 1
else:
self.parent[src_parent] = dest_parent
self.parent[dest_parent] -= 1
if not self.directed:
visitedEdges[dest] = src
return False
def get_parent(self, vertex) -> int:
if self.parent[vertex] == -1:
return vertex
p = vertex
while self.parent[p] > -1:
p = self.parent[p]
if p != vertex:
self.parent[vertex] = p # collapse find
return p
|
def read_edges():
input_file = open('input1.txt', 'r')
input_data = input_file.read()
input_list = input_data.split("\n")
return_list = []
for input_row in input_list:
row_params = input_row.split(' ')
if len(row_params) != 3:
break
u = int(row_params[0])
v = int(row_params[1])
x = int(row_params[2])
if u < 0 or v < 0:
break
if u >= v:
break
edge = {
'u': u,
'v': v,
'x': x,
}
return_list.append(edge)
return return_list
def extract_values_from_list_of_dict(list, key):
retval = []
for item in list:
retval.append(item[key])
return retval
def min(list):
minimum = None
for n in list:
if minimum == None or n < minimum:
minimum = n
return minimum
def max(list):
maximum = None
for n in list:
if maximum == None or n > maximum:
maximum = n
return maximum
def get_vertices_count(edges_list):
vertices = extract_values_from_list_of_dict(edges_list, 'v')
return max(vertices) + 1
if __name__ == "__main__":
edges_list = read_edges()
vertices_count = get_vertices_count(edges_list)
print edges_list
print vertices_count
|
# 載入內建的 sys 模組並取得資訊
# import sys as system
# print(system.platform)
# print(system.maxsize)
# 建立geometry模組, 載入並使用
# import geometry
# result=geometry.distance(1,1,5,5)
# print(result)
# result=geometry.slope(1,2,5,6)
# print(result)
# 調整搜尋模組的路徑
import sys
sys.path.append("mod") #在模組的搜尋紀錄中心新增
print(sys.path) #印出模組的搜尋路徑
import geometry
print(geometry.distance(3,3,3,3))
print(geometry.slope(1,2,5,6)) |
#參數的預設資料
# def power(base,exp=0):
# print(base**exp)
# power(3,2)
# power(4)
#使用參數名稱對應
# def divide(n1,n2):
# print(n1/n2)
# divide(3,6)
# divide(n1=6,n2=3)
#無限/不訂 參數資料
def avg(*ns):
sum=0
for x in ns:
sum+=x
print(sum/len(ns))
avg(7,5,6) |
# while 迴圈
# 1+2+3+.....+10
#n=1
#sum=0 #紀錄累加的結果
#while n<=10 :
# sum=sum+n
# n+=1
#print(sum)
# for 迴圈
# 1+2+3+.....+10
# sum=0
# for x in range(1,11):
# sum=sum+x
# print(sum) |
from time import sleep
def countdown(n):
while n>0:
yield n
n -= 1
# Fibonacci数生成器
def fib():
a, b = 0, 1
while True:
a, b = b, a + b
yield a
# 偶数生成器
def even(gen):
for val in gen:
if val % 2 == 0:
yield val
def main():
gen = even(fib())
for _ in range(10):
print(next(gen))
##def main():
## for num in countdown(5):
## print(f'Countdown: {num}' )
## sleep(1)
## print('Countdown Over!')
if __name__ == '__main__':
main() |
def is_palindrome():
return "malayalam" == "malayalam"[::-1]
res=is_palindrome()
if res == True:
print("String is a palindrome")
else:
print("String is not a palindrome")
|
class User:
"""
Class that generates new instances of users
"""
user_list = [] # Empty user list
def __init__(self, first_name, last_name, email_address, password):
# docstring removed for simplicity
self.first_name = first_name
self.last_name = last_name
self.email_address = email_address
self.password = password
def save_user(self):
'''
This method saves user objects into the user_list.
'''
User.user_list.append(self)
def delete_user(self):
'''
delete_user method deletes a saved user from the user_list
'''
User.user_list.remove(self)
@classmethod
def find_by_email_address(cls, email_address):
'''
This method takes an email and returns user data that matches the email.
Args:
email: email address to search
Returns:
user information
'''
for user in cls.user_list:
if user.email_address == email_address:
return user
@classmethod
def display_users(cls,email_address):
'''
method that returns the user list
'''
return cls.user_list
@classmethod
def user_exist(cls,email_address):
'''
Method that checks if a user exists from the user listself.
Args:
password: email to search if it exists
Returns:
Boolean: True or false depending if the user exists
'''
for user in cls.user_list:
if user.password == email_address:
return True
return False
|
# https://en.wikipedia.org/wiki/Insertion_sort
def insertion_sort(collection):
for i in range(1, len(collection)):
while i > 0 and collection[i - 1] > collection[i]:
collection[i - 1], collection[i] = collection[i], collection[i - 1]
i -= 1
return collection
result = insertion_sort([0, 5, 3, 2, 2]) |
# https://leetcode.com/problems/01-matrix/
from typing import List
def updateMatrix(matrix: List[List[int]]) -> List[List[int]]:
from collections import deque
offsets = [(1, 0), (-1, 0), (0, 1), (0, -1)]
def bfs(i2, j2):
nonlocal offsets, matrix
queue = deque([(i2, j2, 1)])
visited = set()
while queue:
y, x, d = queue.popleft()
for offset in offsets:
x2, y2 = offset[0] + x, offset[1] + y
if x2 < 0 or y2 < 0:
continue
if x2 >= len(matrix[0]) or y2 >= len(matrix):
continue
if (y2, x2) not in visited and matrix[y2][x2] == 0:
return d
visited.add((y2, x2))
queue.append((y2, x2, d+1))
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] != 0:
answer = bfs(i, j)
matrix[i][j] = answer
q = [[0,0,0],
[0,1,0],
[1,1,1]]
updateMatrix(q) |
#
#
#
#
#Basic Object Oriented Programing
#Notes
#how to create a class
class Hotel():
pass
#create instances of the class
bates_motel = Hotel()
grand_budapest = Hotel()
#create unique instance of the class
class Hotel():
#Constructor
#can contain default properties, must come after required properties
def __init__(self, name_of_hotel, location, slogan='this is the default slogan'):
self.name = name_of_hotel
self.location = location
self.slogan = slogan
#Representation
#can be useful to set the default return of calling the instance
#ex bates_motel returns Bates Motel, America, this is the default slogan
def __repr__(self):
return(f'{self.name}, {self.location}, {self.slogan}')
#A function inside the class
def info(self):
print(f'{self.name} is a hotel in {self.location}')
#create instance of hotel class with properties
bates_motel = Hotel('Bates Motel', 'America')
grand_budapest = Hotel('Grand Budapest', 'Budapest')
print(bates_motel.name)
# Bates Motel
print(bates_motel.info())
# Bates Motel is a hotel in America
print(bates_motel.slogan)
# this is the default slogan
#Reassignment
bates_motel.slogan = 'Happiest Place On Earth!'
print(bates_motel.slogan)
#call __repr__
bates_motel
#import from another file
from python_file_name import Class_Name
#keep all the class files in their own folder called lib
#in that folder there should be a file called
# __init__.py that is empty file in the folder containg the Classes
#access that by
from lib.superhero import Superhero
from lib.villan import Villan
#in those .py files
#access the super Class again
from lib.character import Character
#inherit method from parent class but add its own customizations
#def strike is defined in the superClass
def strike(self, target):
#super() inherits the following Method and allows you to add
#customization for this specific class
super().strike(target)
|
from histogram import histogram
from anagram import make_anagram_dict
from math import log10
words = open("words.txt", "r").readlines()
dictionary = make_anagram_dict(words)
def anagram_count(dictionary):
"""
Given a dictionary of anagrams, this function counts how many keys have n
anagrams, for n = 2,...,12, and returns a dictionary where the keys are the
number of anagrams, and the values are log10 of the number of words in the
given dictionary with that number of anagrams.
Arguments:
:param dictionary: dictionary with keys = alphabetically sorted letters of
a word and values = anagrams of the key
:return: dictionary with keys = number of anagrams, and values = log10 of the
number of words with that many anagrams.
"""
counts = dict()
for n in range(2, 13):
count = 0
for key in dictionary:
if len(dictionary[key]) == n:
count = count + 1
if count != 0:
counts[n] = log10(count)
else:
#cannot calculate log10 of 0, so we substitute with a value of 0
counts[n] = 0
return counts
x = list(anagram_count(dictionary).keys())
y = list(anagram_count(dictionary).values())
print("""Histogram for x = number of anagrams, and y = log10 of the number of words with x number of anagrams""")
histogram(x, y, 30)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 21 07:03:15 2019
@author: prapti
"""
import cv2
import math
img = cv2.imread('lenna.png', cv2.IMREAD_GRAYSCALE)
print(img.shape)
cv2.imshow('input image',img)
'''
GAMMA TRANSFORMATION
'''
gamma = float(input("Enter Gamma Value:"))
#gamma = 1.5
for i in range(img.shape[0]):
for j in range(img.shape[1]):
intensity = img[i, j]
img[i,j] = 255 * math.pow((intensity/255), gamma)
cv2.imshow('output image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
#ref- https://stackoverflow.com/questions/16521003/gamma-correction-formula-gamma-or-1-gamma |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:yiluzhang
"""
Reinforcement learning maze example.
Red rectangle: explorer.
Black rectangles: hells [reward = -1].
Yellow bin circle: paradise [reward = +1].
All other states: ground [reward = 0].
This script is the main part which controls the update method of this example.
The RL is in RL_brain.py.
View more on my tutorial page: https://morvanzhou.github.io/tutorials/
"""
from maze_env import Maze
from RL_brain import QLearningTable
# 主循环
def update():
step_num = 0
is_hell = False
for episode in range(10000):
#print(step_num)
#print(is_hell)
if ((0 < step_num < 7) and (not is_hell)):
print(episode)
step_num = 0
# initial observation
# state,当前位置是指红色正方形的坐标,如起点正方形对角坐标分别为 (5,5) 和 (35, 35)
observation = env.reset()
# for test
# if(episode > 20):
# RL.print_q_table()
while True:
# fresh env.require continuous fresh to keep dynamic
env.render()
# RL choose action based on observation
action = RL.choose_action(str(observation))
# RL take action and get next observation and reward
observation_, reward, done = env.step(action)
if (observation_ == 'terminal' and reward == -1):
is_hell = True
else:
is_hell = False
step_num += 1
# RL learn from this transition
RL.learn(str(observation), action, reward, str(observation_))
# swap observation
observation = observation_
# break while loop when end of this episode
if done:
break
# end of game
print('game over')
env.destroy() # after operating 100 times game over and destroy the environment
# 相关注释网站https://cloud.tencent.com/developer/article/1148483
# https://blog.csdn.net/duanyajun987/article/details/78614902
if __name__ == "__main__":
env = Maze() # 使用tkinter 初始化和创建环境
RL = QLearningTable(actions=list(range(env.n_actions))) # 定义强化学习类,初始化相关参数
env.after(100, update) # call update() after 100ms
# update()
env.mainloop() #
# update() #放在后面就用不了
|
# Testing drawing 500 bezier points with algorithm from http://stackoverflow.com/questions/246525/how-can-i-draw-a-bezier-curve-using-pythons-pil/2292690#2292690
import timer
import random
from pascal_bezier import *
NUM_CURVES = 500
NUM_STEPS = 1000
R = random.randint
points = [[(R(0,999), R(0,999)), (R(0,999), R(0,999)), (R(0,999), R(0,999))] for i in range(NUM_CURVES)]
ts = [t/100.0 for t in range(NUM_STEPS)]
im = Image.new('RGBA', (1000, 1000), (155, 255, 0, 0))
draw = ImageDraw.Draw(im)
draw.rectangle([(0,0),(1000,1000)], fill=(0,0,0)) # Black as the night
with timer.Timer('Testing plotting %u bezier points with Camerons implementation') as t:
for p in points:
bezier = make_bezier(p)
points = bezier(ts)
#draw.polygon(points)
#im.save('outt.png')
|
import os
import csv
# Path to collect data from the Resources folder
votes_csv = os.path.join('Resources', 'election_data.csv')
#Function created to more easily check whether candidate already has an entry in the candidate list[]
def candidate_in_list(candidateList, aCandidate):
name = str(aCandidate)
inList = bool(False)
#Cycle through the current candidate list, if the name is found set inList to true
for candidate in candidateList:
if candidate == name:
inList = True
#return whether the candidate was found or not
return inList
#Define Variables for candidate calculations
totalVotes = 0
winner = str("Unknown")
#Define List for Candidate List in form [Candidate1, Candidate1's VoteCount, Candidate 2, Candidate2's VoteCount,..]
candidateList = []
#Variables to create and update candidateList
candidateIndex = int(0)
candidateVotes = int(0)
# Open and read the votes csv
with open(votes_csv) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=",")
#Skip the header
next(csv_file)
for row in csv_reader:
#Increment total vote count
totalVotes = totalVotes + 1
#If the candidate is already in the list ( found by function ), add to their vote counter
if candidate_in_list(candidateList, row[2]):
candidateIndex = candidateList.index(str(row[2])) #locate list index of candidate
candidateIndex = int(candidateIndex) + 1 #locate list index of the candidate's vote counter
candidateVotes = int(candidateList[candidateIndex]) #capture their number of current votes
candidateVotes = int(candidateVotes) + 1 #add to the count from the vote data
candidateList[candidateIndex] = candidateVotes #reset the candidate's vote counter to the new value
#create a new candidate entry with candidate name and set their adjacent vote count to register their first vote
else:
candidateList.append(str(row[2]))
candidateList.append(1)
#Candidate list now built from file and can be used for processing outputs
#Print screen headers and total votes counted
print('\n'"Election Results")
print("-----------------------------")
print(f"Total Votes: {totalVotes}")
print("-----------------------------")
#Define some helpful output variables
i = int(0)
printName = ""
printVotes = ""
votePercentage = float(0)
mostVotes = int(0)
#Print Results by Candidate
#Use while loop to go through candidate List to collect and print the voting results to screen
while i < len(candidateList):
printName = str(candidateList[i])
i = i + 1 #jump to the candidate's adjacent vote count in list
printVotes = str(candidateList[i])
votePercentage = float(int(printVotes)/int(totalVotes)*100)
#format percentage
votePercentage = round(votePercentage,2)
#Check with each candidate to track largest number of votes to set the winner
if mostVotes < int(candidateList[i]):
mostVotes = int(candidateList[i])
winner = str(printName)
#Print candidate line
print(f"{printName}: {votePercentage}% ({printVotes})")
i = i + 1 #continue to next candidate in list
#Print the winner
print("-----------------------------")
print(f"Winner: {winner}")
print("-----------------------------")
# Specify the file to write to
output_path = os.path.join("Analysis", "election_results.txt")
# Open the file using "write" mode. Specify the variable to hold the contents
with open(output_path, 'w', newline='') as file:
file.write("Election Results"'\n')
file.write("-----------------------------"'\n')
file.write(f"Total Votes: {totalVotes}"'\n')
file.write("-----------------------------"'\n')
#Use while loop to go through candidate List to collect and print the voting results to file
i = int(0) #reset i from previous loop, reuse existing variables from screen prints
while i < len(candidateList):
printName = str(candidateList[i])
i = i + 1 #jump to adjacent candidate vote count in list
printVotes = str(candidateList[i])
votePercentage = float(int(printVotes)/int(totalVotes)*100)
#format percentage
votePercentage = round(votePercentage,2)
#Winner has already been calculated
#Write candidate line to file
file.write(f"{printName}: {votePercentage}% ({printVotes})"'\n')
i = i + 1 #continue to next candidate in list
#Print the winner to file
file.write("-----------------------------"'\n')
file.write(f"Winner: {winner}"'\n')
file.write("-----------------------------"'\n')
#File read and output complete |
def fibonacci(x):
if x<0:
print("invalid input")
elif x==0:
return 0
elif x==1:
return 1
else:
return fibonacci(x-1)+fibonacci(x-2)
print("Fabonacci series is as follows: ")
i=0
while i<10:
print(int(fibonacci(i)))
i=i+1
print("done")
|
listaclientes = []
clientes = 0
while clientes < 500:
cliente = input("Nombre:")
producto = input("Su producto es:")
costo = float(input("Su costo es:"))
registro = dict(cliente=cliente, producto=producto, costo=costo)
listaclientes.append(registro)
# final = input("¿Se agregara otro cliente a el registro?")
# while final != ("Si") or final != ("No")
# print(La respuesta debe limitarse a"Si"o"No")
# final = input ("¿Se agregara otro cliente a el registro?")
# if final == ("Si"):
# clientes += 1
# else if final == ("No"):
# break
# for registro in listaclientes:
# print (registro)
# costostotales = input(“¿Quiere consultar el costo total de el día?” )
# while costostotales != (“Si”) or costostotales != (“No”):
# print(La respuesta debe limitarse a "Si" o "No")
# costostotales = input(“¿Quiere consultar el costo total de el día?” )
# if consultaCostoTotal == ("si"):
# costos = float(sum(costo))
# print(costos)
|
myList = LinkedList()
myList.add(500)
myList.add(100)
myList.add(200)
myList.add(300)
myList.add(500)
myList.add(400)
myList.add(500)
myList.add(500)
myList.add(600)
#
myList.isEmpty()
# Adding elements to linked list
myList.add()
# Returning the size of the linked list
myList.size()
# Finding elements in the linked list
myList.search()
# Removing element from linked list
myList.remove
#Printing all the elements in the List
myList.printList()
# Finding all instances of an element in the list
myList.findAll()
# Inserting elements into a list
myList.insert()
# Removing item at specified index
myList.popAtIndex()
# Appending a new element to the end of linked list
myList.appendLast()
|
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
#first count the length of the linked list
temp = head
if head is None:
return head
count = 1
stack = []
queue = []
while temp.next is not None:
stack.append(temp.val)
temp = temp.next
count += 1
print count
for i in range(count / 2):
old_next = head.next
head.next.val = stack.pop()
head.next.next = old_next
head = old_next
lis = [1, 2, 3, 4]
f = Solution()
f.reorderList(lis)
print lis
|
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def rorateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if head == None:
return head
if k == 0:
return head
count = 1
old_head = head
temp = head
while temp.next:
temp = temp.next
count += 1
step = count - k % count
if step == count:
return head
new_head = head
new_tail = None
for i in range(step):
new_tail = new_head
new_head = new_head.next
new_tail.next = None
tail = new_head
if tail == None:
tail.next = old_head
else:
while tail.next:
tail = tail.next
tail.next = old_head
return new_head
|
# Given n non-negative integers a1, a2, ..., an ,
# where each represents a point at coordinate (i, ai).
# n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0).
# Find two lines, which, together with the x-axis forms a container,
# such that the container contains the most water.
# https://leetcode.com/problems/container-with-most-water/
# Example:
# Input: height = [1,8,6,2,5,4,8,3,7]
# Output: 49
# Solution:
from collections import defaultdict
class Solution:
# Shrinking the window approach is used traversing from left and right towards the middle
def maxArea(self, height: List[int]) -> int:
ptr1 = 0
ptr2 = len(height)-1
max_area = 0
while ptr1 < ptr2:
area = min(height[ptr1],height[ptr2]) * (ptr2-ptr1)
max_area = max(max_area, area)
if height[ptr1] <= height[ptr2]:
ptr1+=1
else:
ptr2-=1
return max_area
|
C = 0
farenheit = 0
for C in range(10, 110, 10) :
farenheit = C * 1.8 + 32
print("A temperatura em graus é", C, "C⁰", "e em farenheit", farenheit, "F")
|
ini = int(input('insira o limite inferior :'))
fini = int(input('insira o limite superior'))
soma = 0
i = ini
f = 1
y = 0
while ini <= i <= fini :
soma = ini + ini + f
i += 1
f += 1
y = y + soma
print(soma)
|
a = {'a':3, 'b': 4, 'c': 5}
print(a['a'])
a['a'] += 1
print(a)
|
A = int(input("digite Votos validos de A:"))
B = int(input("digite Votos validos de B:"))
C = int(input("digite Votos validos de C:"))
nda = int(input("digite Votos nulos de A:"))
ndb = int(input("digite Votos nulos de B:"))
ndc = int(input("digite Votos nulos de C:"))
eba = int(input("digite Votos em branco de A:"))
ebb = int(input("digite Votos em branco de B:"))
ebc = int(input("digite Votos em branco de C:"))
vnva = int(input("digite Votos não validos de A:"))
vnvb = int(input("digite Votos não validos de B:"))
vnvc = int(input("digite Votos não validos de C:"))
totaleleitores = (A + B + C + nda + ndb + ndc + eba + ebc)
percentual = float((A + B + C) * 100 / totaleleitores)
percentA = float((A * 100) / totaleleitores)
percentB = float((B * 100) / totaleleitores)
percentC = float((C * 100) / totaleleitores)
percentnul = float((vnva + vnvb + vnvc) * 100 / totaleleitores)
percenteB = float((eba + ebb + ebc) * 100 / totaleleitores)
print("Percentagem de eleitores é:", percentual)
print("Percentagem de votos em A:", percentA)
print("Percentagem de votos em B:", percentB)
print("Percentagem de votos em C:", percentC)
print("Percentagem de votos nulos :", percentnul)
print("Percentagem de votos em Branco:", percenteB)
|
a = int(input('insira num:'))
b = int(input('insira num:'))
c = int(input('insira num:'))
if a > b and b >c :
print(a, b, c)
print('o maior numero é {}'.format(a))
elif b > a and a > c :
print(a, b, c)
print('o maior numero é {}'.format(b))
else :
print(a, b, c)
print('o maior numero é {}'.format(c))
|
mes = int(input("digite o mes:"))
if ((mes <= 0) or (mes > 12)) :
print("mes invalido")
else :
ano = int(input("insira valor de anos:"))
if (ano % 4 == 0) and (ano % 100 != 0) :
print("ano bissexto")
elif (ano % 400 == 0) :
print("ano bissexto")
else :
print("ano comun")
|
'''
Created on 15 Nov 2014
@author: MuresanVladut
'''
class Student:
def __init__(self,idd,name,group):
self.idd=idd
self.name=name
self.group=group
def getId(self):
return self.idd
def getName(self):
return self.name
def getGroup(self):
return self.group
def setId(self,idd):
self.idd=idd
def setName(self,name):
if not isinstance(name,str):
raise TypeError
self.name=name
def setGroup(self,group):
self.group=group
def __str__(self):
'''return "The student "+self.name+" with the id "+str(self.idd)+" is in the group "+str(self.group)'''
return "The student "+self.getName()+" with the id "+str(self.getId())+" is in the group "+str(self.getGroup())
def __repr__(self):
return str(self.idd)+":"+str(self.name)+":"+str(self.group)
|
import sys
from typing import Tuple, Optional
global nums
def sum2(start: int, end: int, target: int) -> Optional[Tuple[int, int]]:
"""
Find two number in the nums[start:end] whose sum is equal to target.
"""
seen = set()
for i in range(start, end):
n = nums[i]
if target - n in seen:
return (n, (target - n))
else:
seen.add(n)
return None
if __name__ == "__main__":
nums = sorted(map(int, sys.stdin))
end = len(nums)
for i, num in enumerate(nums):
ret = sum2(i + 1, end, 2020 - num)
if ret:
print(num * ret[0] * ret[1])
|
def compare(point, position):
x = 1 if point[0]-position[0]>0 else (0 if point[0]-position[0]==0 else -1)
y = 1 if point[1]-position[1]>0 else (0 if point[1]-position[1]==0 else -1)
return x, y
# lx: the X position of the light of power
# ly: the Y position of the light of power
# tx: Thor's starting X position
# ty: Thor's starting Y position
lx, ly, tx, ty = [int(i) for i in input().split()]
directions = {
(0,-1):"N",
(1,-1):"NE",
(1,0):"E",
(1,1):"SE",
(0,1):"S",
(-1,1):"SW",
(-1,0):"W",
(-1,-1):"NW"
}
while True:
move = compare((lx,ly),(tx,ty))
print(directions[move])
tx+=move[0]
ty+=move[1]
|
import datetime
def array_to_date(array):
return datetime.date(array[2], array[1], array[0])
def today_to_array():
today = datetime.date.today()
return [today.day, today.month, today.year]
def array_to_string(array):
arr = [str(number) for number in array]
return '-'.join(arr)
def string_to_array(array):
array = array.split('-')
array = [int(element) for element in array]
return array
# Approximate
def date_distance(array1, array2):
return array1[2]*365 + array1[1]*30 + array1[0] - array2[2]*365 - array2[1]*30 - array2[0]
# returns True if the first date is later than the second one
def is_later(array1, array2):
if array1[2] < array2[2]:
return True
if array1[1] < array2[1]:
return True
if array1[0] < array2[0]:
return True
return False
# Same as input but waits for non EOF non space input
def iinput():
result = input()
while result == '' or result == ' ':
result = input()
return result
|
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.queue = collections.OrderedDict()
def get(self, key):
if key not in self.queue:
return -1
value = self.queue.pop(key)
self.queue[key] = value
return self.queue[key]
def put(self, key, value):
if key in self.queue:
self.queue.pop(key)
elif len(self.queue.items()) == self.capacity:
self.queue.popitem(last=False)
# OrderedDict.popitem()有一个可选参数last(默认为True),当last为True时它从OrderedDict中删除最后一个键值对并返回该键值对,当last为False时它从OrderedDict中删除第一个键值对并返回该键值对。
self.queue[key] = value
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.