blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
42d56f46cdb8e84ff52ed1118b8ebb97198d36ec | zhou-zhenyi/sicp | /c1_1_elements/s11_block.py | 431 | 3.640625 | 4 | def sqrt(x):
def sqrt_iter(guess):
if good_enough(guess):
return guess
else:
return sqrt_iter(improve(guess))
def improve(guess):
return average(guess, (x / guess))
def average(x, y):
return (x + y) / 2
def good_enough(guess):
return abs(square(guess) - x) < 0.001
def square(x):
return x * x
return sqrt_iter(1.0)
print(sqrt(9)) |
fadb969735d518e2ad47ea2aa34eeeaa8450ca55 | 2292527883/Learn-python-3-to-hard-way | /ex15/ex15.py | 844 | 3.5 | 4 | from sys import argv
script, filename, py1 = argv # 从外部获取参数 赋值给script ,filename
txt = open(filename) # 打开 filenmae 文件赋值给txt变量
print(f"Here's your file {filename} :")
print(txt.read()) # 读取txt变量的值
print("script的意思是:", script)
print("Type the filename again :")
file_again = input(">")
txt_again = open(file_again) # 再读取一遍filename的文件
print(txt_again.read())
py = open(py1)
print(py.read())
# 第一次报错py1 不是字符串,没有read属性
# 最后检查发现写成了print(py1.read())
# 第二次报错UnicodeDecodeError: 'gbk' codec can't decode byte”
# 在网上查找原因是使用了GBK编码的文件名:为中文
# 遂编辑TXT文本中的中文改成英文
# 顺利运行
# 结论:命令行运行要使用一致编码的文字
|
d4605dcedf034a697a4ccf804f04af1e3ae85f12 | mconchac/Django | /1.py | 978 | 4.25 | 4 | # este es el comando para imprimir en consola
""" esta es otra forma de hacer comentarios en varias líneas
como en este ejemplo
y se cierra con comillas dobles 3 veces
"""
print("hola soy yo, mcc")
print (100)
print ("soy nivelpro")
str("test2")
lista = ["string", 1, [1,2,3], "true"]
# definición de listas
{"name": "Carlos"}
# definición de diccionarios
test1 = "Colombia"
# definición de variables
print (test1)
print (lista[3])
def test1():
return "test"
print(test1())
tupla1 = ("python", "django")
print(tupla1[1])
print(int(5.2))
print(len("estoy en curso de stack"))
print(type(5))
print(sum([5,7,3]))
print(sorted([10,50,25]))
producto = ("carne")
precio = (100)
if (producto == "papas"):
if (precio >= 50):
precio = (precio - (precio*10/100))
print(producto, "a $", int (precio))
elif (producto == "carne"):
print("por hoy", producto, "gratis")
for i in range(4):
print(i)
x = 0
while x < 10:
print (x)
x +=1 |
b875727edfd22560eacdeef3a35d7f8a0165a283 | SongJialiJiali/test | /leetcode_409.py | 655 | 3.515625 | 4 | #leetcode 409. 最长回文串
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
resoult={}
for i in s:
resoult[i]=s.count(i)
num = 0
resoult_q = 0
for keys in resoult:
if resoult[keys] % 2 == 0:
num = num + resoult[keys]
elif resoult[keys] % 2 != 0 and resoult[keys] > 1:
num = num + resoult[keys] - 1
resoult_q += 1
else:
resoult_q += 1
if resoult_q > 0:
return num+1
else:
return num
|
3446262a43cfc47aef94c4073f585fd2fa43d88c | IswaryaBaskaran/Python-Programs | /factorial.py | 204 | 4.25 | 4 | '''TO FIND FACTORIAL OF A GIVEN NUMBER'''
n = int(input("Enter a number: "))
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
print(recur_factorial(n)) |
d7c5fc8f4f253d5933902ec0333e9a30f480a39f | sbo97t/BootCamp | /C to F converter.py | 427 | 4.125 | 4 | # C to F converter
print("Enter a temp in Celsius to convert to Fahrenheit")
temp = float(input("Celsius "))
print((temp * 9/5) + 32)
print("Would you like to convert from Farhneheit to Celsius? (Y or N) ")
answer=input()
if answer=="Y":
print("Enter a temp in Fahrenheit to convert to Celsius")
tempF = float(input("Fahrenheit "))
print((tempF - 32) * 5/9)
else:
print("Thanks for playing!")
|
c8e5fb48af6221d337e58f956bbfab8f490f1d9c | YeomeoR/codewars-python | /well_of_ideas.py | 920 | 3.96875 | 4 | # In this kata you need to check the provided array (x) for good ideas 'good' and bad ideas 'bad'. If there are one or two good ideas, return 'Publish!', if there are more than 2 return 'I smell a series!'. If there are no good ideas, as is often the case, return 'Fail!'.
def well(x):
good = x.count("good")
return "I smell a series!" if good > 2 else "Publish!" if good else "Fail!"
# good = 0
# bad = 0
# for ele in x:
# if ele == 'good':
# good += 1
# "elif ele == 'bad':"
# bad += 1
# if good > 2:
# return "I smell a series!"
# elif good > 0 and good < 3:
# return "Publish!"
# else:
# return "Fail!"
print(well(['bad', 'bad', 'bad']), 'Fail!')
print(well(['good', 'bad', 'bad', 'bad', 'bad']), 'Publish!')
print(well(['good', 'bad', 'bad', 'bad', 'bad', 'good', 'bad', 'bad', 'good']), 'I smell a series!') |
3c94c7256f428461154f03ca144c31a70482c981 | d1rtyst4r/archivetempLearningPythonGPDVWA | /Chapter03/tasks/guests.py | 2,720 | 4.15625 | 4 | guests = ['elizabeth', 'albert', 'peteris', 'jonny']
print("Hi " + guests[0].title() + ", I would like to invite you to my party!")
print("Hi " + guests[1].title() + ", I would like to invite you to my party!")
print("Hi " + guests[2].title() + ", I would like to invite you to my party!")
print("Hi " + guests[3].title() + ", I would like to invite you to my party!")
print("Here is number of guests: " + str(len(guests)) + ".")
# Update the list
guest_who_could_not_come = guests.pop(0)
guests.insert(0, 'theodore')
print("\n" + guest_who_could_not_come.title() + "'ll mise the party.")
print("\nHi " + guests[0].title() + ", I would like to invite you to my party!")
print("Hi " + guests[1].title() + ", I would like to invite you to my party!")
print("Hi " + guests[2].title() + ", I would like to invite you to my party!")
print("Hi " + guests[3].title() + ", I would like to invite you to my party!")
print("Here is number of guests: " + str(len(guests)) + ".")
# Add new guests
guests.insert(0, "richard")
guests.insert(3, "cesar")
guests.append("cleo")
print("\nHi " + guests[0].title() + ", I would like to invite you to my party!")
print("Hi " + guests[1].title() + ", I would like to invite you to my party!")
print("Hi " + guests[2].title() + ", I would like to invite you to my party!")
print("Hi " + guests[3].title() + ", I would like to invite you to my party!")
print("Hi " + guests[4].title() + ", I would like to invite you to my party!")
print("Hi " + guests[5].title() + ", I would like to invite you to my party!")
print("Hi " + guests[6].title() + ", I would like to invite you to my party!")
print("Here is number of guests: " + str(len(guests)) + ".")
# Remove guests
print("\nHi, sorry but I have only two places, so some guests will mise my party.")
guest_who_could_not_come = guests.pop()
print("Hi " + guest_who_could_not_come.title() + ", sorry but party canceled!")
guest_who_could_not_come = guests.pop()
print("Hi " + guest_who_could_not_come.title() + ", sorry but party canceled!")
guest_who_could_not_come = guests.pop()
print("Hi " + guest_who_could_not_come.title() + ", sorry but party canceled!")
guest_who_could_not_come = guests.pop()
print("Hi " + guest_who_could_not_come.title() + ", sorry but party canceled!")
guest_who_could_not_come = guests.pop()
print("Hi " + guest_who_could_not_come.title() + ", sorry but party canceled!")
print("\nHi " + guests[0].title() + ", I would like to invite you to my party!")
print("Hi " + guests[1].title() + ", I would like to invite you to my party!")
print("Here is number of guests: " + str(len(guests)) + ".")
# Remove by del
del guests[1]
del guests[0]
print(guests)
print("Here is number of guests: " + str(len(guests)) + ".")
|
150b41309be6793b942ce188e9e81d74a1be7143 | CFoyer-Portfolio/PyFEA | /pyfea/tools/plotting.py | 1,864 | 3.5625 | 4 | # -*- coding: utf-8 -*-
#Created on Thu Jun 20 23:13:03 2019
#@author: Christophe
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D; _ = Axes3D #hide spyder warning msg
import numpy as np
import pyvista as pv
def scatter3d_mpl(points):
# plot the surface
plt3d = plt.figure().gca(projection='3d')
ax = plt.gca()
ax.scatter(points[:,0], points[:,1], points[:,2], color='green')
#Set equal axes. Thank you P. Sharpe :)
def set_axes_equal(ax):
'''Make axes of 3D plot have equal scale so that spheres appear as spheres,
cubes as cubes, etc.. This is one possible solution to Matplotlib's
ax.set_aspect('equal') and ax.axis('equal') not working for 3D.
Input
ax: a matplotlib axis, e.g., as output from plt.gca().
'''
x_limits = ax.get_xlim3d()
y_limits = ax.get_ylim3d()
z_limits = ax.get_zlim3d()
x_range = abs(x_limits[1] - x_limits[0])
x_middle = np.mean(x_limits)
y_range = abs(y_limits[1] - y_limits[0])
y_middle = np.mean(y_limits)
z_range = abs(z_limits[1] - z_limits[0])
z_middle = np.mean(z_limits)
# The plot bounding box is a sphere in the sense of the infinity
# norm, hence I call half the max range the plot radius.
plot_radius = 0.5*max([x_range, y_range, z_range])
ax.set_xlim3d([x_middle - plot_radius, x_middle + plot_radius])
ax.set_ylim3d([y_middle - plot_radius, y_middle + plot_radius])
ax.set_zlim3d([z_middle - plot_radius, z_middle + plot_radius])
plt.tight_layout()
set_axes_equal(ax)
def scatter3d(points):
p = pv.BackgroundPlotter()
point_cloud = pv.PolyData(points)
p.add_mesh(point_cloud)
p.enable_eye_dome_lighting()
p.show(window_size=[1024, 768]) |
3e253220d9a5e827b6cb7d0245aae9ff889ac9e2 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/leap/d9f5e279b7f94c1ab1f5974360770eb7.py | 256 | 3.65625 | 4 | '''
Excercism Problem #2
Iteration 1
'''
def is_leap_year(test_year):
if (test_year % 4 == 0 and test_year % 100 != 0) or (test_year % 400 == 0):
return True
return False
def main():
pass
if __name__ == '__main__':
main()
|
07f46340cce040da895ecdfefdd9c283c412fa13 | laobadao/Machine-Learning-U | /ml_assign/P1_Predicting_Boston_Housing_Prices/boston_housing.py | 6,541 | 3.734375 | 4 | """Load the Boston dataset and examine its target (label) distribution."""
# Load libraries
import numpy as np
import pylab as pl
from sklearn import datasets
from sklearn.tree import DecisionTreeRegressor
from sklearn import cross_validation
from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error, make_scorer
from sklearn.grid_search import GridSearchCV
def load_data():
"""Load the Boston dataset."""
boston = datasets.load_boston()
return boston
def explore_city_data(city_data):
"""Calculate the Boston housing statistics."""
# Get the labels and features from the housing data
housing_prices = city_data.target
housing_features = city_data.data
# Size of data
print "No. of data points: {}".format(housing_features.shape[0])
# Number of features
print "No. of features: {}".format(housing_features.shape[1])
# Minimum housing price
print "Minimum housing price: {}".format(min(housing_prices))
# Maximum housing price
print "Maximum housing price: {}".format(max(housing_prices))
# Mean housing price
print "Mean housing price: {}".format(np.mean(housing_prices))
# Calculate median?
print "Median housing price: {}".format(np.median(housing_prices))
# Calculate standard deviation?
print "Standard deviation of housing prices: {}".format(np.std(housing_prices))
def performance_metric(label, prediction):
"""Calculate and return the appropriate performance metric."""
mse = mean_squared_error(label, prediction)
return mse
def split_data(city_data):
"""Randomly shuffle the sample set. Divide it into training and testing set."""
# Get the features and labels from the Boston housing data
X, y = city_data.data, city_data.target
# Split up the dataset between training and testing
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.45, random_state=42)
return X_train, y_train, X_test, y_test
def learning_curve(depth, X_train, y_train, X_test, y_test):
"""Calculate the performance of the model after a set of training data."""
# We will vary the training set size so that we have 50 different sizes
sizes = np.linspace(1, len(X_train), 50)
train_err = np.zeros(len(sizes))
test_err = np.zeros(len(sizes))
print "Decision Tree with Max Depth: "
print depth
for i, s in enumerate(sizes):
# Create and fit the decision tree regressor model
regressor = DecisionTreeRegressor(max_depth=depth)
regressor.fit(X_train[:s], y_train[:s])
# Find the performance on the training and testing set
train_err[i] = performance_metric(y_train[:s], regressor.predict(X_train[:s]))
test_err[i] = performance_metric(y_test, regressor.predict(X_test))
# Plot learning curve graph
learning_curve_graph(sizes, train_err, test_err)
def learning_curve_graph(sizes, train_err, test_err):
"""Plot training and test error as a function of the training size."""
pl.figure()
pl.title('Decision Trees: Performance vs Training Size')
pl.plot(sizes, test_err, lw=2, label = 'test error')
pl.plot(sizes, train_err, lw=2, label = 'training error')
pl.legend()
pl.xlabel('Training Size')
pl.ylabel('Error')
pl.show()
def model_complexity(X_train, y_train, X_test, y_test):
"""Calculate the performance of the model as model complexity increases."""
print "Model Complexity: "
# We will vary the depth of decision trees from 2 to 25
max_depth = np.arange(1, 25)
train_err = np.zeros(len(max_depth))
test_err = np.zeros(len(max_depth))
for i, d in enumerate(max_depth):
# Setup a Decision Tree Regressor so that it learns a tree with depth d
regressor = DecisionTreeRegressor(max_depth=d)
# Fit the learner to the training data
regressor.fit(X_train, y_train)
# Find the performance on the training set
train_err[i] = performance_metric(y_train, regressor.predict(X_train))
# Find the performance on the testing set
test_err[i] = performance_metric(y_test, regressor.predict(X_test))
# Plot the model complexity graph
model_complexity_graph(max_depth, train_err, test_err)
def model_complexity_graph(max_depth, train_err, test_err):
"""Plot training and test error as a function of the depth of the decision tree learn."""
pl.figure()
pl.title('Decision Trees: Performance vs Max Depth')
pl.plot(max_depth, test_err, lw=2, label = 'test error')
pl.plot(max_depth, train_err, lw=2, label = 'training error')
pl.legend()
pl.xlabel('Max Depth')
pl.ylabel('Error')
pl.show()
def fit_predict_model(city_data):
"""Find and tune the optimal model. Make a prediction on housing data."""
# Get the features and labels from the Boston housing data
X, y = city_data.data, city_data.target
# Setup a Decision Tree Regressor
regressor = DecisionTreeRegressor()
# Setup parameters and scores for model optimization through Grid Search
parameters = {'max_depth':(1,2,3,4,5,6,7,8,9,10)}
scorer = make_scorer(mean_squared_error, greater_is_better=False)
gs = GridSearchCV(regressor, parameters, scoring=scorer)
gs.fit(X, y)
# Select the best settings for regressor
reg = gs.best_estimator_
# Fit the learner to the training data
print "Final Model: "
print reg.fit(X, y)
# Use the model to predict the output of a particular sample
x = [11.95, 0.00, 18.100, 0, 0.6590, 5.6090, 90.00, 1.385, 24, 680.0, 20.20, 332.09, 12.13]
y = reg.predict(x)
print "House: " + str(x)
print "Prediction: " + str(y)
def main():
"""Analyze the Boston housing data. Evaluate and validate the
performanance of a Decision Tree regressor on the housing data.
Fine tune the model to make prediction on unseen data."""
# Load data
city_data = load_data()
# print city_data
# Explore the data
explore_city_data(city_data)
# Training/Test dataset split
X_train, y_train, X_test, y_test = split_data(city_data)
# Learning Curve Graphs
max_depths = [1,2,3,4,5,6,7,8,9,10]
for max_depth in max_depths:
learning_curve(max_depth, X_train, y_train, X_test, y_test)
# # Model Complexity Graph
model_complexity(X_train, y_train, X_test, y_test)
# # Tune and predict Model
fit_predict_model(city_data)
if __name__ == "__main__":
main()
|
06cd942275d2508fae26cae6706ae3c60ea0cc18 | timetobye/TIL | /Python/7_Python_utility/dict_union/dict_union.py | 1,127 | 4.1875 | 4 | """
Dict Union 은 Python 3.9 에 추가된 기능(그 이전 버전은 구동 안 됨)
- https://www.python.org/dev/peps/pep-0584/#id18
- https://www.python.org/dev/peps/pep-0584/#specification
병합 연산자 '|' 를 이용하여 Dictionary 를 병합할 수 있다.
- 참고 문서 : https://betterprogramming.pub/new-union-operators-to-merge-dictionaries-in-python-3-9-8c7dbbd1080c
"""
# 1
d = {'spam': 1, 'eggs': 2, 'cheese': 3}
e = {'cheese': 'cheddar', 'aardvark': 'Ethel'}
print(d | e)
"""
Dict union will return a new dict consisting of the left operand merged with the right operand,
each of which must be a dict (or an instance of a dict subclass). If a key appears in both operands,
the last-seen value (i.e. that from the right-hand operand) wins:
{'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}
"""
# 2
print(e | d)
"""
{'cheese': 3, 'aardvark': 'Ethel', 'spam': 1, 'eggs': 2}
"""
# 3
d |= e
print(d)
"""
{'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}
"""
# 4
d |= [('spam', 999)]
print(d)
"""
{'spam': 999, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}
""" |
151ca6bd31b3227de252e47ecafd2d08a59902b5 | hsl39/PythonTicTacToe | /board.py | 1,044 | 3.9375 | 4 | class Space:
def __init__(self, x, y):
self.value = " "
self.coord = [x,y]
def setValue(self, value):
self.value = value
def printSpace(self):
print("[" + self.value + "]", end = "")
def getXCoord(self):
return self.coord[0]
def getYCoord(self):
return self.coord[1]
class Board:
#Tic Tac Toe does not have dynamic board sizes, 3x3 by default.
def __init__(self):
self.spaces = []
#Index starts at 1 for clarity
for x in range(1,4):
for y in range(1,4):
self.spaces.append( Space(x,y) )
def printBoard(self):
currRow = 0
#This is pretty gross, but it works
print(" 1 2 3", end= "")
for x in self.spaces:
if(x.getXCoord() > currRow):
#Print a new line on new row
print("\n" + str(currRow), end = "")
currRow += 1
x.printSpace()
def winCheck(self):
return
|
991656767c61470b5cde77f5f6037412e3b7a7de | VUW-FAIR/blockchains_web_scraping | /github/jsontocsv_for_github.py | 2,565 | 3.578125 | 4 | import os
import pandas
from pandas.io.json import json_normalize
import json
'''
Make new subdirectory of specified name
'''
def make_dir(name):
newpath = r'.\\' + "json_to_csv" + '\\' + name
if not os.path.exists(newpath):
print("making dir")
os.makedirs(newpath)
'''
Takes your root directory for github folder (after being parsed by github scraper to json)
and converts json files to csv of new folders of same structure.
'''
def json_to_csv():
rootdir = '.\GitHubScraping'
for subdir, dirs, files in os.walk(rootdir):
# print(str(subdir))
for file in files:
# print(file)
dir_to_file = os.path.join(subdir, file)
print(dir_to_file)
userName = dir_to_file.split('\\')[2].strip()
repoName = dir_to_file.split('\\')[3].strip()
typeName = dir_to_file.split('\\')[4].strip()
path = userName + "\\" + repoName + "\\" + typeName
print((dir_to_file.split('\\')[5].strip())[0:-5])
make_dir(path)
convert_to_csv(dir_to_file, '.\\' + "json_to_csv" + '\\' + path + '\\' + str((dir_to_file.split('\\')[5].strip())[0:-5]) + ".csv")
print(userName)
'''
Converts your json file to to CSV.
Normalizes data and then saves in output directory.
'''
def convert_to_csv(inputDir, outputDir):
with open(inputDir, 'r', encoding="utf-8") as json_file:
data = json.load(json_file)
df = pandas.io.json.json_normalize(data)
df.to_csv(outputDir)
print(df)
'''
Joins multiple CSV files together (of same structure)
by finding all files of subdirectory and appending them
to one file.
'''
def join_files_together():
rootdir = '.\json_to_csv'
for subdir, dirs, files in os.walk(rootdir):
print(str(subdir))
print((subdir.split('\\')))
if(len(subdir.split('\\')) > 4):
with open(subdir + "\\" + subdir.split('\\')[4].strip() + "_combined_.csv", 'a', encoding="utf8") as fout:
for i in range (0, len(files)):
if(i == 0):
for line in open(subdir + "\\" + files[i], encoding="utf8"):
fout.write(line)
else:
f = open(subdir + "\\" + files[i], encoding="utf8")
next(f) #skipping the header
for line in f:
fout.write(line)
json_to_csv()
join_files_together()
|
59755ad367ec9d930b24a417f9c0ced30b1191f7 | eugenechung81/coding-java-projects | /distributed-cache-py-analysis/reference/test.py | 343 | 3.515625 | 4 | import csv
from collections import defaultdict
reader = csv.DictReader(open('test.csv', newline=''))
cities = defaultdict(int)
for row in reader:
cities[row["CITY"]] += int(row["AMOUNT"])
writer = csv.writer(open('out.csv', 'w', newline = ''))
writer.writerow(["CITY", "AMOUNT"])
writer.writerows([city, cities[city]] for city in cities)
|
14c890c289fde88451b0ff25e55af541faace580 | katieunger/hmc-homework | /lesson_3/lesson_3_states.py | 5,459 | 4.15625 | 4 | # Challenge Level: Beginner
# Background: You have a text file with all of the US state names:
# states.txt: See section_07_(files).
#
# You also have a spreadsheet in comma separated value (CSV) format, state_info.csv. See also section_07_(files)
# state_info.csv has the following columns: Population Rank, State Name, Population, US House Members, Percent of US Population
# Challenge 1: Open states.txt and use the information to generate an HTML drop-down menu as in: https://github.com/shannonturner/python-lessons/blob/master/playtime/lesson02_states.py
with open("states.txt", "r") as states_file:
statesList = states_file.read().split("\n")
for index, state in enumerate(statesList):
statesList[index] = state.split("\t")
print("<select>")
for state in statesList:
print("<option value='{0}'>{1}</option>".format(state[0], state[1]))
print("</select>")
# Challenge 2: Save the HTML as states.html instead of printing it to screen.
# Your states.html should look identical (or at least similar) to the one you created in the Lesson 2 playtime, except you're getting the states from a file instead of a list.
with open("states.html", "w") as statesSelectFile:
statesSelectFile.write("<select>\n")
for state in statesList:
statesSelectFile.write("\t<option value='{0}'>{1}</option>\n".format(state[0], state[1]))
statesSelectFile.write("</select>")
# Challenge 3: Using state_info.csv, create an HTML page that has a table for *each* state with all of the state details.
# # Read state_info.csv into stateInfoList, splitting on newlines
with open("state_info.csv", "r") as stateInfoFile:
stateInfoList = stateInfoFile.read().split("\n")
print("{0}\n".format(stateInfoList))
# # Make stateInfoList into a list of smaller lists by splitting on commas
# # Note that each "row" in CSV is contained in single quotes, and the commas we're concerned with are outside these quotes
for index, state in enumerate(stateInfoList):
stateInfoList[index] = state.split(",")
print("{0}\n".format(stateInfoList))
# # Remove first item from stateInfoList (headers)
headers = stateInfoList.pop(0)
print("{0}\n".format(headers))
print("{0}\n".format(stateInfoList))
# # Make a states dictionary by looping through each state list contained in stateInfoList and making an entry in statesDictionary for each state with attributes for population rank, population estimate, number of House seats, and percent of total population
statesDictionary = {}
for state in stateInfoList:
statesDictionary[state[1]] = {
"popRank":state[0],
"popEst":state[2],
"houseSeats":state[3],
"percentPop":state[4]
}
print("{0}\n".format(statesDictionary))
# # Use dictionary to write states-table.html
# # Using sorted to print states alphabetically by key
with open("states-table.html", "w") as statesTableFile:
for state in sorted(statesDictionary.keys()):
statesTableFile.write("<table border='1'>\n")
statesTableFile.write("\t<tr>\n")
statesTableFile.write(("\t\t<td colspan='2'>{0}</td>\n").format(state))
statesTableFile.write("\t</tr>\n")
statesTableFile.write("\t<tr>\n")
statesTableFile.write("\t\t<td>Rank: {0}</td>\n".format(statesDictionary[state]["popRank"]))
statesTableFile.write("\t\t<td>Percent: {0}</td>\n".format(statesDictionary[state]["percentPop"]))
statesTableFile.write("\t</tr>\n")
statesTableFile.write("\t<tr>\n")
statesTableFile.write("\t\t<td>US House Members: {0}</td>\n".format(statesDictionary[state]["houseSeats"]))
statesTableFile.write("\t\t<td>Population: {0}</td>\n".format(statesDictionary[state]["popEst"]))
statesTableFile.write("\t</tr>\n")
statesTableFile.write("</table>\n<hr>\n")
# Sample output:
# <table border="1">
# <tr>
# <td colspan="2"> California </td>
# </tr>
# <tr>
# <td> Rank: 1 </td>
# <td> Percent: 11.91% </td>
# </tr>
# <tr>
# <td> US House Members: 53 </td>
# <td> Population: 38,332,521 </td>
# </tr>
# </table>
# Challenge 4 (Not a Python challenge, but an HTML/Javascript challenge): When you make a choice from the drop-down menu, jump to that state's table.
with open("states-table-select.html", "w") as statesTableFile:
statesTableFile.write("<select onchange='location = this.value;'>\n")
for state in sorted(statesDictionary.keys()):
statesTableFile.write("\t<option value='#{0}'>{1}</option>\n".format(state.replace('"', ''), state.replace('"', '')))
statesTableFile.write("</select>\n")
for state in sorted(statesDictionary.keys()):
statesTableFile.write("<section id={0}>\n".format(state))
statesTableFile.write("<h1>{0}</h1>\n".format(state.replace('"', '')))
statesTableFile.write("<table border='1'>\n")
statesTableFile.write("\t<tr>\n")
statesTableFile.write(("\t\t<td colspan='2'>{0}</td>\n").format(state).replace('"', ''))
statesTableFile.write("\t</tr>\n")
statesTableFile.write("\t<tr>\n")
statesTableFile.write("\t\t<td>Rank: {0}</td>\n".format(statesDictionary[state]["popRank"]))
statesTableFile.write("\t\t<td>Percent: {0}</td>\n".format(statesDictionary[state]["percentPop"].replace('"', '')))
statesTableFile.write("\t</tr>\n")
statesTableFile.write("\t<tr>\n")
statesTableFile.write("\t\t<td>US House Members: {0}</td>\n".format(statesDictionary[state]["houseSeats"]))
statesTableFile.write("\t\t<td>Population: {0}</td>\n".format(statesDictionary[state]["popEst"]))
statesTableFile.write("\t</tr>\n")
statesTableFile.write("</table>\n<hr>\n")
statesTableFile.write("</section>\n") |
7ddf0486fdd4b48bda93a08287b5fb6a136b0e9a | BrianWikse/IntegrationProject | /MAIN.py | 6,306 | 4.21875 | 4 | #My name is Brian Wikse
#This is a quiz game.
#This is a function that will print a name and email when it is called, this function is used in Quesion 10.
def info(name, mail):
print(name, mail)
print("Welcome to", end=' ')
print("the Quiz Game!")
#The end= in the print statement combines the two print statements and adds a space between the two statements
print("This program was finished on:")
print('10','24','2020', sep='/')
#The sep= in the print statement changes the normal space separator to a "/".
score = 0
#Sets the variable score's value to 0.
question1 = int(input("\nWhat is 2 + 1? "))
#The "+" allows the program to add 1 to 2 in order to get the answer of 3.
if question1 == (2+1):
score+=1
#Adds 1 to the variable score's value.
print("Correct!")
elif question1 != (2+1):
print("Incorrect!")
else:
print("Incorrect!")
question2 = int(input("\nWhat is 1,730 - 393? "))
#The "-" allows the program to subtract 393 from 1730 to get the answer of 1337.
if question2 == (1730-393):
score+=1
print("Correct!")
elif question2 != (1730-393):
print("Incorrect!")
else:
print("Incorrect!")
question3 = int(input("\nWhat is 54 * 17? "))
#The "*" allows the program to multiply 54 and 17 to get the answer of 918.
if question3 == (54*17):
score+=1
print("Correct!")
elif question3 != (54*17):
print("Incorrect!")
else:
print("Incorrect!")
question4 = int(input("\nWhat is 1422 / 9? "))
#The "/" allows the program to divide 9 from 1422 to get the answer of 158.
if question4 == (1422/9):
score+=1
print("Correct!")
elif question4 is not 158:
print("Incorrect!")
#The "not" operator works the same as using !=.
else:
print("Incorrect!")
question5 = int(input("\nWhat is 4 to the power of 4? "))
#The "**" allows the program to put 4 to the power of 4 to get the answer of 256.
if question5 == (4**4):
score+=1
print("Correct!")
elif question5 != (4**4):
print("Incorrect!")
question6 = int(input("\nWhat is 50 divided by 3 rounded down to the nearest whole number? "))
#The "//" allows the program to divide 50 by 3 and then rounds down the answer to the nearest whole number which would be 16.
if question6 == (50//3):
score+=1
print("Correct!")
elif question6 != (2+1):
print("Incorrect!")
else:
print("Incorrect!")
question7 = int(input("\nWhat is the remainder of 170 divided by 4? "))
#The "%" allows the program to take the remainder of 170 divided by 4.
if question7 == (170%4):
score+=1
print("Correct!")
elif question7 != (170%4):
print("Incorrect!")
else:
print("Incorrect!")
print("\nIf you wanted to count from 1 to 10 in python, which line of code would you use?")
print("A: for num in range(1, 11):")
print("B: for num in range(10):")
print("C: for num in range(1, 10, 1):")
print("D: None of the above.")
question8 = str(input("What is your answer? "))
if question8 == "A" or question8 == "a":
score+=1
print("Correct! Here is the result of the code: ")
for num in range(1, 11):
print(num)
#The for loop uses in and range as paramaters for the loop.
#The code will print from the number 1 to the number 10 because our range starts at 1 and ends at 11, because the range always needs to be 1 number higher then where you want it to stop.
elif question8 != "A" and question8 != "a":
print("Incorrect! The answer was A. Here is the result of the code in A: ")
for num in range(1, 11):
print(num)
else:
print("Incorrect! The answer was A. Here is the result of the code in A: ")
for num in range(1, 11):
print(num)
print("\nIf you wanted to count from 1 to 10 if num=1 in python, which line of code would you use?")
print("A: while (num>10):")
print("B: while (num>11)")
print("C: while (num>11):")
print("D: None of the above")
question9 = str(input("What is your answer? "))
if question9 == "C" or question9 =="c":
score+=1
print("Correct! Here is the result of the code: ")
num = 1
while (num < 11):
print(num)
num = num +1
#The "while" loop allows the program to keep printing the variale num until num reaches 11 which breaks the loop.
elif question9 != "C" and question9 != "c":
print("Incorrect! The answer was C. The result of C's code would look like this: ")
num = 1
while (num < 11):
print(num)
num = num + 1
else:
print("Incorrect! The answer was C. The result of C's code would look like this: ")
num = 1
while (num < 11):
print(num)
num = num + 1
print("\nWhich function would you use if you wanted to display your name and e-mail?" )
print("A: info(name, mail):")
print("B: def info(name, mail):")
print("C: def info(name):")
print("D: None of the above")
question10 = str(input("What is your answer? "))
if question10 == "B" or question10 == "b":
score+=1
print("Correct! Here is the result of the code: ")
info("Brian", "bjwikse9764@eagle.fgcu.edu")
else:
print("Incorrect! The answer was B. Look at the result of B's code: ")
info("Brian", "bjwikse9764@eagle.fgcu.edu")
if score == 10:
score = str(score)
print("\nYour score is: " + score + "\nExcellent! You got them all correct!")
#The "+" in the print command combines the seperate strings in order to form one complete string.
elif score <= 9 and score > 7:
score = str(score)
print("\nYour score is: " + score + "\nGreat job!")
elif score <= 7 and score > 5:
score = str(score)
print("\nYour score is: " + score + "\nPretty good job!")
elif score == 5:
score = str(score)
print("\nYour score is: " + score + "\nOnly half right?")
elif score < 5 and score >= 3:
score = str(score)
print("\nYour score is: " + score + "\nYou could have done better.")
else:
score = str(score)
print("\nYour score is: " + score + "\nSeriously?! Did you even try?")
score = int(score)
goodbye = ("Goodbye " * score)
#The "*" in the goodbye variable will make it so the word "Goodbye" will be printed the amount of times as the number of points the player scored when the goodbye variable is printed.
print(goodbye)
|
e60c90b1051b346aa91e51ea974edf56467326c5 | ngsc-py/2020-python-code | /ch6/06-4monthdictonary.py | 275 | 3.90625 | 4 | month={1:'January',2:'Feburary',3:'March',4:'April'}
month[5]='May'
month[6]='June'
month[7]='July'
month[8]='August'
month[9]='September'
print(month)
print()
from random import randint
for i in range(5):
r = randint(1,9)
print('%d: %s' %(r,month[r]))
|
0af610fa59951240f5ee794ef723aa7cd7b85c8f | herozhao/Python-Learning | /Previous/Lab11/exa/school.py | 2,509 | 3.609375 | 4 |
def getStudentInfo():
d = {}
with open("university.txt",'r') as f:
next(f)
coursenames = f.readline()
courseList = coursenames.split()
courseList = courseList[2:]
next(f)
for line in f:
lineList = line.split('|')
personalist = lineList[1:]
name = lineList[0]
name = name.strip()
if (name not in d):
l = []
d[name]=l
for i in range(len(courseList)):
grade = personalist[i]
grade = grade.strip()
if grade != '-':
testtuple = (courseList[i], float(grade))
value2 = d[name]
value2.append(testtuple)
d[name] = value2
return d
def getClassInfo():
x = {}
d =getStudentInfo()
for k, value in d.items():
for cla in value:
course,grade = cla
if course not in x:
l = []
x[course] = l
testtuple = (k,grade)
value2 = x[course]
value2.append(testtuple)
x[course]=value2
for k, value in x.items():
value3 = x[k]
value3 = sorted(value3)
x[k] = value3
return x
def getBestInCourse(course):
y = getClassInfo()
courseinfo = y[course]
max1 = 0
maxName = ''
for value in courseinfo:
name,grade = value
if grade> max1:
max1 = grade
maxName = name
return (maxName,max1)
def getCourseAverage(course):
y = getClassInfo()
courseinfo = y[course]
sum = 0.0
count = 0.0
for value in courseinfo:
name,grade = value
sum += grade
count +=1.0
average = float(sum/count)
average = round(average,2)
return average
def getStudentGPA(name):
y = getStudentInfo()
studentinfo = y[name]
sum = 0.0
num = 0
l = []
with open('course.txt','r')as f:
next(f)
next(f)
for line in f:
course,hour = line.split()
course = course.strip()
hour = hour.strip()
l[course] = int(hour)
for cla in studentinfo:
courseName, grade = cla
getHour = l[courseName]
num += getHour
temp1 = grade*getHour
sum+=temp1
gpa = float(sum/num)
gpa = round(getHour,2)
return gpa
def getCourseAverage(course):
y = getClassInfo()
|
704b1eeaa9dee3b2d1477cce0c0f3d464883a989 | dpk3d/HackerRank | /CheckValidShuffleString.py | 2,667 | 4.4375 | 4 | """
https://www.programiz.com/java-programming/examples/check-valid-shuffle-of-strings
Given strings A, B, and C, find whether C is formed by an interleaving of A and B.
An interleaving of two strings S and T is a configuration such that it creates a new string Y from the concatenation substrings of A and B and |Y| = |A + B| = |C|
For example:
A = "XYZ"
B = "ABC"
We can make multiple interleaving string Y like, XYZABC, XAYBCZ, AXBYZC, XYAZBC and many more
so here your task is to check whether you can create a string Y which can be equal to C.
Specifically, you just need to create substrings of string A and create substrings B and
concatenate them and check whether it is equal to C or not.
Note: a + b is the concatenation of strings a and b.
Return true if C is formed by an interleaving of A and B, else return false.
Example 1:
Input:
A = YX, B = X, C = XXY
Output: 0
Explanation: XXY is not interleaving
of YX and X
Example 2:
Input:
A = XY, B = X, C = XXY
Output: 1
Explanation: XXY is interleaving of
XY and X.
"""
# concat and sort mechanism
# it's a simple solution does not work for all test cases..
def validShuffle(inputString1, inputString2, shuffleString):
concat_sort_str = sorted(inputString1 + inputString2)
print(concat_sort_str) # ['X', 'X', 'Y']
sort_shuffle = sorted(shuffleString)
print(sort_shuffle) # ['X', 'X', 'Y']
if sort_shuffle == concat_sort_str:
print(" It's a Valid shuffle string : " + shuffleString)
return True
else:
print(" Not valid shuffle string : " + shuffleString)
return False
str1 = "XY"
str2 = "X"
checkStr = "XXY"
validShuffle(str1, str2, checkStr)
# It's a Valid shuffle string : XXY
def checkValidShuffle(i, j, k, a, b, c, dpArray):
if i == len(a) and j == len(b) and k == len(c): return 1
if dpArray[i][j] != -1: return dpArray[i][j]
out1, out2 = 0, 0
if i < len(a) and a[i] == c[k]:
out1 = checkValidShuffle(i + 1, j, k + 1, a, b, c, dpArray)
if j < len(b) and b[j] == c[k]:
out2 = checkValidShuffle(i, j + 1, k + 1, a, b, c, dpArray)
dpArray[i][j] = out1 + out2
print(dpArray[i][j]) # print 0 or 1, or 2
return dpArray[i][j]
# Dynamic Programming
def isInterleave(A, B, C):
j = 0
i = 0
k = 0
dpArray = [[-1 for i in range(len(B) + 1)] for j in range(len(A) + 1)]
print(dpArray) # [[-1, -1], [-1, -1], [-1, -1]]
if len(A) + len(B) != len(C): return 0
print(checkValidShuffle(i, j, k, A, B, C, dpArray)) # print 0 or 1
return checkValidShuffle(i, j, k, A, B, C, dpArray)
str1 = "YX"
str2 = "X"
checkStr = "XXY"
isInterleave(str1, str2, checkStr)
|
4ae0f22b870226e9108106390109c098666a97ff | junyechen/Basic-level | /1042 字符统计.py | 1,108 | 3.875 | 4 | '''
请编写程序,找出一段给定文字中出现最频繁的那个英文字母。
输入格式:
输入在一行中给出一个长度不超过 1000 的字符串。字符串由 ASCII 码表中任意可见字符及空格组成,至少包含 1 个英文字母,以回车结束(回车不算在内)。
输出格式:
在一行中输出出现频率最高的那个英文字母及其出现次数,其间以空格分隔。如果有并列,则输出按字母序最小的那个字母。统计时不区分大小写,输出小写字母。
输入样例:
This is a simple TEST. There ARE numbers and other symbols 1&2&3...........
输出样例:
e 7
'''
##############################################################
'''
题目非常简单,一次通过
'''
##############################################################
stat = [0] * 26
max = 0
for i in input().lower():
index_ = ord(i) - ord('a')
if 0 <= index_ <= 25:
stat[index_] += 1
if max < stat[index_]:
max = stat[index_]
max_index = stat.index(max)
print(chr(max_index + ord('a')),stat[max_index])
|
9b73dbe3f7fefe96457b07166fdcf40b037fadd2 | lilda/likelion_python | /python.py | 1,129 | 3.828125 | 4 | blogs = ["1", "2", "3"]
for blog in blogs:
print(blog)
for i in range(1):
# 0 ~ 9
print("1") #반복할때 숫자(반복된 횟수)와 함께 1 출력
for _ in range(1):
print("HEllo Django") #10번 반복할때 숫자는 보이지 않게
aaa = { "사과" : 1, "배": 2, "포도":3 , "바나나": 234} #dict="key":value
for k, v in aaa.items():
print(k + " " + str(v))
def func(a, b):
#def d():
#print("1234") #함수안에 함수를 사용할수있지만 하지말자. 함수안에서만 사용할수있음
return a + b # 숫자뿐만아니라 문자도 할수있다 abc+def = abcdef
print(func(10, 20))
def func2(f):
print(f(10, 10))
return
func2(func)
def plus(i, j):
return i + j
def minus(i, j):
return i - j
def triple_plus(i, j, l):
return i + j + l
# args -> 파라미터가 몇개 필요한지 모르니, 첫 번째 이후 인자들을 모두 args라고 부르겠다. args는 리스트
def 출력(calc, *args):
print(calc(*args))
출력(plus, 1, 2)
출력(minus, 1, 2)
출력(triple_plus, 1, 2, 3)
|
48e5ef0991ee277442e93ce0fad29f7ca56d1436 | ritchereluao/turtle_crossing_game | /road.py | 601 | 3.703125 | 4 | from turtle import Turtle
class Road(Turtle):
def __init__(self):
super().__init__()
self.pensize(width=15)
self.color("white")
# self.penup()
# self.hideturtle()
def draw_middle_line(self):
self.goto(-320, 0)
self.forward(620)
# turtle = Turtle()
# turtle.pensize(width=5)
# turtle.penup()
# turtle.hideturtle()
# turtle.goto(-320, 0)
# for _ in range(15):
# turtle.forward(20)
# turtle.penup()
# turtle.forward(20)
# turtle.pendown()
|
fdf3346f2792520bb9d6238bc75f1ba9f335e6b6 | Shubham1744/Python_Basics_To_Advance | /CheckDivisible/Prog4.py | 312 | 4.34375 | 4 | # Accept one number and check whether is is divisible by 5 or not.
def CheckDivisible(No1):
if No1 % 5 == 0:
return True
else:
return False
No1 = int(input("Enter Number :"))
bret = CheckDivisible(No1)
if bret == True:
print("divisible by 5")
else :
print("Not divisible by 5")
|
5cff4ec6f0f61e0514e421024235c5247d571b5e | houstonwalley/Kattis | /Python/IsItHalloween.py | 135 | 3.84375 | 4 | n = list(input().split())
if n[0] == "OCT" and n[1] == "31" or n[0] == "DEC" and n[1] == "25":
print("yup")
else:
print("nope") |
0d823cc7cc1af945423750bb571eb461254d94a2 | theeric80/LeetCode | /medium/reverse_words_in_a_string.py | 365 | 3.6875 | 4 |
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
return ' '.join(s.split()[::-1])
def main():
inputs = ['the sky is blue', '', 'a']
for s in inputs:
result = Solution().reverseWords(s)
print '{0} = {1}'.format(s, result)
if __name__ == '__main__':
main()
|
812aede80a2eab19f4499466141a4d8218f274dc | juliyat/Python | /Python book/Chapter 3.py | 532 | 3.984375 | 4 | cost = 35.27
tip = cost / 15
total = cost + tip
per = total // 3
print " about $", per
print ""
print ""
area = 12.5 * 16.7
perimeter = (12.5 + 16.7) * 2
print "The area is", area
print "The perimeter is", perimeter
print ""
print ""
f = int(raw_input("Enter the temperature in fahrenheit-"))
c = (f - 32) * 5/9
print "It's",c, "degrees Celsius now."
print ""
print ""
length = int(raw_input("Enter how far you want to drive-"))
speed = int(raw_input("What's your speed?"))
time = length / speed
print "it will take", time, "hours." |
b2814f414ef311ad7cb32dae88b82ec8b42bfd74 | IshchenkoMaksim/lab5 | /ind2.py | 575 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
if __name__ == '__main__':
s = input("Введите слово: ")
m = int(input("Введите номер первой буквы для замены: "))
n = int(input("Введите номер второй буквы для замены: "))
m -= 1
n -= 1
if m > len(s) or n > len(s):
print('Неверное число', file=sys.stderr)
exit(1)
else:
t = s[:m] + s[n] + s[m+1:n] + s[m] + s[n+1:]
print(f"Слово после замены: {t}")
|
89646218ebd98627eb8587bd437a36c80bbc6396 | IsaGher/ANS-unidad1 | /ejercicioUno.py | 518 | 3.71875 | 4 | import math
x = float(input("Ingrese valor de x: "))
cifras = float(input("Ingrese cuantas cifras significativas: "))
es = 0.5*(10**(2-cifras))
ea = es+1
n = 1
ant = 1
while ea>es:
f = 1
for i in range(1,(n+1)):
signo = (-1)**(i+1)
f += signo*round((x**i)/(i*math.exp(i)),6)
ea = round(abs((f-ant)/f)*100,6)
print('{:^10}{:^10}{:^10}'.format('Iteracion','x','error'))
print('{:^10}{:^10}{:^10}'.format(n,f,ea))
n +=1
ant = f
print("Respuesta: x=",f," con error de: ",ea) |
d12c463b935b82891b536b10f969dbe074ea2891 | MrHamdulay/csc3-capstone | /examples/data/Assignment_9/mkhnel011/question1.py | 1,441 | 3.9375 | 4 | """ a program that determines which students, according to the marks need to see a student an advisor
nelisile mkhwebane
13/05/2014"""
import math
""" get the text file from the user"""
filename= input("Enter the marks filename:\n")
"""open the file and get it's content"""
f = open(filename, "r")
lines = f.readlines()
f.close()
"""get the sum of the marks for the average"""
sum_marks= 0
for i in range (len(lines)):
for j in range(len(lines[i])):
if lines[i][j]==",":
sum_marks = sum_marks+ int(lines[i][j+1:])
average = sum_marks/ len(lines)
"""calculating the standard deviation"""
sum_s = 0
for i in range (len(lines)):
for j in range (len(lines[i])):
if lines[i][j] ==",":
sum_s = sum_s + (int(lines[i][j+1:])-average)**2
"""therefore, the standard deviation"""
stand_dev = math.sqrt(sum_s/len(lines))
"""printing out the resuts"""
print("The average is:", "%.2f" % (average))
if stand_dev==0:
print("The std deviation is:", "0.00")
else:
print("The std deviation is:", "%.2f" % (stand_dev))
if stand_dev>0:
print("List of students who need to see an advisor:")
"""to get the list of students"""
for i in range (len(lines)):
for j in range (len(lines[i])):
if lines[i][j]==",":
if int(lines[i][j+1:]) < average - stand_dev:
print(lines[i][:j])
|
9463a140bd35139b8cbda6dd8075a3dc7a0a42bc | Beornwulf/AoC2016 | /day1/puzzle2/puzzle2.py | 2,106 | 3.78125 | 4 | def turn_right(direction):
return {
'north': 'east',
'east': 'south',
'south': 'west',
'west': 'north'
}.get(direction)
def turn_left(direction):
return {
'north': 'west',
'west': 'south',
'south': 'east',
'east': 'north'
}.get(direction)
def travel(direction, distance):
global x, y, logs, duplicate_logs
for i in range(distance):
if direction is 'north':
y += 1
elif direction is 'east':
x += 1
elif direction is 'south':
y -= 1
elif direction is 'west':
x -= 1
location = (x,y)
if location in logs:
duplicate_logs.append(location)
else:
logs.append(location)
input = "R3, L5, R2, L2, R1, L3, R1, R3, L4, R3, L1, L1, R1, L3, R2, L3, L2, R1, R1, L1, R4, L1, L4, R3, L2, L2, R1, L1, R5, R4, R2, L5, L2, R5, R5, L2, R3, R1, R1, L3, R1, L4, L4, L190, L5, L2, R4, L5, R4, R5, L4, R1, R2, L5, R50, L2, R1, R73, R1, L2, R191, R2, L4, R1, L5, L5, R5, L3, L5, L4, R4, R5, L4, R4, R4, R5, L2, L5, R3, L4, L4, L5, R2, R2, R2, R4, L3, R4, R5, L3, R5, L2, R3, L1, R2, R2, L3, L1, R5, L3, L5, R2, R4, R1, L1, L5, R3, R2, L3, L4, L5, L1, R3, L5, L2, R2, L3, L4, L1, R1, R4, R2, R2, R4, R2, R2, L3, L3, L4, R4, L4, L4, R1, L4, L4, R1, L2, R5, R2, R3, R3, L2, L5, R3, L3, R5, L2, R3, R2, L4, L3, L1, R2, L2, L3, L5, R3, L1, L3, L4, L3"
input = input.split(", ")
logs = []
duplicate_logs = []
direction = 'north'
x = 0
y = 0
for i in input:
turn = i[0]
distance = int(i[1:])
if turn is "R":
direction = turn_right(direction)
elif turn is "L":
direction = turn_left(direction)
travel(direction, distance)
print("Total distance: %d" % (abs(x)+abs(y)))
first_duplicate = duplicate_logs[0]
first_duplicate_distance = (abs(first_duplicate[0])+abs(first_duplicate[1]))
print("First duplicated location: %s, %d away" % (first_duplicate, first_duplicate_distance))
|
e9968c2f032ba3223dd944263fc7e6eaa3074053 | nghiattran/playground | /knapsack.py | 1,847 | 3.6875 | 4 | import time
def knapSack(val, wt, W, n):
# Base Case
if n == 0 or W == 0:
return 0
# If weight of the nth item is more than Knapsack of capacity
# W, then this item cannot be included in the optimal solution
if (wt[n - 1] > W):
return knapSack(val, wt, W, n - 1)
# return the maximum of two cases:
# (1) nth item included
# (2) not included
else:
return max(val[n-1] + knapSack(val, wt, W-wt[n-1], n-1),
knapSack(val, wt, W, n - 1))
def knapsack_bruteforce(values, weights, capacity, n = 0):
max_value = 0
for index in range(0, len(values)):
if capacity >= weights[index]:
tmp = knapsack_bruteforce(values[1:], weights[1:], capacity - weights[index])
tmp_max_value = tmp + values[index]
max_value = max(max_value, tmp_max_value)
return max_value
def knapSack1(W, wt, val, n):
K = [[0 for x in range(W + 1)] for x in range(n + 1)]
# Build table K[][] in bottom up manner
for i in range(n + 1):
for w in range(W + 1):
if i == 0 or w == 0:
K[i][w] = 0
elif wt[i - 1] <= w:
K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w])
else:
K[i][w] = K[i - 1][w]
return K[n][W]
values = [60, 100, 120]
weights = [10, 20, 30]
capacity = 0
start = time.time()
for index in range(0, 1000000):
knapsack_bruteforce(values, weights, capacity, len(values))
end = time.time()
print(end - start)
start = time.time()
for index in range(0, 1000000):
knapSack(values, weights, capacity, len(values))
end = time.time()
print(end - start)
start = time.time()
for index in range(0, 1000000):
knapSack1(val=values, wt=weights, W=capacity, n=len(values))
end = time.time()
print(end - start) |
797acdc8a5fd330ea163f8d4d993593d0c8a7910 | jiexishede/leetcode-1 | /src/longest_common_prefix.py | 1,230 | 3.59375 | 4 | class Solution:
# @param {string []} strs
# @return {string}
def longestCommonPrefix(self, strs):
if not strs:
return ""
longestIndex = 0
foundNotMatched = False
for index in range(0, len(strs[0])):
if not foundNotMatched:
longestIndex = index
char = strs[0][index]
for i,str in enumerate(strs):
if index >= len(str) or str[index] != char:
foundNotMatched = True
break
if foundNotMatched:
return strs[0][:longestIndex]
else:
return strs[0][:longestIndex+1]
if __name__ == '__main__':
test_list = [[], ['a'], ['a','b'], ['aa','aa'], ['aa', 'a']]
result_list = ['','a','','aa','a']
success = True
solution = Solution()
for i, s in enumerate(test_list):
result = solution.longestCommonPrefix(s)
if result != result_list[i]:
success = False
print s
print 'Expected value ',result_list[i]
print 'Actual value ',result
if success:
print 'All the tests passed'
else:
print 'Please fix the failed test'
|
8437a87ee111cb42e736813766cdd0e00a381b7e | dipanbhusal/Python_practice_programs | /ques6.py | 667 | 4.25 | 4 | # 6. Write a Python program to find the first appearance of the substring 'not' and
# 'poor' from a given string, if 'not' follows the 'poor', replace the whole 'not'...'poor'
# substring with 'good'. Return the resulting string.
def string_manipulation(string):
if 'poor' and 'not' in string:
poor_index = string.find('poor')
not_index = string.find('not')
if poor_index > not_index:
result = string.replace(string[not_index:poor_index+4], 'good')
else:
result = string
return result
if __name__=="__main__":
test_string = input('Enter the string: ')
res = string_manipulation(test_string)
print(res)
|
e4771e3c68b965bf4044b8cd3f02df2bc382f7f9 | Sharko-21/homework-template | /homework2/bubble_sort.py | 992 | 4.15625 | 4 | def input_arr(num):
arr = []
for i in range(0, num):
current_elem = float(input('Введите ' + str(i) + ' элемент массива: '))
arr.append(current_elem)
return arr
def bubble_sort(arr):
for i in range(0, len(arr) - 1):
for j in range(i + 1, len(arr)):
if arr[i] > arr[j]:
arr[i], arr[j] = arr[j], arr[i]
return arr
arr = input_arr(int(input('Введите размер массива: ')))
print(bubble_sort(arr))
# Сложность O(n^2)
# Малоэффектинвый алгоритм сортировки
# Применяется только в учебе
# Сравнивает соседние числа и меняет их местами, если это требуется
# И так до тех пор, пока все числа не отсортируются
# При увеличении кол-ва чисел производительность сильно падает
|
d6aec33ee3dd56d2aed4be5cfa167bc66da2002a | quocthai200x/NguyenXuanQuocThai-Fundamentals-C4E27 | /session 3/session3.py | 2,456 | 3.90625 | 4 | # # # n = int (input("tổng chữ số cần tính : "))
# # # tong = 0
# # # for i in range (n) :
# # # x = int(input('mời nhập các số : '))
# # # tong = tong + x
# # # print ('tổng các chữ số đó là : ', tong)
# # # n = int(input('mời nhập số : '))
# # # if n%2 == 1 :
# # # print ('abc')
# # # else :
# # # print ('ưhdiuashud')
# # # namsinh = int(input("mời nhập năm sinh của bạn : "))
# # # age = 2019 - namsinh
# # # if 0 < age <10 :
# # # print ('you are baby')
# # # print (age)
# # # elif age < 16 :
# # # print ('you are teen')
# # # print (age)
# # # else :
# # # print ('you are adult')
# # # print (age)
# # yob = input('nhập năm sinh : ')
# # while not yob.isdigit() :
# # print ('mày sai rồi ')
# # yob = input('nhập lại năm sinh : ')
# # age =2019 - int(yob)
# # print ( 'tuổi của bạn là : ',age)
# password = input('nhập pass : ')
# while True :
# if len(password)>8 :
# break
# print('mật khẩu ko đc nhỏ hơn 8 kí tự ')
# password = input('nhập lại pass : ')
# print('welcome to your home ')
# loopcount = 0
# while True :
# print ('loopcount : ', loopcount)
# loopcount += 1
# if loopcount >= 3 :
# break
# print('abc')
# a = input('nhập số a : ')
# while not a.isdigit () :
# a = (input ("nhập lại số a"))
# b = input ('nhập số b : ')
# while not b.isdigit () :
# b = (input ("nhập lại số b "))
# c = input ('nhập số c : ')
# while not c.isdigit () :
# c = (input ("nhập lại số c "))
# print (a,b,c)
# a= int(a)
# b= int(b)
# c= int(c)
# print (a+b+c)
# delta = (b*b) - (4*a*c)
# if delta > 0 :
# x1 = (-b +delta**0.5)/(2*a)
# x2 = (-b -delta**0.5)/(2*a)
# print ('phương trình có 2 nghiệm riêng biệt là : ',x1 , x2)
# elif delta == 0 :
# print ('phương trình có 1 nghiệm duy nhát là : ',x)
# else :
# print ('phương trình vô nghiệm ')
ls=[]
n=int(input('nhập sô phần tử trong danh sách : '))
for i in range (n):
print('nhập số phần tử thứ ',i+1)
so = int(input(''))
ls.append(so)
print('dãy bạn vừa nhập là : ')
print (ls)
print()
print('tổng dãy số bạn vừa nhập là : ')
print(sum(ls))
print()
print('phần tử thứ 2 trong dãy là : ')
print (ls[1])
|
0df8749044ab85a4cb855bb3127a5de0253d63cb | moon0331/baekjoon_solution | /programmers/고득점 Kit/네트워크.py | 679 | 3.71875 | 4 | def DFS(n, computers, start_node, visited):
stack = [start_node]
while stack:
node = stack.pop()
for next_node in range(n):
if not visited[next_node] and computers[node][next_node] == 1:
stack.append(next_node)
visited[next_node] = True
def solution(n, computers):
visited = [False for _ in range(n)]
answer = 0
for start_node in range(n):
if visited[start_node]:
continue
DFS(n, computers, start_node, visited)
answer += 1
return answer
print(solution(3, [[1, 1, 0], [1, 1, 0], [0, 0, 1]]) == 2)
print(solution(3, [[1, 1, 0], [1, 1, 1], [0, 1, 1]]) == 1) |
2b392be7b7e9c2faac60e70c6682b2be7ee96d97 | NorthcoteHS/10MCOD-Max-APPELMAN | /modules/u3_organisationAndReources/naming/saysHello.py | 250 | 3.734375 | 4 | """
Prog: saysHello.py
Name: Max Appelman
Date: 2018/03/12
Desc: Says hello to the user.
"""
#gets name of user and displays a personalised greeting
name = input('What is your name? ')
print('Hello ' + name + ', I am Computer! Nice to meet you.')
|
f34bfed9d86499bde96a0a5a7c2c0723e0d31cc7 | Tassneem04Hamdy/AUG-Problem-Solving-For-Bioinformatics-Level-1- | /Session 2/List/LoopInList.py | 493 | 3.953125 | 4 |
@auther nouran ahmed ibrahim
List = ['a', 1, "b", 2, 'c', 'd']
# display all items in list
for item in List:
print(item)
# find num of small char in list
countChar = 0
for item in List:
if str(item).isalpha(): # convert all items to String then check if it char or not
countChar += 1
print("number of chars : ", countChar)
# '''
# find element index in the list
for index in range(len(List)):
if List[index] == "b":
print("b appeares in : ", index)
break
# '''
|
7d05035329c7083cb9dafe6f7647827b40027f6b | wmemon/python_playground | /24_days/Day 24/Question102.py | 493 | 4.03125 | 4 | """Write a Python program that accepts a string and calculate the number of digits and letters."""
def get_digits(string):
digits = 0
for alpha in string:
if alpha.isdecimal():
digits+=1
return digits
def get_letters(string):
letters = 0
for alpha in string:
if alpha.isalpha():
letters+=1
return letters
string = input("Please enter a string: ")
print(f"Digits: {get_digits(string)}")
print(f"Letters: {get_letters(string)}") |
da45d464210e6287fa0b543fc380751a2f824ae9 | alhanson7210/deploying-working-software | /assignments/a1-unit-tests/test_calculator_one.py | 4,879 | 3.6875 | 4 | from unittest import TestCase
from calculator_one import Calculator
class TestCalculator(TestCase):
def setUp(self) -> None:
self.calculator = Calculator()
def test_default_init_calculation(self):
actual = self.calculator.get_last_calculation()
if type(actual) != int:
self.fail("actual was not a number data type: int, float, or complex")
expected = 0
self.assertEqual(actual, expected, "Default should be zero")
def test_invalid_init_parameter_type(self):
with self.assertRaises(ValueError, msg="Invalid Output: non integer parameter"):
self.calculator = Calculator(tuple())
def test_valid_init_parameter_type(self):
self.calculator = Calculator(10)
actual = self.calculator.get_last_calculation()
if type(actual) != int:
self.fail("actual was not a number data type: int, float, or complex")
expected = 10
self.assertEqual(actual, expected, "Init parameter 10 should match the latest calculation")
def test_default_operand_for_add_to_last_calculation(self):
self.calculator = Calculator(5)
actual = self.calculator.add_to_last_calculation()
if type(actual) != int:
self.fail("actual was not a number data type: int, float, or complex")
expected = 5
self.assertEqual(actual, expected, "Invalid Output: expected to have 0 added to the initial value")
def test_invalid_operand_for_add_to_last_calculation(self):
with self.assertRaises(ValueError, msg="Invalid Output: non integer parameter"):
self.calculator.add_to_last_calculation(list())
def test_valid_operand_for_add_to_last_calculation(self):
self.calculator = Calculator(5)
actual = self.calculator.add_to_last_calculation(3)
if type(actual) != int:
self.fail("actual was not a number data type: int, float, or complex")
expected = 8
self.assertEqual(actual, expected, "Invalid Output: expected to have 3 added to the initial value")
def test_default_operand_for_subtract_from_last_calculation(self):
self.calculator = Calculator(5)
actual = self.calculator.subtract_from_last_calculation()
if type(actual) != int:
self.fail("actual was not a number data type: int, float, or complex")
expected = 5
self.assertEqual(actual, expected, "Invalid Output: expected to have 0 subtracted to the initial value")
def test_invalid_operand_for_subtract_from_last_calculation(self):
with self.assertRaises(ValueError, msg="Invalid Output: non integer parameter"):
self.calculator.subtract_from_last_calculation(list())
def test_valid_operand_for_subtract_from_last_calculation(self):
self.calculator = Calculator(5)
actual = self.calculator.subtract_from_last_calculation(3)
if type(actual) != int:
self.fail("actual was not a number data type: int, float, or complex")
expected = 2
self.assertEqual(actual, expected, "Invalid Output: expected to have 2 subtracted to the initial value")
def test_default_operand_two_add_parameter(self):
actual = self.calculator.add(7)
if type(actual) != int:
self.fail("actual was not a number data type: int, float, or complex")
expected = 7
self.assertEqual(actual, expected, "Invalid Output: expected to have 7 added to the default value")
def test_invalid_add_parameters(self):
with self.assertRaises(ValueError, msg="Invalid Output: non integer parameters"):
self.calculator.add(dict(), set())
def test_valid_add_parameters(self):
actual = self.calculator.add(3, 2)
if type(actual) != int:
self.fail("actual was not a number data type: int, float, or complex")
expected = 5
self.assertEqual(actual, expected, "Invalid Output: expected addition calculation to have 5")
def test_default_operand_two_subtract_parameter(self):
actual = self.calculator.subtract(7)
if type(actual) != int:
self.fail("actual was not a number data type: int, float, or complex")
expected = 7
self.assertEqual(actual, expected, "Invalid Output: expected to have 7 subtracted to the default value")
def test_invalid_subtract_parameters(self):
with self.assertRaises(ValueError, msg="Invalid Output: non integer parameters"):
self.calculator.subtract(dict(), set())
def test_valid_subtract_parameters(self):
actual = self.calculator.subtract(3, 2)
if type(actual) != int:
self.fail("actual was not a number data type: int, float, or complex")
expected = 1
self.assertEqual(actual, expected, "Invalid Output: expected subtraction calculation to have 1")
|
4daea6f6078e514ad05369a1b5bbd4648ecdcbbd | whelanworkmaster/mta_info_scraper | /scripts/timer.py | 896 | 3.90625 | 4 | import time
class TimerError(Exception):
"""A custom exception used to report errors in use of Timer class"""
class Timer:
def __init__(self):
self._start_time = None
self._total_time = None
def start(self):
if self._start_time is not None:
return
self._start_time = time.perf_counter()
self._total_time = self._start_time
def stop(self):
if self._start_time is None:
raise TimerError(f"Timer is not running. Use .start() to start it")
self._total_time += time.perf_counter() - self._start_time
self._start_time = None
def get_time(self):
if not self._total_time:
return 0.0
elif not self._start_time:
return self._total_time + time.perf_counter()
else:
return self._total_time + time.perf_counter() - self._start_time
|
828ec355176643d361fa0c59558465a2f2058e2f | LukasForst/RPH | /scrabble/scrabble_player.py | 1,862 | 3.65625 | 4 | import config_scrabble
class ScrabblePlayer:
rows = 15
columns = 15
def __init__(self, dictionary_path):
self.halfIDX = int(self.rows / 2) - 1
self.is_first_move = True
self.all_dictionary_words = {}
self.hand_letters = ""
with open(dictionary_path, encoding='utf-8') as file:
for line in file.read().split('\n'):
self.all_dictionary_words[line.upper()] = self.evaluate_word(line)
def evaluate_word(self, word):
final_value = 0
letter_value = config_scrabble.letter_value
for key in letter_value.keys():
for letter in word:
if(key == letter):
final_value += letter_value[key]
return final_value
def play(self, board, hand_letters):
"""
buď textový řetězec s písmeny, která si hráč přeje místo tahu vyměnit (string)
nebo 2D list se stavem desky po tahu
:param board:
:param hand_letters:
:return:
"""
possible_words = {}
self.hand_letters = hand_letters
hand_letters = ''.join(sorted(hand_letters.upper()))
for word in self.all_dictionary_words.keys():
word_sorted = ''.join(sorted(word))
if word_sorted in hand_letters:
possible_words[word] = self.all_dictionary_words[word]
word = max(possible_words, key=possible_words.get)
idx = 0
for i in range(self.halfIDX, self.halfIDX + len(word)):
tmp = list(word)
board[7][i] = tmp[idx]
idx += 1
self.is_first_move = False
return board
if __name__ == '__main__':
sc = ScrabblePlayer('dictionary.txt')
board = config_scrabble.board
result = sc.play(board, "AHOJEPK")
for i in result:
print(i)
|
30cdc3c9590c2d777ca7b9ffcf9c3c55b68bccca | Baisal89/Sprint_DS8 | /acme_report.py | 1,330 | 3.671875 | 4 | from random import uniform, randint, choice
from acme import Product
DJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved']
NOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???']
def generate_products(n: int = 30) -> list:
"""Creating list of new ACME products!"""
products = []
for i in range(n):
name = choice(DJECTIVES) + ' ' + choice(NOUNS)
price = randint(5, 100)
weight = randint(5, 100)
flammability = uniform(0, 2.5)
products.append(Product(name=name, price=price, weight=weight,
flammability=flammability))
return products
def inventory_report(products: list) -> None:
"""ACME inventory report"""
names = len(set([prod.name for prod in products]))
list_len = len(products)
ave_weight = sum([prod.weight for prod in products])/list_len
ave_price = sum([prod.price for prod in products])/list_len
ave_flame = sum([prod.flammability for prod in products])/list_len
print('\n OFFICIAL ACME INVENTORY REPORT:\n')
print(f'Number of unique product names: {names}')
print(f'Mean product weight: {ave_weight:.2f}')
print(f'Mean product price: {ave_price:.2f}')
print(f'Mean product flammability: {ave_flame:.2f}')
if __name__ =="__main__":
inventory_report(generate_products())
|
1637fc1e41461375967b440657671116274d28a4 | Batyrsultan/WebDevelopment | /week9/informatics/3/2/30599.py | 72 | 3.953125 | 4 | def power_of_two(n):
sqr=1
while(sqr<=n):
print(sqr,end=" ")
sqr=sqr*2 |
b8f33577646fdf501231475142333986479e110a | zaigr/math-pack | /lab_01/task3/main.py | 422 | 4 | 4 |
import common.input
def get_factorial_loop(number: int):
if not 0 <= number <= 100:
raise ValueError
factorial = 1
for i in range(2, number + 1):
factorial *= i
return factorial
def main():
number = common.input.input_number(int, 'Input int from 0 to 100: ')
factorial = get_factorial_loop(number)
print('Factorial: ', factorial)
if __name__ == '__main__':
main()
|
7fa0e4e5bc1f6b516fa564ac947444990dfb0e45 | sgalicia/lesson9 | /Lesson 9/problem3.py | 289 | 3.90625 | 4 | print('-'*60)
print('Alien Greeter Bot: ')
print()
planet = input('What planet are you from? ')
if planet == 'Mars':
print('Welcome to Earth, please do not kill us!')
else:
print('Dammmmnnnnn, your face is so ugly I thought you were an alien. Anyways ... have a good day!')
print('-'*60) |
4deba05c3ed97980a76e9ca50be3b119aaeb7254 | vaishnavivm/FINDING-KAREL-GAME | /codeinplace-master/game.py | 7,013 | 3.734375 | 4 | import tkinter as tk
import time
from PIL import ImageTk, Image
"""FINDING KAREL GAME
The player needs to find Karel with the clues provided by Karel.
The player needs to click on the object that matches the clue.
The player has three chances to click on the right object for the whole game.
If the player clicks wrong objects three times, the game exits and the player has to start over.
"""
#creating a canvas from tkinter; taken for Chris' checkerboard game
def make_canvas(width, height, title=None):
"""
DO NOT MODIFY
Creates and returns a drawing canvas
of the given int size with a blue border,
ready for drawing.
"""
objects = {}
top = tk.Tk()
top.minsize(width=width, height=height)
if title:
top.title(title)
canvas = tk.Canvas(top, width=width + 1, height=height + 1)
canvas.pack()
canvas.xview_scroll(8, 'units') # add this so (0, 0) works correctly
canvas.yview_scroll(8, 'units') # otherwise it's clipped off
return canvas
CANVAS_WIDTH = 800
CANVAS_HEIGHT = 600
#defines correct object's clue coordinates: first four for the first image, second four for image 2 and so on.
#(x1,y1) - Left top and (x2,y2) - Right bottom for each of the clue
CLUE_COORDS = [0,0,800,600,86,140,145,216,153,338,197,377,2,262,801,375,19,255,135,462,0,0,800,600]
#GAMESTATE is dictionary to save current state of the player.
#numlife is the lives or tries a player has
#currentClue is the clue for each image which increments when player chooses the right object
#errorPage is displayed on choosing the wrong object
GAMESTATE = {'numLife' : 3, 'currentClue' : 0, 'errorPage': False}
#Create canvas
canvas = make_canvas(CANVAS_WIDTH, CANVAS_HEIGHT, 'FINDING KAREL')
def main():
# Create image, resize it to canvas dimension and put on canvas
create_image(canvas, "images/home.jpg")
canvas.update()
# adding a mouse click callback; this will get invoked for any click on canvas
canvas.bind("<Button-1>", mouse_click)
canvas.pack()
canvas.mainloop()
"""function mouse_click checks the coordinates of the clues and
moves the next page or the error page based on the player's mouse click"""
def mouse_click(event):
if GAMESTATE['errorPage'] == True : #sets the GAMESTATE[errorPage] back to True and displays the current clue page
if GAMESTATE['numLife'] <=0 : #if numlife (lives left is less than or equal to 0, exit the game)
exit()
else:
GAMESTATE['errorPage'] = False
set_image() #Set the current clue back on the canvas
else:
if GAMESTATE['currentClue'] == 0 : #if currentClue=0, displays the first image and the coordinates from the first four elements in the list
x1 = CLUE_COORDS[0]
y1 = CLUE_COORDS[1]
x2 = CLUE_COORDS[2]
y2 = CLUE_COORDS[3]
if GAMESTATE['currentClue'] == 1 : #if currentClue=1, displays the first image and the coordinates from the 2nd set of four elements in the list
x1 = CLUE_COORDS[4]
y1 = CLUE_COORDS[5]
x2 = CLUE_COORDS[6]
y2 = CLUE_COORDS[7]
elif GAMESTATE['currentClue'] == 2 : #if currentClue=2, displays the first image and the coordinates from the 3rd set of four elements in the list
x1 = CLUE_COORDS[8]
y1 = CLUE_COORDS[9]
x2 = CLUE_COORDS[10]
y2 = CLUE_COORDS[11]
elif GAMESTATE['currentClue'] == 3 : #if currentClue=3, displays the first image and the coordinates from the 4th set of four elements in the list
x1 = CLUE_COORDS[12]
y1 = CLUE_COORDS[13]
x2 = CLUE_COORDS[14]
y2 = CLUE_COORDS[15]
elif GAMESTATE['currentClue'] == 4 :#if currentClue=4, displays the first image and the coordinates from the 5th set of four elements in the list
x1 = CLUE_COORDS[16]
y1 = CLUE_COORDS[17]
x2 = CLUE_COORDS[18]
y2 = CLUE_COORDS[19]
elif GAMESTATE['currentClue'] == 5 : #if currentClue=5, displays the first image and the coordinates from the last four elements in the list
x1 = CLUE_COORDS[20]
y1 = CLUE_COORDS[21]
x2 = CLUE_COORDS[22]
y2 = CLUE_COORDS[23]
#checks if the selected object falls within the (x1,y1) and (x2,y2) coordinates
if ((event.x > x1 and event.y > y1) and (event.x < x2 and event.y < y2)):
print("Yay! You got it!")
GAMESTATE['currentClue'] += 1 #if currect object selected, increments the currentClue to 1
canvas.delete("all")
if GAMESTATE['currentClue'] != 6 and GAMESTATE['currentClue'] != 1:
create_image(canvas, "images/awesome.jpg") #creates the image if the clues are correct and when the clues are not the first(Intro Screen) and last (ie. 1 and 6)
canvas.update()
time.sleep(0.5) #sustains the image for 0.5s)
set_image()
else:
GAMESTATE['numLife'] -= 1 # Reduce the remaining lives
GAMESTATE['errorPage'] = True # Set the error Page flag and display the number of remaining tries
if GAMESTATE['numLife'] <= 0:
create_image(canvas, "images/Sorry.jpg") #displays this image if the player finishes three wrong tries
canvas.update()
elif GAMESTATE['numLife'] == 2:
create_image(canvas, "images/oops.jpg") # If the user has 2 more tries left
canvas.update()
elif GAMESTATE['numLife'] == 1:
create_image(canvas, "images/oops1.jpg") #1 more try left
canvas.update()
print("Try again! you have remaining lives - ", GAMESTATE['numLife'])
# displays on terminal the coordinates of mouse click (for reference)
print("clicked at", event.x, event.y)
"""Sets an image to nextClueImagePath based on the increment of current clue"""
def set_image():
if GAMESTATE['currentClue'] == 0:
nextClueImagePath = 'images/home.png'
if GAMESTATE['currentClue'] == 1:
nextClueImagePath = 'images/STUDY.png'
if GAMESTATE['currentClue'] == 2:
nextClueImagePath = 'images/BEDROOM.png'
elif GAMESTATE['currentClue'] == 3:
nextClueImagePath = 'images/Garden.png'
elif GAMESTATE['currentClue'] == 4:
nextClueImagePath = 'images/Kitchen.png'
elif GAMESTATE['currentClue'] == 5:
nextClueImagePath = 'images/bakerkarel0.jpg'
elif GAMESTATE['currentClue'] == 6:
exit()
create_image(canvas, nextClueImagePath)
def create_image(canvas, imagePath):
# Loads the image, resizes it to the canvas dimensions
img = Image.open(imagePath)
img = img.resize((CANVAS_WIDTH, CANVAS_HEIGHT), Image.ANTIALIAS)
photoImg = ImageTk.PhotoImage(img)
canvas.image = photoImg
canvas.create_image(0,0,anchor =tk.NW, image = photoImg )
if __name__ == '__main__':
main()
|
507f32d83c0c15b37a44f7f37700b8fab19673f3 | Elcoss/Python-Curso-em-Video | /Mundo1/desafio3.py | 134 | 3.703125 | 4 | n1=int(input('digite um valor: '))
n2=int(input('digite outro valor: '))
n3= n1+n2
print(f'a soma entre {n1} e {n2} vale {n3}')
|
29a0dfb14231e4bc5c8e2ebab295cc0f1880094d | valleyceo/code_journal | /1. Problems/b. Strings & Hash/0. Template/c. Best Substring - Find All Subset Combination in String.py | 1,029 | 3.9375 | 4 | # Compute All String Decompositions
'''
- Given a input string and array of strings
- Return the starting indices of substrings of the sentence
'''
# O(N*n*m) time, N is length of sentence, m is number of words, n is length of each word
def find_all_substrings(s: str, words: List[str]) -> List[int]:
def match_all_words_in_dict(start):
curr_string_to_freq = collections.Counter()
for i in range(start, start + len(words) * unit_size, unit_size):
curr_word = s[i:i + unit_size]
it = word_to_freq[curr_word]
if it == 0:
return False
curr_string_to_freq[curr_word] += 1
if curr_string_to_freq[curr_word] > it:
# curr_word occurs too many times for a match to be possible.
return False
return True
word_to_freq = collections.Counter(words)
unit_size = len(words[0])
return [
i for i in range(len(s) - unit_size * len(words) + 1)
if match_all_words_in_dict(i)
]
|
a22434d114b2402d95a372c3e95145b2d59b1488 | geon1002/bach | /python/phan tich.py | 168 | 3.8125 | 4 | a = input("so: ")
so = int(a)
sochia = 2
while so >sochia:
if so % sochia==0:
print(sochia)
so /= sochia
else:
sochia +=1
print(so)
|
83a3c8f42faa31328cde36a49f15b776526b3689 | DaniloBP/Python-3-Bootcamp | /nested_lists.py | 779 | 3.90625 | 4 |
matrix1 = [ [1,2,3,4], [5,6,7,8], [9,10,11,12] ]
# print(matrix1, end="\n\n")
# print(matrix1[0][1], end="\n\n") # 2
# print(matrix1[1][-1], end="\n\n") # 8
# print(matrix1[2][-4], end="\n\n") # 9
# print(matrix1[-2][-3], end="\n\n") # 6
# for l in matrix1:
# print(" ", end="")
# for val in l:
# print(val, end="\t")
# print()
# [ [ print(val) for val in l] for l in matrix1] # Using List Comprehension.
# board = [ [ num for num in range(1,4)] for val in range(1,4) ]
# print(board)
# board = [ ['X' if num % 2 != 0 else 'O' for num in range(1,4)] for val in range(1,4) ]
# print(board)
# board = [ ['*' for num in range(1,4)] for val in range(1,4) ]
# print(board)
# EXERCISES
answer = [ [ i for i in range(0,5)] for val in range(0,5) ]
print(answer) |
aef28419d542d53dff30a0e5089ce479c4bff05a | vdpham326/Python_Coding_Exercises | /first_half.py | 303 | 4.125 | 4 | # Given a string of even length, return the first half. So the string "WooHoo" yields "Woo".
def first_half(str):
half = int(len(str) / 2)
return str[:half]
#return half
print(first_half('Woohoo'))
print(first_half('HelloThere'))
print(first_half('abcdefg'))
#print(first_half('Woohoo'))
|
d650c4afa97c57556cd0bb8644e347ba7bc52480 | fabiourias/520 | /funcoes.py | 1,821 | 3.640625 | 4 | #!/usr/bin/python3
#encoding: utf-8
from
def boas_vindas(nome='Daniel', idade=24):
nome = input('Digite o seu nome:')
idade = int(input('Digite sua idade:'))
dic = {'nome': nome, 'idade': idade}
return dic
def boas_vindas02(*args):
for x in args:
print('Seja bem vindo: {}!'.format(x))
def boas_vindas03(**kwargs):
''' funcao de boas vindas! '''
for x,y in kwargs.items(): #.values .keys .items
print (x,y, sep=':')
def calculo_total(**produto):
''' funcao calculo soma o total de cada item! '''
a = produto['qtde']
b = produto['valor']
c = produto['nome']
result = 'Produto: {}, Total: {}'.format(c, a * b)
return result
def boas_vindas04():
print ('Seja bem vindo!')
def ola(nome):
print('Ola {}!'.format(nome))
boas_vindas04()
#ola('Daniel')
#for nome in nomes:
# boas_vindas(nome)
def gravar_log(log):
with open('python.log', 'a') as arq:
arq.write(log)
def soma(x ,y):
return (x + y)
def open_file(nome):
try:
with open(nome, 'r') as arquivo:
return arquivo.readlines()
except Exception as e:
return 'Falha ao ler o arquivo informado: {}'.format(e)
def format_file(nome, modo, conteudo=None):
if modo.lower() == 'r':
try:
with open(nome, modo) as arquivo:
return arquivo.readlines()
except Exception as e:
result = 'Falha ao ler o arquivo informado: {} [error] - [{}]'.format(e)
gravar_log(result)
return result
elif modo == 'a':
try:
with open(nome, modo) as arquivo:
arquivo.write(conteudo + '\n')
return True
except Exception as e:
return 'Falha ao escrever no arquivo: {} !'.format(e)
|
f1f32d571b20f00ea0e5f1b3ed7095d1375b13c2 | EliRuan/ifpi-ads-algoritmos2020 | /Exercícios Iteração WHILE/f3_q01.py | 172 | 3.984375 | 4 | n = int(input('Digite um número: '))
c = 1
print(f'Os números inteiros entre 1 e {n} são:')
while c <= n:
print(c, end=' ')
c += 1
print('Fim')
|
20761809b8478b6015e51d381edfdb49a65f8f46 | ljZhang416/studypython | /lpthw/day02_3.py | 265 | 3.609375 | 4 | # 1.输入一个季度(1-4表示),输出这个季度有哪几个月
# 如果输入的不是1-4的整数,则提示用户输入错了
while True:
a = int(input("请输入:"))
if a == 1:
print("123")
elif a==2:
print("456")
else:
print("输入错误") |
55fbbe46f95f9084d90913e616f2da348ef297d7 | agentmilindu/IEEExtremes | /IEEExtreme8/Grand-Integer-Lottery/AnonymouZ.py | 557 | 3.59375 | 4 | def remove_repetitions(seq):
seen = set()
seen_add = seen.add
return [ x for x in seq if not (x in seen or seen_add(x))]
params = input().split()
S = int(params[0])
E = int(params[1])
P = int(params[2])
N = int(params[3])
selects = []
for i in range(N):
t = input().strip()
selects.append(t)
LS = []
for i in range(S,E+1):
for n in selects:
number = str(i)
if n in number:
LS.append(i)
LS.sort()
LS = remove_repetitions(LS)
try:
print(LS[P-1])
except:
print("DOES NOT EXIST")
|
2b8bccea06f840b8701e282b5581b4941b56554e | nkkodwani/arul-naveen-c2fo-2021 | /PracticeProjects/ArulFiles/dp_allocate_mailboxes_partitions.py | 3,375 | 3.5 | 4 | '''
LEETCODE PROBLEM 1478:
Given the array houses and an integer k. where houses[i] is the location of the ith house along a street, your task is to allocate k mailboxes in the street.
Return the minimum total distance between each house and its nearest mailbox.
https://leetcode.com/problems/allocate-mailboxes/
INPUT:
hosues = list of house position in increasing order
int n_mailbox = number of mailboxes (k in Leetcode problem)
OUTPUT:
minimum total distance between houses and mailbox
ex: 3 houses at [1, 5, 20] and 2 mailboxes:
ouput = 4
mailboxes placed at 3 and 20; minimum output = 4 = (3-1) + (5-3) + (20-20)
PSEUDOCODE:
Base Cases:
k = 1 : put mailbox in median (given by leetcode hint)
k = # of houses : put one mailbox at each house (total distance is 0)
partition:
break houses into k groups --> this makes it so each group has one mailbox (base case)
from leetcode discussion: form one group, then form k-1 groups with remaining elements (recursion)
'''
import numpy as np
import statistics as st
#INPUT:
num_houses = int(input("Input the number of houses: "))
houses_pos = []
for i in range (num_houses):
house = int(input("Input house position: "))
houses_pos.append(house)
k = int(input("Input the number of mailboxes: "))
#CREATE MEMO TABLE:
a1 = np.zeros(shape=(houses_pos[-1], houses_pos[-1]))
a1.fill(-1)
#right now this is not being used
#start index will be first house pos
#end index will be last house pos
#k will be mailboxes in the group
def allocate_mailboxes(start: int, end : int, k : int):
#Base case: if there is one mailbox, place it at the median house (hint from LC)
if k == 1:
mid_index = int(st.median([start, end]))
total_dist = 0
for i in range(start, end + 1):
total_dist += (abs(houses_pos[i] - houses_pos[mid_index])) #adds total distance from each house to mailbox
return total_dist
#Another base case: if there is a mailbox for every house in the group, then total distance will be 0
if k == (end - start) + 1:
return 0
total_dist = 10000000
#need to break houses into k subgroups. Each subgroup gets one mailbox
for i in range (start, end): #tries every possible partition of the houses
inst_dist = allocate_mailboxes(start, i, 1) + allocate_mailboxes(i+1, end, k-1)
#replace total distance if instant distance is
if inst_dist < total_dist:
total_dist = inst_dist
'''
each time the loop runs, the program partitions the houses list. the idea is to make two groups: the first group is given one mailbox (first 'allocate_mailboxes') and the second group is given
the rest of the mailboxes. Recursion is used to continue partitioning the second group over and over until the mailboxes for that group = 1 (therefore recurses k-1 times). When the mailboxes
for the second group == 1, the method finds the median house in the group and places the mailbox there.
'''
#old code to show the partition
# group1 = houses_pos[start:i]
# group2 = houses_pos[i:end]
# print(group1, group2)
#form k-1 groups out of group2
return total_dist
print(allocate_mailboxes(0, len(houses_pos) - 1, k))
|
164c21a4d7cd1fd7720ae37b63b107bb02815857 | daniel-reich/ubiquitous-fiesta | /TCbrjfMm2dPzQDbz5_5.py | 131 | 4 | 4 |
def insert_whitespace(txt):
k = ""
for letter in txt:
if letter.isupper():
k += " "
k += letter
return k[1:]
|
1f60d444cd6c7d8a72a0308e811a714d2deee1ec | emohr44/Coding-Practice | /Variables and Types.py | 404 | 4.1875 | 4 | # This script introduces the concept of data types such as of
# integers and stings. We cast strings as integers and visaversa so
# that we can add integers and concatenate strings.
one, two = 1, 2
three = one + two
four = "4"
seven = int(four) + three
print three
print seven
hello, world = "hello", "world"
helloworld = hello + " " + world
print helloworld
print helloworld + " " + str(three)
|
257bb9507e00ff99d9a75e813c1a015ad142bc46 | jwright0991/RedBlackTree | /RedBlackLeafNode.py | 345 | 3.765625 | 4 | #Black Null Nodes for bottom level of each path of a Red-Black Tree
#data is set to 0 so it will not be counted as odd
class BlackLeafNode:
def __init__(self):
self.isRed = False
self.data = None
self.isLeaf = True
self.isEvenSum = True
self.data = 0
def __str__(self):
return "B/N LEAF"
|
12c4e61cd18fa619c19005cc31cdca87f524c9b6 | Vestenar/PythonProjects | /venv/02_Codesignal/02_The Core/066_numberOfClans.py | 1,405 | 3.578125 | 4 | def numberOfClans(divisors, k):
divisors = list(set(divisors))
clans = {k: [] for k in range(1, k + 1)}
ans = []
for i in range(1, k+1):
for div in divisors:
if i % div == 0:
a = clans[i]
a.append(div)
clans[i] = a
for key, val in clans.items():
if val not in ans:
ans.append(val)
return len(ans)
divisor = [6, 2, 2, 8, 9, 2, 2, 2, 2]
kk = 10
print(numberOfClans(divisor, kk))
# divisors = [2, 6, 8, 9] (duplicates don't matter in divisors).
#
# 1,3,5,7 are divisible by none of those, 1 clan
# 2,4,10 are divisible by only 2 among these, 1 clan
# 6 is divisible by 2,6 among these, 1 clan.
# 8 is divisible by 2,8 among these, 1 clan.
# 9 is divisible by only 9 among these, 1 clan.
#
# Total is 5 clans.
'''
Let's call two integers A and B friends
if each integer from the array divisors is either a divisor of both A and B or neither A nor B.
If two integers are friends, they are said to be in the same clan.
How many clans are the integers from 1 to k, inclusive, broken into?
Example
For divisors = [2, 3] and k = 6, the output should be
numberOfClans(divisors, k) = 4.
The numbers 1 and 5 are friends and form a clan,
2 and 4 are friends and form a clan,
and 3 and 6 do not have friends and each is a clan by itself.
So the numbers 1 through 6 are broken into 4 clans.
'''
|
604064516088cd6084ffc7b2044d779234e8b5e6 | mrkienls/membership | /mem/test.py | 186 | 3.515625 | 4 | class Car:
def __init__(self, color, mileage):
self.color = color
self.mileage = mileage
def __str__(self):
return 'a {self.color} car'.format(self=self) |
0f57348d3102007047f8b0458213e3dbaae85a5e | Tang8560/Geeks | /python/bubble_sort.py | 2,072 | 4.125 | 4 | # 泡沫排序
"""
泡沫排序 (Bubble Sort) 想法是這樣的,假設要由小排到大,
左邊為小右邊為大,以左邊第一個為基準點,不斷的跟右邊的值比大小,
比較小的就往左,大的就停住,然後再從這個 礙事的 大的值繼續往右比。
如果到很不幸馬上就遇到更大的,再從更大的往右比,直到最後一個位置。
現在,已經比完第一輪了,接著再從最左邊的頭開始,往下比下去。
我們用比身高來舉例,分為 1 到 10 :
矮 ------------------------------------> 高
8 6 1 10 5 3 9 2 7 4
6 8 1 10 5 3 9 2 7 4
6 1 8 10 5 3 9 2 7 4
可惡,8 碰到 10 過不去了,那就只好讓 10 繼續比下去。
6 1 8 10 5 3 9 2 7 4
6 1 8 5 10 3 9 2 7 4
6 1 8 5 3 10 9 2 7 4
6 1 8 5 3 9 10 2 7 4
6 1 8 5 3 9 2 10 7 4
6 1 8 5 3 9 2 7 10 4
6 1 8 5 3 9 2 7 4 10
現在 10 撞牆了,已經稱霸沒得比了,所以再從頭的 6 開始往右比。
6 1 8 5 3 9 2 7 4 10
1 6 8 5 3 9 2 7 4 10
1 8 6 5 3 9 2 7 4 10
程式時間複雜度:O(N^2)
"""
data = [89, 34, 23, 78, 67, 100, 66, 29, 79, 55, 78, 88, 92, 96, 96, 23]
# 結果: data = [23, 23, 29, 34, 55, 66, 67, 78, 78, 79, 88, 89, 92, 96, 96, 100]
def bubble_sort(data):
n = len(data)
# 利用雙重迴圈去做循環比較
for i in range(n-2): # 有 n 個資料長度但只要執行 n-1 次
for j in range(n-i-1):
if j != len(data)-1:
# temp1 = data[j]
# temp2 = data[j+1]
# print(temp1, temp2)
if data[j] > data[j+1]:
"""互換方式1"""
# data[j] = temp2
# data[j+1] = temp1
"""互換方式2"""
data[j], data[j+1] = data[j+1], data[j]
print(data)
bubble_sort(data) |
b3d46b19b964721bd8e5f3485b0b0af0122b9fcf | cryptkeypr/python100days | /bmi_calculator2-0.py | 728 | 4.375 | 4 | # 🚨 Don't change the code below 👇
height = float(input("enter your height in m: "))
weight = float(input("enter your weight in kg: "))
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
#BMI = weight/(height**2)
bmi = int(round((weight/(height**2)),0))
if bmi <= 18.5:
print(f"Your BMI is {bmi}, you are underweight.")
elif bmi > 18.5 and bmi <= 25:
print(f"Your BMI is {bmi}, you are normal weight.")
elif bmi > 25 and bmi <= 30:
print(f"Your BMI is {bmi}, you are slightly overweight.")
elif bmi > 30 and bmi <= 35:
print(f"Your BMI is {bmi}, you are obese.")
elif bmi > 35:
print(f"Your BMI is {bmi}, you are clinically obese.")
else:
print("You're off the charts mate lol.")
|
68ed39b7a878a791e757d2bcceba64ff1507ad98 | gakawarstone/python | /Head_First_Python/mymodules/vsearch/vsearch.py | 369 | 3.640625 | 4 | def search4vowels(phrase: str) -> set:
"""Return vowels pinned in aforementioned phrase."""
vowels = set('aeiou')
return vowels.intersection(set(phrase))
def search4letters(phrase: str, letters: str = 'aeiou') -> set:
"""Return array of letters from 'letters',
pinned in aforementioned phrase."""
return set(letters).intersection(set(phrase))
|
8d69091e6cded850fa36b495489ba31378f1e3b3 | AndrewParisee/prog1700-cet-ap-master-python- | /tech-checks/Tech_Check3.py | 1,055 | 3.9375 | 4 | # PROG 1700 Tech Check #3 Variables, Operators, Inputs and Output
print ("Tax Withholding Calculator")
print ("")
# Define Variables
weekly_salary = int(input("Please enter the full amount of your weekly salary: $"))
dependants = int(input("How many dependants do you have?: "))
Provincial_Tax = 0.06
Federal_Tax = 0.25
Dependant_Tax = 0.02
prov_tax = ""
fed_tax = ""
dep_deduction = ""
# Perform Calculations
prov_tax = weekly_salary * Provincial_Tax
fed_tax = weekly_salary * Federal_Tax
dep_deduction = weekly_salary * Dependant_Tax * dependants
Total_Withheld = (prov_tax - dep_deduction) + fed_tax
Take_Home = weekly_salary - Total_Withheld
# Output Results
print ("")
print ("Your Provincial Tax Withheld is ${:.2f}.".format(prov_tax))
print ("Your Federal Tax Withheld is ${:.2f}.".format(fed_tax))
print ("Your Dependant Deduction for {}".format(dependants) + " dependants is ${:.2f}.".format(dep_deduction))
print ("The Total Amount Withheld is ${:.2f}.".format(Total_Withheld))
print ("Your Total Take-Home Pay is ${:.2f}.".format(Take_Home)) |
8993550dd7cfc2c0dfd5ba07c58710084cfe9f92 | isisisisisitch/python10 | /ca/bytetube/02_processControl/05_Three.py | 135 | 3.53125 | 4 | #x if 条件 else y <===> if else
a = 1
b = 2
d = 10
e = 100
c = a if a > b else b
c = (d if d > e else e) if a < b else b
print(c) |
66b2bc1d905b2b94293e9816f8932f3f623fd78d | isabelsedunko/learn-python | /16_Fibonacci.py | 335 | 3.796875 | 4 | bakery_cache = {}
def carrotcake(n):
if n in bakery_cache:
return bakery_cache[n]
if n == 1:
value = 1
elif n == 2:
value = 1
elif n > 2:
value = carrotcake(n-1) + carrotcake(n-2)
bakery_cache[n]=value
return value
for n in range(1,101):
print(n,":", carrotcake(n))
|
26245981248246b9ed362b58addd4e04e9a26df8 | llenroc/LeetCode-28 | /Search/BFS/Abstract_BFS_problems/773_Sliding_Puzzle_hard.py | 3,222 | 3.6875 | 4 | # 这道题和127题word ladder是同一种类型的,即不是在一个matrix或者tree里进行bfs
# 而是每一个node都代表一种状态,127题里每个node是目前单词的拼写,
# 这道题里每个node是board经过这么多次swap以后到现在的排布
# 而这种问题中,两个node是否相连,就看第二个node是不是第一个node经过一次transformation之后就能得到的
# 127题里就是换一个字母能不能从第一个词到第二个词,如果能,那么两个词就是相连的nodes
# 这道题就是在第一种board的排布的基础上做一次0和邻居的swap能不能得到第二种board的排布,如果能,那么
# 这两种board排布的形态就是相连的node
class Solution:
def slidingPuzzle(self, board: List[List[int]]) -> int:
# 如果input就直接等于target,return 0
# 这里必须要check以下,因为如果不check,按照下面的算法走,会把本身就等于target的board
# 里的0和旁边的一个数字swap以下,之后再下一个level再swap回来,所以会return 2
if board==[[1,2,3],[4,5,0]]:
return 0
#找到board里初始形态中0的坐标,之后我们把每一个新遇到的state给push到queue里时
#也都带着那个state的0的坐标,这样每次pop出来一个state就不需要用nested for loop
#去找0在哪了
zeroR=0
zeroC=1
for r in range(0,2):
for c in range(0,3):
if board[r][c]==0:
zeroR=r
zeroC=c
# queue里的每一个element都是一个有3个element的tuple,第一个element是board在这个state下的布局
# 即2D array,第二个element是0在这个state里的坐标,是一个tuple,第三个element是这个state在BFS
# 中所处的level
queue=[(board,(zeroR,zeroC),0)]
directions=[[1,0],[-1,0],[0,1],[0,-1]]
# 因为list不是hashable的,所以我们要把见过的state,转化成string之后存到set里
seen={str(board)}
while queue:
# 这里r和c就是当前state里0的坐标
state,(r,c),level=queue.pop()
# 找到0周围的邻居们
for d in directions:
newR=r+d[0]
newC=c+d[1]
if newR<0 or newR>=2 or newC<0 or newC>=3:
continue
# list是object,不能直接在list里swap,得先make一个list的copy之后在copy里swap
boardCopy=[row[:] for row in state]
boardCopy[r][c]=boardCopy[newR][newC]
boardCopy[newR][newC]=0
#如果swap过后的结果就等于target,那么直接return level+1
if boardCopy==[[1,2,3],[4,5,0]]:
return level+1
#否则把新的state和新state里0的坐标和level push到queue里
if str(boardCopy) not in seen:
seen.add(str(boardCopy))
queue.insert(0,(boardCopy,(newR,newC),level+1))
# 如果queue空了还没见到target,那就说明这个input board是变不成target的,return -1
return -1 |
e8cde086b998ea440b0a06f96f05104ea9397d83 | tnakaicode/jburkardt-python | /prob/runs.py | 8,721 | 3.90625 | 4 | #! /usr/bin/env python
#
def runs_mean ( m, n ):
#*****************************************************************************80
#
## RUNS_MEAN returns the mean of the Runs PDF.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 03 April 2016
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer M, N, the parameters of the PDF.
#
# Output, real MEAN, the mean of the PDF.
#
mean = float ( m + 2 * m * n + n ) / float ( m + n )
return mean
def runs_pdf ( m, n, r ):
#*****************************************************************************80
#
## RUNS_PDF evaluates the Runs PDF.
#
# Discussion:
#
# Suppose we have M symbols of one type and N of another, and we consider
# the various possible permutations of these symbols.
#
# Let "R" be the number of runs in a given permutation. By a "run", we
# mean a maximal sequence of identical symbols. Thus, for instance,
# the permutation
#
# ABBBAAAAAAAA
#
# has three runs.
#
# The probability that a permutation of M+N symbols, with M of one kind
# and N of another, will have exactly R runs is:
#
# PDF(M,N)(R) = 2 * C(M-1,R/2-1) * C(N-1,R/2-1)
# / C(M+N,N) for R even
#
# = ( C(M-1,(R-1)/2) * C(N-1,(R-3)/2 )
# + C(M-1,(R-3)/2) * C(N-1,(R-1)/2 )
# ) / C(M+N,N) for R odd.
#
# Note that the maximum number of runs for a given M and N is:
#
# M + N, if M = N
# 2 * min ( M, N ) + 1 otherwise
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 03 April 2016
#
# Author:
#
# John Burkardt
#
# Reference:
#
# Kalimutha Krishnamoorthy,
# Handbook of Statistical Distributions with Applications,
# Chapman and Hall, 2006,
# ISBN: 1-58488-635-8,
# LC: QA273.6.K75.
#
# Parameters:
#
# Input, integer M, N, the parameters of the PDF.
#
# Input, integer R, the number of runs.
#
# Output, real PDF, the value of the PDF.
#
from i4_choose import i4_choose
from sys import exit
if ( m < 0 ):
print ( '' )
print ( 'RUN_PDF - Fatal error!' )
print ( ' M must be at least 0.' )
print ( ' The input value of M = %d' % ( m ) )
exit ( 'RUN_PDF - Fatal error!' )
if ( n < 0 ):
print ( '' )
print ( 'RUN_PDF - Fatal error!' )
print ( ' N must be at least 0.' )
print ( ' The input value of N = %d' % ( n ) )
exit ( 'RUN_PDF - Fatal error!' )
if ( n + m <= 0 ):
print ( '' )
print ( 'RUN_PDF - Fatal error!' )
print ( ' M+N must be at least 1.' )
print ( ' The input value of M+N = %d' % ( m + n ) )
exit ( 'RUN_PDF - Fatal error!' )
#
# If all the symbols are of one type, there is always 1 run.
#
if ( m == 0 or n == 0 ):
if ( r == 1 ):
pdf = 1.0
else:
pdf = 0.0
return pdf
#
# Take care of extreme values of R.
#
if ( r < 2 or m + n < r ):
pdf = 0.0
return pdf
#
# The normal cases.
#
if ( ( r % 2 ) == 0 ):
pdf = float ( 2 * i4_choose ( m - 1, ( r / 2 ) - 1 ) \
* i4_choose ( n - 1, ( r / 2 ) - 1 ) ) \
/ float ( i4_choose ( m + n, n ) )
else:
pdf = float ( i4_choose ( m - 1, ( r - 1 ) / 2 ) \
* i4_choose ( n - 1, ( r - 3 ) / 2 ) \
+ i4_choose ( m - 1, ( r - 3 ) / 2 ) \
* i4_choose ( n - 1, ( r - 1 ) / 2 ) ) \
/ float ( i4_choose ( m + n, n ) )
return pdf
def runs_pdf_test ( ):
#*****************************************************************************80
#
## RUNS_PDF_TEST tests RUNS_PDF.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 03 April 2016
#
# Author:
#
# John Burkardt
#
import platform
print ( '' )
print ( 'RUNS_PDF_TEST' )
print ( ' Python version: %s' % ( platform.python_version ( ) ) )
print ( ' RUNS_PDF evaluates the Runs PDF' )
print ( '' )
print ( ' M is the number of symbols of one kind,' )
print ( ' N is the number of symbols of the other kind,' )
print ( ' R is the number of runs (sequences of one symbol)' )
print ( '' )
print ( ' M N R PDF' )
print ( '' )
m = 6
for n in range ( 0, 9 ):
print ( '' )
pdf_total = 0.0
for r in range ( 1, 2 * min ( m, n ) + 3 ):
pdf = runs_pdf ( m, n, r )
print ( ' %8d %8d %8d %14g' % ( m, n, r, pdf ) )
pdf_total = pdf_total + pdf
print ( ' %8d %14g' % ( m, pdf_total ) )
#
# Terminate.
#
print ( '' )
print ( 'RUNS_PDF_TEST' )
print ( ' Normal end of execution.' )
return
def runs_sample ( m, n, seed ):
#*****************************************************************************80
#
## RUNS_SAMPLE samples the Runs PDF.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 03 April 2016
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer M, N, the parameters of the PDF.
#
# Input, integer SEED, a seed for the random number generator.
#
# Output, integer R, the number of runs.
#
# Output, integer SEED, a seed for the random number generator.
#
from i4vec_run_count import i4vec_run_count
a, seed = runs_simulate ( m, n, seed )
r = i4vec_run_count ( m + n, a )
return r, seed
def runs_sample_test ( ):
#*****************************************************************************80
#
## RUNS_SAMPLE_TEST tests RUNS_SAMPLE.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 03 April 2016
#
# Author:
#
# John Burkardt
#
import numpy as np
import platform
from i4vec_max import i4vec_max
from i4vec_mean import i4vec_mean
from i4vec_min import i4vec_min
from i4vec_variance import i4vec_variance
nsample = 1000
seed = 123456789
print ( '' )
print ( 'RUNS_SAMPLE_TEST' )
print ( ' Python version: %s' % ( platform.python_version ( ) ) )
print ( ' RUNS_MEAN computes the Runs mean' )
print ( ' RUNS_SAMPLE samples the Runs distribution.' )
print ( ' RUNS_VARIANCE computes the Runs variance' )
m = 10
n = 5
print ( '' )
print ( ' PDF parameter M = %14g' % ( m ) )
print ( ' PDF parameter N = %14g' % ( n ) )
mean = runs_mean ( m, n )
variance = runs_variance ( m, n )
print ( ' PDF mean = %14g' % ( mean ) )
print ( ' PDF variance = %14g' % ( variance ) )
x = np.zeros ( nsample )
for i in range ( 0, nsample ):
x[i], seed = runs_sample ( m, n, seed )
mean = i4vec_mean ( nsample, x )
variance = i4vec_variance ( nsample, x )
xmax = i4vec_max ( nsample, x )
xmin = i4vec_min ( nsample, x )
print ( '' )
print ( ' Sample size = %6d' % ( nsample ) )
print ( ' Sample mean = %14g' % ( mean ) )
print ( ' Sample variance = %14g' % ( variance ) )
print ( ' Sample maximum = %6d' % ( xmax ) )
print ( ' Sample minimum = %6d' % ( xmin ) )
#
# Terminate.
#
print ( '' )
print ( 'RUNS_SAMPLE_TEST' )
print ( ' Normal end of execution.' )
return
def runs_simulate ( m, n, seed ):
#*****************************************************************************80
#
## RUNS_SIMULATE simulates a case governed by the Runs PDF.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 03 April 2016
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer M, N, the parameters of the PDF.
#
# Input, integer SEED, a seed for the random number generator.
#
# Output, integer A(M+N), a sequence of M 0's and N 1's chosen
# uniformly at random.
#
# Output, integer SEED, a seed for the random number generator.
#
import numpy as np
from i4_uniform_ab import i4_uniform_ab
a = np.zeros ( m + n )
for i in range ( m, m + n ):
a[i] = 1
for i in range ( 0, m + n - 1 ):
j, seed = i4_uniform_ab ( i, m + n - 1, seed )
k = a[i]
a[i] = a[j]
a[j] = k
return a, seed
def runs_variance ( m, n ):
#*****************************************************************************80
#
## RUNS_VARIANCE returns the variance of the Runs PDF.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 03 April 2016
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer M, N, the parameters of the PDF.
#
# Output, real VARIANCE, the variance of the PDF.
#
variance = float ( 2 * m * n * ( 2 * m * n - m - n ) ) \
/ float ( ( m + n ) * ( m + n ) * ( m + n - 1 ) )
return variance
if ( __name__ == '__main__' ):
from timestamp import timestamp
timestamp ( )
runs_pdf_test ( )
runs_sample_test ( )
timestamp ( )
|
0333fa708c6724a3c379279f2eee381c79297b90 | s-debnath/code-combat | /leetcode/problem_268.py | 383 | 3.734375 | 4 | # 268. Missing Number
# Difficulty: Easy
# https://leetcode.com/explore/challenge/card/march-leetcoding-challenge-2021/588/week-1-march-1st-march-7th/3659/
class Solution:
def missingNumber(self, nums: List[int]) -> int:
total_nums = len(nums)
expected_sum = (total_nums*(total_nums+1))//2
actual_sum = sum(nums)
return expected_sum - actual_sum
|
d5169a3f4e9fc8cbc2ec0e5e23bb14d169d49748 | gitprouser/LeetCode-3 | /ugly-number.py | 342 | 3.5 | 4 | class Solution(object):
def devide(self, o, d):
while o % d == 0:
o /= d
return o
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
ds = [2, 3, 5]
for d in ds:
num = self.devide(num, d)
return num == 1
|
2b6cdc8af7dc8940140ce46e307b936836f5877e | Silentsoul04/FTSP_2020 | /MatPlotlib Forsk/PieChart_BarChart_Metplotlib.py | 2,874 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 22 12:09:21 2020
@author: Rajesh
"""
"""
Pie chart, where the slices will be ordered and plotted counter-clockwise:
"""
import matplotlib.pyplot as plt
labels = 'CSE', 'ECE', 'IT', 'EE'
sizes = [15, 30, 25, 10]
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
explode = (0.5, 0, 0, 0) # explode 1st slice
# plt.pie(sizes, labels=labels, autopct='%.0f%%')
# or
plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.2f%%', shadow=True, startangle=180)
plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.savefig("E:\MatPlotlib Forsk\pie.jpg")
plt.show()

----------------------------------------------------------------------------------------------------------
import matplotlib.pyplot as plt
labels = 'Python','Java','c++','ML','DL','AI'
sizes = [75 , 20, 40, 90, 85, 90]
colors = ['Blue','Red','Yellow','Green','brown','lightskyblue']
explode = (0.2,0,0,0,0,0)
plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.2f%%', shadow=True, startangle=180)
plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.savefig("E:\MatPlotlib Forsk\pie1.jpg")
plt.show()
-------------------------------------------------------------------------------------------
import matplotlib.pyplot as plt
plt.pie([75 , 20, 40, 90, 85, 90],labels=['Python','Java','c++','ML','DL','AI'],\
autopct='%1.2f%%',shadow=True,explode = (0.2,0,0,0,0,0),\
colors = ['Blue','Red','Yellow','Green','brown','lightskyblue'],startangle=30)
plt.savefig("E:\MatPlotlib Forsk\pie2.jpg")
plt.show()
----------------------------------------------------------------------------------------------------------------------
"""
Plotting a bar chart
"""
import matplotlib.pyplot as plt
objects = ('Python', 'C++', 'Java', 'Perl', 'Scala', 'Lisp')
performance = [10,8,6,4,2,1]
plt.bar([0,1,2,3,4,5], performance, align='center', alpha=1.0)
plt.xticks([0,1,2,3,4,5], objects)
plt.ylabel('Usage')
plt.title('Programming Language Usage')
plt.savefig("E:\MatPlotlib Forsk\bar.jpeg")
plt.show()
------------------------------------------------------------------------------------------------------
import matplotlib.pyplot as plt
objects = ('Rajesh','sharma','Ravi','Sandeep','Yogi Londa','Mohit')
performance = [90,80,70,60,50,40]
plt.bar([0,1,2,3,4,5], performance, align = 'center' , alpha = 1.0)
plt.xticks([0,1,2,3,4,5], objects)
plt.ylabel('|_______________________Marks____________________|')
plt.xlabel('|________________________Student Names ______________|')
plt.title('Forsk School students Marks')
plt.savefig("E:\MatPlotlib Forsk\bar1.jpg")
plt.show()
--------------------------------------------------------------------------------------------------


|
75c5b02b5c08847610f561e41e16b84d47fe014a | ErisonSandro/Exercicios-Python | /exercicios/ex012- Calculando descontos.py | 278 | 3.59375 | 4 | #Faça um algoritmo que leia o preço de um produto e mostre seu novo preço
#com 5% de desconto
preço = float(input('Preço do produto? R$'))
desconto = (preço * 5) / 100
total = preço - desconto
print('O valor é {:.2f} e com desconto fica {:.2f}'.format(preço, total))
|
b921185e664cca5a8a129b253d9b71412de26600 | C-CCM-TC1028-111-2113/homework-1-LuisFernandoGonzalezCortes | /assignments/08Caracol/src/exercise.py | 216 | 3.671875 | 4 | def main():
#escribe tu código abajo de esta línea
t=float(input("Dar tiempo en minutos: "))
c = ((t * 60) * (.57))
print("Centimetros recorridos: ", c)
if __name__ == '__main__':
main()
|
a1595d473ed15493b9235b85bd90029b25759cde | jwplante/adventofcode2019 | /day5/part1.py | 5,655 | 3.75 | 4 |
class Computer:
def __init__(self, prog):
self.pc = 0 # Program Counter
self.prog = prog # Program Data
self.debug = False # Debug mode
self.paused = False # Will take in new instructions but will not execute
self.halted = False # Will stop the program
def haltProgram(self):
self.halted = True
def advanceProgCounter(self, instructions):
self.pc += instructions
# Gets the given modes for the opcode at PC
def parseArguments(self):
opcode = self.prog[self.pc] // 100
ret_array = []
for i in range(2):
ret_array.append(opcode % 10)
opcode //= 10
if self.debug: print(ret_array)
return ret_array
# Gets the opcode number for the opcode at PC
def getOpcode(self):
return self.prog[self.pc] % 100
# Stores the given value to the given address
def storeConstant(self, addr, val):
if (addr < len(self.prog)):
self.prog[addr] = val
else:
print("Access out of bounds! Terminating program!")
self.haltProgram()
# Gives the correct value for the array access depending on the mode
# @value - The true value (immediate) or address (position)
def accessConstant(self, immediate, value):
if (immediate == 1):
return value
elif (value < len(self.prog)):
return self.prog[value]
else:
print("Access out of bounds! Terminating program!")
self.haltProgram()
class IOSystem:
def __init__(self):
pass
# Takes in the input from the user
def getInput(self):
return int(input("Please enter ship's ID: "))
# Puts the output to the terminal
def putOutput(self, data):
print(str(data))
class InstructionSet:
def __init__(self, com, io):
self.com = com # Main Computer instance
self.io = io # IO class
# Opcode 1
# Takes 3 parameters
# Adds together parameters 1 and 2 and stores in parameter 3's location
def add(self):
if (self.com.pc < len(self.com.prog) - 3):
parameters = self.com.parseArguments()
mode_param1 = parameters[0]
mode_param2 = parameters[1]
arg1 = self.com.accessConstant(mode_param1, self.com.prog[self.com.pc + 1])
arg2 = self.com.accessConstant(mode_param2, self.com.prog[self.com.pc + 2])
arg3 = self.com.prog[self.com.pc + 3]
if self.com.debug: print("ADD(" + str(arg1) + ", " + str(arg2) + ") to " + str(arg3))
self.com.storeConstant(arg3, arg1 + arg2)
self.com.advanceProgCounter(4)
# Opcode 2
# Takes 3 parameters
# Multiplies together parameters 1 and 2 and stores in parameter 3's location
def multiply(self):
if self.com.debug: print("MULTIPLY")
if (self.com.pc < len(self.com.prog) - 3):
parameters = self.com.parseArguments()
mode_param1 = parameters[0]
mode_param2 = parameters[1]
arg1 = self.com.accessConstant(mode_param1, self.com.prog[self.com.pc + 1])
arg2 = self.com.accessConstant(mode_param2, self.com.prog[self.com.pc + 2])
arg3 = self.com.prog[self.com.pc + 3]
if self.com.debug: print("MULT(" + str(arg1) + ", " + str(arg2) + ") to " + str(arg3))
self.com.storeConstant(arg3, arg1 * arg2)
self.com.advanceProgCounter(4)
# Opcode 3
# Takes 1 parameter
# Stores the value of input into address parameter
def inp(self):
if self.com.debug: print("STORE")
if (self.com.pc < len(self.com.prog) - 1):
input = self.io.getInput()
store_addr = self.com.accessConstant(0, self.com.pc + 1)
self.com.storeConstant(store_addr, input)
self.com.advanceProgCounter(2)
if self.com.debug: print("STORE " + str(input) + " to " + str(store_addr))
# Opcode 4
# Takes 1 parameter
# Takes the value of address parameter 1 and outputs it.
def outp(self):
if (self.com.pc < len(self.com.prog) - 1):
parameters = self.com.parseArguments()
val = -1
if (parameters[0] == 1):
val = self.com.prog[self.com.pc + 1]
else:
addr = self.com.prog[self.com.pc + 1]
val = self.com.prog[addr]
if self.com.debug: print("OUTPUT")
self.io.putOutput(val)
self.com.advanceProgCounter(2)
# Opcode 99
# Takes no arguments
# Terminates the program
def halt(self):
if self.com.debug: print("HALT")
self.com.haltProgram()
self.com.advanceProgCounter(1)
lookup_table = {1 : add, 2 : multiply, 3 : inp, 4 : outp, 99 : halt}
# Execute the program
def executeProgram(self):
while (self.com.pc < len(self.com.prog) and not self.com.halted):
if self.com.debug: print("Current instruction: " + str(self.com.prog[self.com.pc]))
if self.com.debug: print("Prog. Counter: " + str(self.com.pc))
opcode = self.com.getOpcode()
if self.com.debug: print("Current opcode: " + str(opcode))
self.lookup_table[opcode](self)
# Open and parse the file
with open("input.txt", 'r') as f:
st_instructions = f.read()
# Convert to int array
initial_instructions = list(map(int, st_instructions.split(',')))
computer = Computer(initial_instructions)
io_system = IOSystem()
inst_set = InstructionSet(computer, io_system)
inst_set.executeProgram()
|
7d2ee3d9ccb97d6477f2556774b5437490ec5aef | prajapatisweta/python-program | /file_handling_1.py | 334 | 3.765625 | 4 | # write a program to read an entire text file
fobj = open("Batch2.txt", "w")
str_1 = "Welcome Batch 2! \nWe are working on Practical 6\nIt is based on File Handling concepts"
fobj.write(str_1)
print("Text Written to the file")
fobj = open("Batch2.txt", "r")
str_2 = fobj.read()
print("Concepts of File are:\n", str_2)
fobj.close() |
573d7540b76abc73d1ce3f5f718a0d354bab2039 | simiyukuta/route_distance_checker | /sth.py | 1,927 | 4 | 4 | track=['AB','BC','CD','DC','DE','AD','CE','EB','AE']
track_distance=[5,4,8,8,6,5,2,3,7]
route=raw_input('Enter a route\n')
route_length=len(route)
def check_route_existence(route):
if route in track:
state='Route exists\n'
return state
else:
state='NO SUCH ROUTE\n'
return state
def process_formula(route):
if len(route)==2:
f=check_route_existence(route)
if f=='Route exists\n':
x=track.index(route)
print 'Total distance for route ',route,' is ',track_distance[x],' units'
else:
print 'NO SUCH ROUTE'
elif len(route)==3:
a=route[0]
b=route[1]
c=route[2]
route1=a+b
route2=b+c
f=check_route_existence(route1)
g=check_route_existence(route2)
if f=='Route exists\n':
x=track.index(route1)
route1_distance=track_distance[x]
if g=='Route exists\n':
r=track.index(route2)
route2_distance=track_distance[r]
total_distance=route1_distance+route2_distance
print 'Total distance for route ',route,' is ',total_distance ,'units'
else:
print 'NO SUCH ROUTE'
elif len(route)==5:
a=route[0]
b=route[1]
c=route[2]
d=route[3]
e=route[4]
route1=a+b
route2=b+c
route3=c+d
route4=d+e
f=check_route_existence(route1)
g=check_route_existence(route2)
h=check_route_existence(route3)
i=check_route_existence(route4)
if f=='Route exists\n':
x=track.index(route1)
route1_distance=track_distance[x]
if g=='Route exists\n':
r=track.index(route2)
route2_distance=track_distance[r]
if h=='Route exists\n':
m=track.index(route3)
route3_distance=track_distance[m]
if i=='Route exists\n':
n=track.index(route4)
route4_distance=track_distance[n]
total_distance=route1_distance+route2_distance+route3_distance+route4_distance
print 'Total distance for route ',route,' is ',total_distance ,'units'
else:
print 'NO SUCH ROUTE'
else:
print 'YOU ARE LOST,CALL POLICE'
process_formula(route)
|
900bc6284475b9776734a2bacdc4f831cfcb350f | Hareharan6707/sdet | /python/Activity5.py | 112 | 3.8125 | 4 | n = input("Enter a number : ")
for i in range(1,11) :
num = int(n) * i
print( n , "*" , i, "=" , num) |
4025d8ebe6fc746c94e59d9c7661185922955e98 | alvarogomezmu/dam | /SistemasGestion/Python/2ev/Actividad1/Ejercicio03.py | 597 | 3.734375 | 4 | #_*_coding_utf-8_*_
'''
Escribe una funcion sumador(fichero) que, dado el nombre de un
fichero te texto que contiene numeros separados por espacios
en blanco, devuelva la suma de dichos numeros
'''
import os
def comprobarFichero(f) :
if (f, os.W_OK) :
print 'Fichero OK, Escritura OK'
elif (f, os.R_OK) :
print 'Fichero OK, Lectura OK'
else :
print 'Fichero no OK'
def sumador(f) :
numeros = f.read().split()
suma = 0
for i in numeros :
suma += int(i)
return suma
# main
f = open ('numeros.txt','r')
comprobarFichero(f)
print sumador(f)
f.close()
comprobarFichero(f)
|
7683b7eb8867d7de8f00d4801d52eb608bf7d7b2 | ajdt/udacity_cs212 | /unit7/parking_lot_search.py | 13,170 | 3.59375 | 4 | """
UNIT 4: Search
Your task is to maneuver a car in a crowded parking lot. This is a kind of
puzzle, which can be represented with a diagram like this:
| | | | | | | |
| G G . . . Y |
| P . . B . Y |
| P * * B . Y @
| P . . B . . |
| O . . . A A |
| O . S S S . |
| | | | | | | |
A '|' represents a wall around the parking lot, a '.' represents an empty square,
and a letter or asterisk represents a car. '@' marks a goal square.
Note that there are long (3 spot) and short (2 spot) cars.
Your task is to get the car that is represented by '**' out of the parking lot
(on to a goal square). Cars can move only in the direction they are pointing.
In this diagram, the cars GG, AA, SSS, and ** are pointed right-left,
so they can move any number of squares right or left, as long as they don't
bump into another car or wall. In this diagram, GG could move 1, 2, or 3 spots
to the right; AA could move 1, 2, or 3 spots to the left, and ** cannot move
at all. In the up-down direction, BBB can move one up or down, YYY can move
one down, and PPP and OO cannot move.
You should solve this puzzle (and ones like it) using search. You will be
given an initial state like this diagram and a goal location for the ** car;
in this puzzle the goal is the '.' empty spot in the wall on the right side.
You should return a path -- an alternation of states and actions -- that leads
to a state where the car overlaps the goal.
An action is a move by one car in one direction (by any number of spaces).
For example, here is a successor state where the AA car moves 3 to the left:
| | | | | | | |
| G G . . . Y |
| P . . B . Y |
| P * * B . Y @
| P . . B . . |
| O A A . . . |
| O . . . . . |
| | | | | | | |
And then after BBB moves 2 down and YYY moves 3 down, we can solve the puzzle
by moving ** 4 spaces to the right:
| | | | | | | |
| G G . . . . |
| P . . . . . |
| P . . . . * *
| P . . B . Y |
| O A A B . Y |
| O . . B . Y |
| | | | | | | |
You will write the function
solve_parking_puzzle(start, N=N)
where 'start' is the initial state of the puzzle and 'N' is the length of a side
of the square that encloses the pieces (including the walls, so N=8 here).
We will represent the grid with integer indexes. Here we see the
non-wall index numbers (with the goal at index 31):
| | | | | | | |
| 9 10 11 12 13 14 |
| 17 18 19 20 21 22 |
| 25 26 27 28 29 30 31
| 33 34 35 36 37 38 |
| 41 42 43 44 45 46 |
| 49 50 51 52 53 54 |
| | | | | | | |
The wall in the upper left has index 0 and the one in the lower right has 63.
We represent a state of the problem with one big tuple of (object, locations)
pairs, where each pair is a tuple and the locations are a tuple. Here is the
initial state for the problem above in this format:
"""
puzzle1 = (
('@', (31,)),
('*', (26, 27)),
('G', (9, 10)),
('Y', (14, 22, 30)),
('P', (17, 25, 33)),
('O', (41, 49)),
('B', (20, 28, 36)),
('A', (45, 46)),
('|', (0, 1, 2, 3, 4, 5, 6, 7, 8, 15, 16, 23, 24, 32, 39,
40, 47, 48, 55, 56, 57, 58, 59, 60, 61, 62, 63)))
# A solution to this puzzle is as follows:
# path = solve_parking_puzzle(puzzle1, N=8)
# path_actions(path) == [('A', -3), ('B', 16), ('Y', 24), ('*', 4)]
# That is, move car 'A' 3 spaces left, then 'B' 2 down, then 'Y' 3 down,
# and finally '*' moves 4 spaces right to the goal.
# Your task is to define solve_parking_puzzle:
N = 8
def solve_parking_puzzle(start, N=N):
"""Solve the puzzle described by the starting position (a tuple
of (object, locations) pairs). Return a path of [state, action, ...]
alternating items; an action is a pair (object, distance_moved),
such as ('B', 16) to move 'B' two squares down on the N=8 grid."""
goal_location = get_goal_location(N)
goal, walls, cars = None, None, []
for x in start :
if x[0] == '|':
walls = x
elif x[0] == '@':
goal = x
else:
cars.append(x)
start = (goal,) + tuple(cars) + (walls,)
def is_goal(state):
board = make_board(state, N)
return board[goal_location] == '*'
return shortest_path_search(start, successors, is_goal, N)
# But it would also be nice to have a simpler format to describe puzzles,
# and a way to visualize states.
# You will do that by defining the following two functions:
def locs(start, n, incr=1):
"Return a tuple of n locations, starting at start and incrementing by incr. If n is negative, returns empty tuple "
if n <= 0:
return tuple()
return tuple( start + i*incr for i in range(n) )
def get_goal_location(N):
" gives the goal location for an NxN grid. Goal is placed in middle of right border."
# N-1 is top-most right position, and we add N to that (n/2 -1 )times
return (N-1)+(N-1)/2 *N
def grid(cars, N=N):
"""Return a tuple of (object, locations) pairs -- the format expected for
this puzzle. This function includes a wall pair, ('|', (0, ...)) to
indicate there are walls all around the NxN grid, except at the goal
location, which is the middle of the right-hand wall; there is a goal
pair, like ('@', (31,)), to indicate this. The variable 'cars' is a
tuple of pairs like ('*', (26, 27)). The return result is a big tuple
of the 'cars' pairs along with the walls and goal pairs."""
# for wall locations, the order is top border, bottom, left
wall_locations = locs(0, N)+locs(N*(N-1), N) + locs(N,N-2, N)
right_side = list(locs(N-1+N, N-2, N))
goal_loc = get_goal_location(N)
right_side.remove(goal_loc) # remove goal, location from the list of wall_locations
wall_locations = wall_locations + tuple(right_side)
# order of the state tuple is goal_location, cars, wall_locations
return ( ('@', (goal_loc,)), ) + cars + (('|', wall_locations), )
def make_board(state, N=N):
" using a state tuple, create a full representation of a board"
grid = ['.']*(N*N) # initialize board
for (symbol, locations) in state: # fill board according to squares
for loc in locations:
grid[loc] = symbol
return grid
def car_delta(car):
" returns the delta for car movement. car is a tuple (symbol, (position_tuple)). Assumes each car takes up @ least 2 squares."
return abs( car[1][0] - car[1][1]) # subtracts two position values from each other, assumed tuple is ordered
# this function assumes the position tuple for a car is in ascending order
def movement_range(car, delta, board):
""" returns a tuple of the range a car can move of the form (pos, neg) where pos is the movement range
in the positive direction (DOWN or RIGHT) and neg is movement in the negative direction (UP or LEFT)"""
return ( num_moves(board, car[1][-1], abs(delta)), -1*num_moves(board, car[1][0], -abs(delta)) )
def num_moves(board, start, delta):
" returns the number of moves a car can make from the start position with delta"
squares, start = 0, start + delta
while board[start] == '.' or board[start] == '@':
squares += 1
start += delta
return squares
def shift_car(car, n, delta):
return ( (car[0], tuple(map(lambda x: x + n*delta, car[1]))), )
def successors(state, N=N):
board = make_board(state, N)
cars = state[1:-1]
state_action_pairs = []
for (idx, c) in enumerate(cars):
delta = car_delta(c)
pos, neg = movement_range(c, delta, board)
if pos != 0 :
for i in range(1, pos+1):
new_state = (state[0],) + cars[0:idx] + (shift_car(c, i, delta)) + cars[idx+1:] + state[-1:]
action = (c[0], i*delta)
state_action_pairs.append( (new_state, action) )
if neg != 0 :
for i in range(-1, neg-1, -1):
new_state = (state[0],) + cars[0:idx] + (shift_car(c, i, delta)) + cars[idx+1:] + state[-1:]
action = (c[0], i*delta)
state_action_pairs.append( (new_state, action) )
return dict(state_action_pairs)
def show(state, N=N):
"Print a representation of a state as an NxN grid."
board = make_board(state, N)
# Now print it out
for i,s in enumerate(board):
print s,
if i % N == N - 1: print
# Here we see the grid and locs functions in use:
puzzle1 = grid((
('*', locs(26, 2)),
('G', locs(9, 2)),
('Y', locs(14, 3, N)),
('P', locs(17, 3, N)),
('O', locs(41, 2, N)),
('B', locs(20, 3, N)),
('A', locs(45, 2))))
puzzle2 = grid((
('*', locs(26, 2)),
('B', locs(20, 3, N)),
('P', locs(33, 3)),
('O', locs(41, 2, N)),
('Y', locs(51, 3))))
puzzle3 = grid((
('*', locs(25, 2)),
('B', locs(19, 3, N)),
('P', locs(36, 3)),
('O', locs(45, 2, N)),
('Y', locs(49, 3))))
# Here are the shortest_path_search and path_actions functions from the unit.
# You may use these if you want, but you don't have to.
def shortest_path_search(start, successors, is_goal, N):
"""Find the shortest path from start state to a state
such that is_goal(state) is true."""
if is_goal(start):
return [start]
explored = set() # set of states we have visited
frontier = [ [start] ] # ordered list of paths we have blazed
while frontier:
path = frontier.pop(0)
s = path[-1]
for (state, action) in sorted(successors(s, N).items(), key=lambda x : abs(x[1][1])):
if state not in explored:
explored.add(state)
path2 = path + [action, state]
if is_goal(state):
return path2
else:
frontier.append(path2)
return []
def path_actions(path):
"Return a list of actions in this path."
return path[1::2]
show(puzzle1)
def test():
# test movement_range() function
assert set( (car[0], movement_range(car, car_delta(car), make_board(puzzle1))) for car in puzzle1[1:-1] ) == set([
('*', (0, 0)),
('G', (3, 0)),
('Y', (1, 0)),
('P', (0, 0)),
('O', (0, 0)),
('B', (2, -1)),
('A', (0, -3)) ])
assert set( (car[0], movement_range(car, car_delta(car), make_board(puzzle2))) for car in puzzle2[1:-1] ) == set([
('*', (0, -1)) ,
('B', (1, -1)) ,
('P', (0, 0)) ,
('O', (0, 0)) ,
('Y', (1, -1)) ])
# testing shift_car() function
car , n, delta= ('A', (1, 2, 3, 4)), 2, 8
assert shift_car(car, n, delta) == (('A', (17, 18, 19, 20)), )
assert shift_car(car, 1, delta) == (('A', (9, 10, 11, 12)),)
assert shift_car(car, -2, 4) == (('A', (-7, -6, -5, -4)),)
# testing successors function
assert sorted(successors(puzzle1).values()) == [('A', -3), ('A', -2), ('A', -1), ('B', -1), ('B', 1), ('B', 2), ('G', 1), ('G', 2), ('G', 3), ('Y', 1)]
assert sorted(successors(puzzle2).values()) == sorted( [ ('B', -1), ('B', 1), ('Y', 1), ('Y', -1), ('*', -1) ] )
# regression tests for solve_parking_puzzle
# these are the solutions obtained by my first version of the solver
#print solve_parking_puzzle(puzzle1)[1::2]
solution = solve_parking_puzzle(puzzle1)
print "start state"
for state in solution[0::2] :
show(state)
print
print solution[1::2]
assert solve_parking_puzzle(puzzle1)[1::2] == [('A', -3), ('Y', 24), ('B', 16), ('*', 4)]
#assert solve_parking_puzzle(puzzle2)[1::2] == [('B', -1), ('P', 3), ('O', -3), ('P', -3), ('Y', -2), ('B', 3), ('*', 4)]
#assert solve_parking_puzzle(puzzle3)[1::2] == [('B', -1), ('P', -3), ('O', -4), ('Y', 3), ('P', 3), ('B', 3), ('*', 5)]
#assert len(solve_parking_puzzle(puzzle1)[1::2]) == 4
#assert len(solve_parking_puzzle(puzzle2)[1::2]) == 7
#assert len(solve_parking_puzzle(puzzle3)[1::2]) == 7
sz = 9
puzzle4 = grid((
('*', locs(38, 2)),
), sz)
assert solve_parking_puzzle(puzzle4, sz)[1::2] == [('*', 5)]
puzzle5 = grid((
('*', locs(38, 2)),
('A', locs(22, 3, sz)),
('B', locs(49, 3)),
('O', locs(58, 2)),
('X', locs(24, 3, sz)),
('C', locs(46, 2)),
('Z', locs(10, 3)),
('Y', locs(14, 3))), sz)
print
show(puzzle5, sz)
print solve_parking_puzzle(puzzle5, sz)[1::2]
size = 6
puzzle6 = grid((
('*', locs(14, 2)),
('S', locs(20, 3)),
('B', locs(27, 2)),
('A', locs(10, 2, size))), size)
print
show(puzzle6, size)
print solve_parking_puzzle(puzzle6, size)[1::2]
print solve_parking_puzzle(puzzle6, size)[-1]
print "all tests pass"
from itertools import cycle
cars = cycle('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
hcar = lambda start, l=2: (next(cars), locs(start, l))
vcar = lambda start, l=2: (next(cars), locs(start, l, N))
star = lambda start: ('*', locs(start, 2))
sp = grid((
hcar( 9, 3), vcar(12, 2), vcar(13, 3), vcar(17, 2), hcar(18, 2),
star(27),
hcar(33, 2), vcar(35, 2), vcar(38, 2), vcar(42, 2), hcar(44, 2), hcar(51, 2), hcar(53, 2),
))
def hard_tests():
show(sp)
print solve_parking_puzzle(sp)[1::2]
#print
#show(puzzle2)
#print
#show(puzzle3)
test()
#hard_tests()
|
0eae839ff0ca6b3fd016dfc4dda4692c19e333fe | d0iasm/CtCI | /Chapter02/07_find_intersection.py | 2,027 | 3.625 | 4 | import unittest
from LinkedList import LinkedList, Node
def get_length_and_tail(ll):
n = ll.head
count = 0
if n is None:
return None, count
while n.next:
count += 1
n = n.next
return n, count
def find_intersection(ll1, ll2):
t1, c1 = get_length_and_tail(ll1)
t2, c2 = get_length_and_tail(ll2)
if t1 is not t2:
return None
shorter = ll1.head if c1 < c2 else ll2.head
longer = ll2.head if c1 < c2 else ll1.head
for _ in range(abs(c1-c2)):
longer = longer.next
while shorter != longer:
shorter = shorter.next
longer = longer.next
return shorter
class Test(unittest.TestCase):
def test_find_intersection(self):
ll1 = LinkedList()
ll2 = LinkedList()
data1 = [1,2]
data2 = [2]
data_shared = [3,4,5]
n5 = Node(data_shared[2], None)
n4 = Node(data_shared[1], n5)
n3 = Node(data_shared[0], n4)
n21 = Node(data1[1], n3)
n11 = Node(data1[0], n21)
n12 = Node(data2[0], n3)
ll1.head = n11
ll2.head = n12
self.assertEqual(n3, find_intersection(ll1, ll2))
def test_find_intersection_samelength(self):
ll1 = LinkedList()
ll2 = LinkedList()
data1 = [1,2]
data2 = [1,2]
data_shared = [3,4,5]
n5 = Node(data_shared[2], None)
n4 = Node(data_shared[1], n5)
n3 = Node(data_shared[0], n4)
n21 = Node(data1[1], n3)
n11 = Node(data1[0], n21)
n22 = Node(data2[1], n3)
n12 = Node(data2[0], n22)
ll1.head = n11
ll2.head = n12
self.assertEqual(n3, find_intersection(ll1, ll2))
def test_find_intersection_not_found(self):
ll1 = LinkedList()
ll2 = LinkedList()
data = [1,2,3,4,5]
for d in data:
ll1.append(d)
ll2.append(d)
self.assertIsNone(find_intersection(ll1, ll2))
if __name__ == '__main__':
unittest.main()
|
a2af7626ed6c73afb95b5af9d0726c23ca8d7d10 | TebelloX/Screw-pilot | /python3/even't.py | 158 | 3.703125 | 4 | # Checks if a number is even
import random
def even(num):
try:
return [True,False][num%2] if not random.randint(0, 9) else bool(random.randint(0, 1))
|
5ae06265c8b743941c753896030b6dccb5ac6ec3 | Karan-hash/Python_Questions_Hackerrank_Solutions | /Maximum_sum.py | 557 | 3.5625 | 4 | from itertools import product
n, k = map(int, input().split())
N = (list(map(int, input().split()))[1:] for _ in range(n))
results = map(lambda x: sum(i**2 for i in x)%k, product(*N))
print(max(results))
'''
*N goes through all the values of N. So we can write "*N" instead of "N[0],N[1],...,N[K-1]"
N is different because it is N and not the values of N. In this case we want "N[0],N[1],...,N[K-1]"
instead of N.
'''
# Alternative for lambda and map above = resul = (sum(no**2 for no in nos ) % k for nos in product(*N))
# print(max(resul))
|
6a19f41d1abf5d14ea260870f2e35739bf9cc0f4 | gadlakha/Binary-Search-2 | /Problem2.py | 1,049 | 3.8125 | 4 | #Problem 2:(https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/)
#Time Complexity-O(log n)
#Space Complexity-O(n)
#Test Cases passed on Leetcode
#Binary Search Used
class Solution:
def findMin(self, nums):
low=0
high=len(nums)-1
while low<=high:
mid=low+(high-low)//2
if nums[low]<nums[high]:
return nums[low]
#finding the pivot -which would be minimum element if array was sorted
if (mid==low or nums[mid]<nums[mid-1]) and (mid==high or nums[mid]<nums[mid+1]):
return nums[mid]
#if nums[mid] is smaller than or equal to nums[low],we'll find the pivot on right half
elif nums[low]<=nums[mid]:
low=mid+1
#else,we'll find the pivot on left half
else:
high=mid-1
return -1
#validate code
obj=Solution()
nums=[3,4,5,1,2]
print("Array is:")
print(nums)
minElement=obj.findMin(nums)
print('Min Element in the array is: ')
print(minElement)
|
4c6e820400a82c04fd4499b53e709a35d42d198d | conniec-dev/thinkpython_practices | /chapter17/last_ex_2.py | 1,373 | 4.25 | 4 | class Kangaroo:
"""A Kangaroo is a marsupial."""
def __init__(self, name, contents=None):
"""Initialize the pouch contents.
name: string
contents: initial pouch contents.
"""
# In this version, the default value is None. When
# __init__ runs, it checks the value of contents and,
# if necessary, creates a new empty list. That way,
# every Kangaroo that gets the default value gets a
# reference to a different list.
# As a general rule, you should avoid using a mutable
# object as a default value, unless you really know
# what you are doing.
self.name = name
if contents == None:
contents = []
self.pouch_contents = contents
def __str__(self):
"""Return a string representaion of this Kangaroo."""
t = [self.name + " has pouch contents:"]
for obj in self.pouch_contents:
s = " " + object.__str__(obj)
t.append(s)
return "\n".join(t)
def put_in_pouch(self, item):
"""Adds a new item to the pouch contents.
item: object to be added
"""
self.pouch_contents.append(item)
kanga = Kangaroo("Kanga")
roo = Kangaroo("Roo")
kanga.put_in_pouch("wallet")
kanga.put_in_pouch("car keys")
kanga.put_in_pouch(roo)
print(kanga)
print(roo) |
84fee7978474a2294c5bbfd764802459f54c180d | GuilhermeMenez/Caixa-Registradora | /Caixa_Registradora.py | 689 | 3.65625 | 4 | from functools import reduce
precos = []
inicio = 1
def soma(x, y):
return x + y
def caixa_registradira():
valor_final = reduce(soma, precos)
print(valor_final)
valor_recebido = int(input("digite o valor pago pelo cliente\n"))
troco = valor_final - valor_recebido
print(troco)
receber_produtos()
def receber_produtos():
preco_produto = int(input("digite o preço do produto\n"))
encerrar = int(input(" digite 0 para encerrar, e 1 para continuar\n"))
precos.append(preco_produto)
if encerrar == 0:
return 0
while inicio != 0:
receber_produtos()
if receber_produtos() == 0:
inicio = 0
caixa_registradira()
|
62915d6e84bc6598c8a2a4cdcbf21f015da44cba | betta-cyber/leetcode | /python/206-reverse-linked-list.py | 1,080 | 3.96875 | 4 | #!/usr/bin/env python
# encoding: utf-8
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
return self._reverse(head, None)
def _reverse(self, node, pre):
if not node:
return pre
n = node.next
node.next = pre
return self._reverse(n, node)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head:
return None
tmp = []
while head:
tmp.append(head)
head = head.next
result = tmp.pop()
current = result
while tmp:
k = tmp.pop(-1)
current.next = k
k.next = None
current = k
return result
|
3026072d28d1ab702b836637bd88baf155087bca | YiyingW/Individual_Programs | /cluster_algorithms/kruskal.py | 3,172 | 4.34375 | 4 |
class Weighted_graph:
"""
Implement a weighted graph with a 2d list and a corresponding weight list
Vertices are represented by elements (eg. 1,2,3) in the graph list and edges are represented by a list collection of
each 2 vertices (eg. [1,2])
"""
edges = []
weight = []
vertices = []
def __init__(self, edge_list, weight):
self.edges = edge_list
self.weight = weight
def add(self, edge_list, weight):
"""
add an edge (defined by 2 vertices in a list) and its corresponding weight to edges
"""
self.edges.append(edge_list)
self.weight.append(weight)
def print_graph(self):
"""
print each set of edges in a graph and its corresponding edges
"""
print self.edges
print self.weight
print self.vertices
def __sort(self):
"""
sorts both edges and weight lists in nondecreasing order of weight list elements
"""
if len(self.edges) != len(self.weight):
return
for i in range(1, len(self.weight)):
print i
temp_weight = self.weight[i]
temp_edge = self.edges[i]
current = i - 1
while current >= 0 and temp_weight < self.weight[current]:
self.weight[current+1] = self.weight[current]
self.edges[current+1] = self.edges[current]
current -= 1
self.weight[current+1] = temp_weight
self.edges[current+1] = temp_edge
def __makeset(self):
"""
initialize each vertex to its own component
"""
for i in range(len(self.edges)):
for j in range(len(self.edges[i])):
if self.edges[i][j] not in self.vertices:
self.vertices.append(self.edges[i][j])
for k in range(len(self.vertices)):
self.vertices[k] = [self.vertices[k]]
def __findset(self, vertex):
"""
find and return the index to which vertex belongs in vertices list
"""
for i in range(len(self.vertices)):
for element in self.vertices[i]:
if element == vertex:
return i
return None
def __union(self, vertex1, vertex2):
"""
join 2 vertex together
"""
index1 = self.__findset(vertex1)
index2 = self.__findset(vertex2)
for element in self.vertices[index2]:
self.vertices[index1].append(element)
self.vertices.pop(index2)
def kruskal(self):
self.__sort()
print "sorting is done"
self.__makeset()
print "set is initiated"
count, i = 0, 0
while len(self.vertices) > 1:
if self.__findset(self.edges[i][0])!= self.__findset(self.edges[i][1]):
print "(%d %d) edge selected." % (self.edges[i][0], self.edges[i][1])
count += 1
self.__union(self.edges[i][0], self.edges[i][1])
i += 1
print i
"""
edges = [[3, 4], [1, 3], [5, 6], [1, 5], [3, 6], [1, 2], [2, 4], [3, 5], [4, 6]]
weight = [4,2,3,5,1,6,3,6,2]
graph1 = Weighted_graph(edges, weight)
graph1.print_graph()
graph1.kruskal()
graph1.print_graph()
"""
edges = []
weights = []
text_file = open("file1.txt", "r")
lines = text_file.readlines()
for nline in range(1, len(lines)):
edge_weight_list = lines[nline].rstrip().split(" ")
edge = [int(edge_weight_list[0]), int(edge_weight_list[1])]
weight = int(edge_weight_list[2])
edges.append(edge)
weights.append(weight)
print "reading data is done"
graph = Weighted_graph(edges, weights)
print "graph is created"
graph.kruskal()
|
4866476e5433cebeb86bba509864f61415c8ea6f | Forgotten-Forever/Sword-finger-offer | /ReverseList.py | 1,123 | 4.15625 | 4 | #!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: forgotten_liu
@projectName: python_study
@file: ReverseList
@time: 2020/12/29 20:04
@IDE: PyCharm
@desc: 反转链表
输入一个链表,反转链表后,输出新链表的表头
输入
{1,2,3}
返回值
{3,2,1}
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 方法一
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
if not pHead:
return None
root = None
# 将 pHead 输出,最后一个就是 root 的值
while pHead:
pHead.next, root, pHead = root, pHead, pHead.next
return root
# 方法二、递归到最后将数据输出到 cur
class Solution1:
# 返回ListNode
def ReverseList(self, pHead):
if not pHead or not pHead.next:
return pHead
cur = self.ReverseList(pHead.next)
pHead.next.next = pHead
pHead.next = None
return cur
arr = ListNode(1)
arr.next = ListNode(2)
arr.next.next = ListNode(3)
# s = Solution()
s = Solution1()
print(s.ReverseList(arr))
|
cb4a2043b0c57050666df8628f68acab29e67c62 | cloudsecuritylabs/pythonclassaug2021 | /datatypes-class2/13.stringmanupulation.py | 334 | 3.515625 | 4 | # string concatenation
# first_name + last_name
my_string = "Best students ever!"
print(my_string[0])
print(my_string[0:4])
print(my_string[-1])
print(my_string[4:])
splitted = my_string.split(" ")
print(f'here we go :{splitted[0]}')
is_true = (18.0 == 18.0001)
print(is_true)
is_true = (18.0 == 18.0000000000000000000000000001)
|
2673480a24a1879c2a38df31c2c0683424a04348 | vsdrun/lc_public | /co_twitter/217_Contains_Duplicate.py | 971 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/contains-duplicate/description/
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least
twice in the array,
and it should return false if every element is distinct.
"""
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return len(set(nums)) != len(nums)
def containsDuplicate_slow(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
import collections as cc
result = cc.Counter(nums)
result = result.most_common()
return False if not result or result[0][1] == 1 else True
def build():
return [0]
return []
return [9, 3, 15, 20, 3, 7]
if __name__ == "__main__":
s = Solution()
print(s.containsDuplicate(build()))
|
494b9016a2abbec33f78672dd556e703034237a3 | misbaa/python-assignments | /Day2-assign/Q3.py | 671 | 3.640625 | 4 | Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
#Question-3
>>> dict = {"brand" :"Ford","model":"Mustang","year":1964}
>>> x=dict.get("brand")
>>> print(x)
Ford
>>> y=dict.keys()
>>> print(y)
dict_keys(['brand', 'model', 'year'])
>>> dict.update({"color":"Black"})
>>> print(dict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'Black'}
>>> z=dict.values()
>>> print(z)
dict_values(['Ford', 'Mustang', 1964, 'Black'])
>>> dict.pop("color")
'Black'
>>> print(dict)
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
>>> |
069c5a2be8ee849ba50697344977e7ca1b709514 | thiago5171/python. | /exercicios/ex040.py | 922 | 3.828125 | 4 | """Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa,
mostre: a média de idade do grupo,
qual é o nome do homem mais velho e
quantas mulheres têm menos de 20 anos.
"""
vinte= 0
maior = 0
maiorn = ""
somaidade = 0
for i in range(1,5):
nome = str(input("digite o nome da {}°pessoa: ".format(i)))
idade = int(input("digite a idade da {}° pessoa: ".format(i)))
sexo = str(input("digite o sexo masculino(m) ou feminino(f) [f/m] : "))
print("")
somaidade = somaidade + idade
if sexo == "m":
if idade > maior :
maiorn= nome
else:
if sexo == "f" :
if idade <20 :
vinte= vinte +1
media = somaidade /4
print("a idade media do grupo é de {} anos ".format(media))
print("o homem mais velho é o {} ".format(maiorn))
print("{} mulheres do grupo tem menos de 20 anos ".format(vinte))
|
877a24dbce31099cd3ba89ad41d3a15f461b3d00 | ls-2018/Django_Practice | /others/python从菜鸟到高手/第二章/进一步控制字符串格式参数.py | 1,043 | 3.84375 | 4 | print("{first!s} {first!r} {first!a}".format(first='中'))
"""
字符串
!s 原样输出
!r 调用repr
!a 输出Unicode编码
:f 将十进制数格式化为浮点数, nan\inf 转换为小写
:F 将十进制数格式化为浮点数, nan\inf 转换为大写
c 将一个整数解释为ASCII
!b 十进制数转二进制数
d 将整数格式转换为十进制数
e 将十进制数转换为科学计数法
E 将十进制数转换为科学计数法
:o 将十进制数转换为八进制数
g 根据整数的范围在浮点数和科学计数法之间
G 根据整数的范围在浮点数和科学计数法之间,e为大写
:x 将十进制数转换为十六进制数,字母部分小写
:X 将十进制数转换为十六进制数,字母部分大写
:% 将数字格式化为百分形式
"""
print('{:.5}'.format("hello,world")) # 截取前5个字符
print("{:,}".format(10 * 1000000000000000000000000)) # 用千分位符号输出10,000,000,000,000,000,000,000,000
print("{:%}".format(0.01)) |
8ffd09f2d1cacb933d418e5b646169b6ef722063 | Nymrinae/EPITECH-Projects | /Mathematics/200/201yams/combinaisons.py | 1,105 | 3.671875 | 4 | import sys
from maths import *
def buildDicesList(list):
for i in range(1, 6):
list.append(int(sys.argv[i]))
return (list)
def full(dices, a, b):
a = int(a)
b = int(b)
v_a = dices.count(a)
v_b = dices.count(b)
if (v_a == 3 and v_b == 2):
res = 100
else:
if (v_a > 3):
v_a = 3
if (v_b > 2):
v_b = 2
res = calcProbaFull(v_a, v_b)
print("chances to get a " + str(a) + " full of " + str(b) + ": %0.2f%%" % (res))
def launchGame(dices, list):
c = list[0]
a = list[1]
if (len(list) > 2):
b = int(list[2])
if (c == "pair"):
printResult(c, a, calcProba(dices, 2, a))
elif (c == "three"):
printResult("three-of-a-kind", a, calcProba(dices, 3, a))
elif (c == "four"):
printResult("four-of-a-kind", a, calcProba(dices, 4, a))
elif (c == "full"):
full(dices, a, b)
elif (c == "straight"):
exit(84)
elif (c == "yams"):
printResult(c, a, calcProba(dices, 5, a))
else:
print("Not realized yet.")
exit(84) |
494cc6616e60c1be17b8c18307df4edabfa1cdf2 | Kalyvan420/Inf | /ТЯП/Lab2/23.py | 548 | 3.765625 | 4 | N = int(input('Введите кол-во элементов списка(больше 10): '))
sp = []
if N > 10:
for i in range (0, N):
sp.append(int(input('Введите ' + str(i+1) +' элемент списка: ')))
print(sp)
for i in range (5):
sp.append(int(input('Введите новый элемент списка ' + str(i+1) + ': ')))
print(len(sp))
sp=[x for x in sp if x % 2 == 1]
print(sp)
else:
print('Вводимое число должно быть больше 10')
|
6ee36f6e0496f27988cdd00c2a2013c74931aa7a | issashu/Code-Academy | /Python/20210509/main.py | 323 | 3.9375 | 4 | class EvenOnly(list):
def append(self, integer):
if not isinstance(integer, int):
print("Only integers can be added")
if integer % 2:
print("Only even numbers is recommended to be added")
super().append(integer)
instance = EvenOnly()
instance.append(64)
print(instance) |
0931ce2c3bcd9d0a70417e79d61404ace2f0d41d | AdityaShidlyali/Python | /Learn_Python/Chapter_10/1_intro_dictionary_comprehension.py | 399 | 4.53125 | 5 | # to generate the following dictionary
# {1:1, 2:4, 3:9}
square = {num : num**2 for num in range(1, 5)}
print(square)
# to print the strings as well in the dictionary comprehension is :
square = {f"Square is {num} is {num**2}" for num in range(1, 5)}
print(square)
# word counter using dictionary comprehension :
name = "aditya"
word_count = {ch : name.count(ch) for ch in name}
print(word_count) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.