blob_id
stringlengths 40
40
| repo_name
stringlengths 5
119
| path
stringlengths 2
424
| length_bytes
int64 36
888k
| score
float64 3.5
5.22
| int_score
int64 4
5
| text
stringlengths 27
888k
|
---|---|---|---|---|---|---|
ce1a87b1eecec2297d01e659db08ff7db34e6ae5 | jubic/RP-Misc | /System Scripting/Problem13/creatingTablesInsertDataQuery.py | 1,372 | 4.34375 | 4 | import sqlite3
#
conn = sqlite3.connect("albums.db")
#
conn.execute("PRAGMA foreign_keys = 1")
conn.execute("CREATE TABLE albums (id INTEGER PRIMARY KEY, name TEXT NOT NULL, artist TEXT NOT NULL)")
conn.execute("CREATE TABLE tracks (id INTEGER PRIMARY KEY, name TEXT NOT NULL, album_id INTEGER NOT NULL REFERENCES albums)")
#
conn.execute("INSERT INTO albums (name, artist) VALUES ('The Wall', 'Pink Floyd')")
conn.execute("INSERT INTO albums (name, artist) VALUES ('The Game', 'Queen')")
#
conn.execute("INSERT INTO tracks (name, album_id) VALUES ('Is There Anybody Out There', 1)")
conn.execute("INSERT INTO tracks (name, album_id) VALUES ('Comfortably Numb', 1)")
conn.execute("INSERT INTO tracks (name, album_id) VALUES ('Hey You', 1)")
#
conn.execute("INSERT INTO tracks (name, album_id) VALUES ('Play The Game', 2)")
conn.execute("INSERT INTO tracks (name, album_id) VALUES ('Save Me', 2)")
conn.execute("INSERT INTO tracks (name, album_id) VALUES ('Another One Bites The Dust', 2)")
#
cursor = conn.execute("INSERT INTO tracks (name, album_id) VALUES ('Another One Bites The Dust', 2)")
print "The primary key of the inserted row above is", cursor.lastrowid
#
cursor = conn.execute("SELECT tracks.name FROM albums, tracks WHERE albums.id = tracks.album_id AND albums.artist = 'Queen'")
#
data = cursor.fetchall()
#
for item in data:
print item[0]
#
conn.commit() |
db724b5c3178e379cb951d95a16d9dda55d8bc77 | ivo-bass/SoftUni-Solutions | /programming_basics/more_exercise/nested_loops/safe_passwords_generator.py | 675 | 3.578125 | 4 | x_end = int(input())
y_end = int(input())
max_passwords_count = int(input())
a = 35
b = 64
while max_passwords_count > 0:
for x in range(1, x_end + 1):
for y in range(1, y_end + 1):
a_ascii = chr(a)
a += 1
if a == 56:
a = 35
b_ascii = chr(b)
b += 1
if b == 97:
b = 64
password = f"{a_ascii}{b_ascii}{x}{y}{b_ascii}{a_ascii}"
print(password, end="|")
max_passwords_count -= 1
if max_passwords_count <= 0:
break
if max_passwords_count <= 0:
break
else:
break
|
3599714a3da382eda4b3dc48125948da21d428ba | pjhu/effective-script | /lintcode/lintcode/trailing_zeros.py | 515 | 4.125 | 4 | # -*- coding utf-8 -*-
"""
second
http://www.lintcode.com/en/problem/trailing-zeros/
Write an algorithm which computes the
number of trailing zeros in n factorial.
"""
class TrailingZero(object):
"""
:param n: a integer
:return: ans a integer
"""
def trailing_zeros(self, n):
counter = 0
tmp = n
while tmp:
tmp //= 5
counter += tmp
return counter
if __name__ == "__main__":
obj = TrailingZero()
print(obj.trailing_zeros(100))
|
b0570dc1ce63929990a2a5899110d894f9ad338e | DaVinci42/LeetCode | /116.PopulatingNextRightPointersinEachNode.py | 790 | 3.921875 | 4 | # Definition for a Node.
class Node:
def __init__(
self,
val: int = 0,
left: "Node" = None,
right: "Node" = None,
next: "Node" = None,
):
self.val = val
self.left = left
self.right = right
self.next = next
class Solution:
def connect(self, root: Node) -> Node:
if not root:
return root
if root.left:
self.connectNode(root.left, root.right, None)
return root
def connectNode(self, left: Node, right: Node, tail: Node) -> Node:
left.next = right
right.next = tail
if left.left:
self.connectNode(left.left, left.right, right.left)
self.connectNode(right.left, right.right, None if not tail else tail.left)
|
3d9588be5856aaecce597101fc10ea07a10dd5f3 | niknameovich/Python_Geek | /Exercise2.py | 214 | 3.6875 | 4 | seconds = int(input('Введите количество секунд: '))
myformat = f'часы = {seconds // 3600};минуты = {(seconds % 3600)//60};секунды = {(seconds % 3600) % 60};'
print(myformat)
|
5f8fa42898d7bea5aa1356f093c541324a7aebe8 | denyadenya77/beetroot_units | /unit_2/lesson_13/presentation/11.py | 246 | 4.125 | 4 | # С помощью функции map преобразовать список строк в список чисел: [‘1’, ‘2’, ‘3’, ‘4’] => [1, 2, 3, 4]
l = ['1', '2', '3', '4']
ll = list(map((lambda x: int(x)), l))
print(ll)
|
e8943ead541674b92ca5b619eac9105105f7614e | theavgroup/Pyhon_Basics | /04.py | 627 | 4.03125 | 4 | first_name = "arvind"
last_name = "sharma"
full_name = first_name + " " + last_name
print(full_name)
first_name = "arvind"
last_name = "sharma"
full_name = first_name + " " + last_name
print(full_name.title()+"!")
first_name = "Arvind"
last_name = "Sharma"
full_name = first_name + " " + last_name
print(full_name.upper()+"!")
first_name = "Arvind"
last_name = "Sharma"
full_name = first_name + " " + last_name
print(full_name.lower() + "!")
first_name = "Arvind"
last_name = "Sharma"
full_name = first_name+" " + last_name + " " + "!"
message = "Hello , " + full_name.lower()
print(message)
|
9a1e48f9f439ca7c542f14383082af31e0ced752 | Megscammell/METOD-Algorithm | /src/metod_alg/objective_functions/shekel.py | 1,481 | 3.921875 | 4 | def shekel_function(point, p, matrix_test, C, b):
"""
Compute the Shekel function at a given point with given arguments.
Parameters
----------
point : 1-D array with shape (d, )
A point used to evaluate the function.
p : integer
Number of local minima.
matrix_test : 3-D array with shape (p, d, d).
C : 2-D array with shape (d, p).
B : 1-D array with shape (p, )
Returns
-------
float(-total_sum * 0.5) : float
Function value.
"""
total_sum = 0
for i in range(p):
total_sum += 1 / ((point - C[:, i]).T @ matrix_test[i] @
(point - C[:, i]) + b[i])
return(-total_sum * 0.5)
def shekel_gradient(point, p, matrix_test, C, b):
"""
Compute Shekel gradient at a given point with given arguments.
Parameters
----------
point : 1-D array with shape (d, )
A point used to evaluate the gradient.
p : integer
Number of local minima.
matrix_test : 3-D array with shape (p, d, d).
C : 2-D array with shape (d, p).
b : 1-D array with shape (p, ).
Returns
-------
grad : 1-D array with shape (d, )
Gradient at point.
"""
grad = 0
for i in range(p):
num = matrix_test[i] @ (point - C[:, i])
denom = ((point - C[:, i]).T @ matrix_test[i] @ (point - C[:, i]) +
b[i]) ** (2)
grad += (num / denom)
return grad
|
5cd02c1910f5cbc2b346cfe7a126ec024407efb5 | MixedRealityLab/nottreal | /nottreal/controllers/c_abstract.py | 2,337 | 3.8125 | 4 |
import abc
class AbstractController:
def __init__(self, nottreal, args):
"""
Abstract controller class. All controllers should inherit
this class
Arguments:
nottreal {App} -- Application instance
args {[str]} -- Application arguments
"""
self.nottreal = nottreal
self.args = args
self.responder = self.nottreal.responder
self.router = self.nottreal.router
@abc.abstractmethod
def respond_to(self):
"""
Label of the controller this class will respond to. Note
that multiple controllers can have the same label, but the
last controller to be instantiated wins
Alternatively can be a list of labels.
Decorators:
abc.abstractmethod
Returns:
str/[str] -- Label(s) for this controller
"""
pass
def relinquish(self, instance):
"""
Relinquish control over signals destined for this
controller to the controller?
Arguments:
instance {AbstractController} -- Controller that has
said it wants to be a responder for the same signals
as this controller.
Returns:
{bool} -- True if it's OK to relinquish control
"""
return False
def ready_order(self, responder=None):
"""
Return a position in the queue to be readied. If below 0
then the {ready} method will not be called.
Arguments:
responder {str} -- The responder to be readied. If not
specified, assume its all responders
handled by this class
Returns:
{int}
"""
return 100
def ready(self, responder=None):
"""
Run any additional commands once all controllers are ready
(allows for running cross-controller hooks)
Arguments:
responder {str} -- The responder to be readied. If not
specified, assume its all responders
handled by this class
"""
pass
@abc.abstractmethod
def quit(self):
"""
Make any necessary arrangements to quit the app now
"""
pass
|
aaa1c8600f58fa1846e7b5c08dbf0cdb3935be2e | arifanf/Python-AllSubjects | /PDP 3/pdp3_72.py | 218 | 4 | 4 | from sys import argv
def main():
n=int(input())
if((n>=5) and (n<=6) or (n>=10)):
benar=True
else:
benar=False
print("5<={}<6 atau {}>=10 {}\n".format(n,n,benar))
if __name__ == '__main__':
main() |
52db54372025d184abf1cd48eb33bb58cbb5482a | oscar503sv/basicos_python | /diccionarios/llaves.py | 214 | 3.53125 | 4 | diccionario = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8}
resultado = diccionario.keys()
print(resultado)
resultado = diccionario.values()
print(resultado)
resultado = diccionario.items()
print(resultado)
|
06add00394967fa3224b7a3c9cddad3ee832da5a | jgross21/Programming2Jonah | /Recursion/Recursion.py | 2,738 | 4.125 | 4 | # Functions can call functions
def f():
print('f')
g()
def g():
print('g')
f()
# Function calling itself
def f():
print('f')
f()
#f()
# we can controll the recursion depth
def controlled(level, end_level):
print('Recursion level:', level)
if level < end_level:
controlled(level + 1, end_level)
controlled(0, 10)
import turtle
import random
my_turtle = turtle.Turtle()
my_turtle.speed(0)
my_turtle.width(3)
my_turtle.shape('turtle')
my_screen = turtle.Screen()
'''
my_turtle.goto(0, 0)
my_turtle.goto(100, 0)
my_turtle.goto(100, 100)
my_turtle.pencolor('lightblue')
my_turtle.forward(100)
my_turtle.left(90)
my_turtle.forward(100)
my_turtle.right(45)
my_turtle.backward(50)
my_turtle.penup()
my_turtle.goto(0, 0)
my_turtle.pendown()
my_turtle.setheading(90) # turn to the heading (0 right, 90 up, 180 left)
# draw a shape
my_turtle.fillcolor('red')
my_turtle.pencolor('black')
my_turtle.begin_fill()
for i in range(8):
my_turtle.forward(50)
my_turtle.right(360 / 8)
my_turtle.end_fill()
distance = 20
for i in range (100):
my_turtle.forward(distance + i)
my_turtle.right(15)
my_screen.clear()
'''
def rect(width, heihgt):
my_turtle.penup()
my_turtle.goto(-width / 2, heihgt / 2)
my_turtle.pendown()
my_turtle.pencolor('purple')
my_turtle.setheading(0)
for i in range(2):
my_turtle.forward(width)
my_turtle.right(90)
my_turtle.forward(heihgt)
my_turtle.right(90)
def rectcursive(width, heihgt, depth ,linewidth=3):
if depth > 0:
my_turtle.pensize(linewidth)
my_turtle.penup()
my_turtle.goto(-width / 2, heihgt / 2)
my_turtle.pendown()
my_turtle.pencolor('purple')
my_turtle.setheading(0)
for i in range(2):
my_turtle.forward(width)
my_turtle.right(90)
my_turtle.forward(heihgt)
my_turtle.right(90)
rectcursive(width * 1.25, heihgt * 1.25, depth - 1, linewidth * 1.25)
#rectcursive(40, 15, 12, 1)
def bracket_recursion(size, depth, x=-300, y=0):
my_turtle.penup()
my_turtle.goto(x, y)
my_turtle.pendown()
my_turtle.setheading(90)
my_turtle.forward(size)
my_turtle.right(90)
my_turtle.forward(100)# makes constant
pos1 = my_turtle.pos()
my_turtle.penup()
my_turtle.goto(x, y)
my_turtle.pendown()
my_turtle.setheading(270)
my_turtle.forward(size)
my_turtle.left(90)
my_turtle.forward(100)
pos2 = my_turtle.pos()
if depth > 0:
x, y = pos1
bracket_recursion(size * .5, depth - 1, x, y)
x, y = pos2
bracket_recursion(size * .5, depth - 1, x, y)
bracket_recursion(100, 5)
my_screen.exitonclick()
|
3af7d3f4e1f42adb2a3a86002efc7a26e96ca732 | RostSLO/ML | /Linear Regression/linearRegression.py | 1,683 | 3.890625 | 4 | '''
Created on March 05, 2021
@author: rboruk
'''
import pandas as pd
import numpy as np
import sklearn
from sklearn import linear_model
from sklearn.utils import shuffle
import matplotlib.pyplot as plt
import csv
#preparing pandas dataframe
data = pd.read_csv("student-mat.csv", sep=";")
#shuffle data
data = shuffle(data, random_state=22)
#pre-processing to get only required information
data = data[["G1", "G2", "G3", "studytime", "failures", "absences"]]
print(data.head())
predict = "G3"
#split the data trainig elements and results
X = np.array(data.drop([predict], 1))
Y = np.array(data[predict])
#X = data.drop([predict], axis=1)
#Y = data[predict]
#split the target data to the training and testing sets of data
X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, Y, test_size=0.1)
#create linear regression object
linear = linear_model.LinearRegression()
#train the model on train data
linear.fit(X_train, y_train)
#find the accuracy
acc = linear.score(X_test, y_test)
#make prediction of the marks on test data
predictG3 = linear.predict(X_test)
#create list of # of samples used for prediction
# will be used to plot the actual and predicted data by samples
axisX = [i for i in range(len(predictG3))]
# Plot outputs
#plot the actual marks
plt.plot(axisX, y_test, color='green', label="Actual data")
#plot the predicted marks
plt.plot(axisX, predictG3, color='blue', label="Predicted data")
#titles for the labels and the plot
plt.xlabel('Sample')
plt.ylabel('G3 - mark for the year')
plt.title(f"Real marks versus predicted by ML with accuracy = {str(round(acc*100, 2))}%")
#show the legend
plt.legend()
#display plot
plt.show()
|
339d0517cc3a1eaf1d6a8d3894169e633b87938d | tahniyat-nisar/if_else | /arti gayatri.py | 806 | 4.03125 | 4 | arti=int(input('enter age of arti:'))
gayatri=int(input("enter age of gayatri:"))
vaishnavi=int(input("enter age of vaishnavi:"))
if (arti>gayatri and vaishnavi):
print("arti is elder")
elif gayatri<vaishnavi:
print('vaishnavi is second elder\ngayatri is younger')
if vaishnavi>gayatri:
print("gayatri is second elder\nvaishnavi is younger")
elif gayatri>arti and vaishnavi:
print("gayatri is elder")
if arti<vaishnavi:
print("vaishnavi is second elder\narti is younger")
elif arti>vaishnavi:
print("arti is second elder\nvaishnavi is younger")
if vaishnavi>arti and gayatri:
print("vaishnavi is elder")
elif arti<gayatri:
print("gayatri is second elder\n arti is younger")
if arti>gayatri:
print("arti is second elder\n gayatri is younger") |
d88927f3f1d94de5db21d4e6d457005435dd4cab | alexandrucatanescu/neural-program-comprehension | /stimuli/Python/one_file_per_item/jap/104_# str_if 14.py | 159 | 3.78125 | 4 | bunsyou = "I am a"
gengo = "cat"
if len(gengo) > 3:
print(gengo)
elif bunsyou[-1] == gengo[1]:
print(bunsyou)
else:
print(bunsyou + " " + gengo)
|
2c3c54422345861dcdb5e1f2cea80cdaddbd2a64 | tcloud1105/Apache-Spark-and-Python | /RB-Python/SparkMLUseCaseClustering.py | 3,302 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Spark with Python
Copyright : V2 Maestros @2016
Code Samples : Spark Machine Learning - Clustering
The input data contains samples of cars and technical / price
information about them. The goal of this problem is to group
these cars into 4 clusters based on their attributes
## Techniques Used
1. K-Means Clustering
2. Centering and Scaling
-----------------------------------------------------------------------------
"""
import os
os.chdir("C:/Personal/V2Maestros/Courses/Big Data Analytics with Spark/Python")
os.curdir
#Load the CSV file into a RDD
autoData = sc.textFile("auto-data.csv")
autoData.cache()
#Remove the first line (contains headers)
firstLine = autoData.first()
dataLines = autoData.filter(lambda x: x != firstLine)
dataLines.count()
from pyspark.sql import SQLContext,Row
sqlContext = SQLContext(sc)
import math
from pyspark.mllib.linalg import Vectors
#Convert to Local Vector.
def transformToNumeric( inputStr) :
attList=inputStr.split(",")
doors = 1.0 if attList[3] =="two" else 2.0
body = 1.0 if attList[4] == "sedan" else 2.0
#Filter out columns not wanted at this stage
values= Vectors.dense([ doors, \
float(body), \
float(attList[7]), \
float(attList[8]), \
float(attList[9]) \
])
return values
autoVector = dataLines.map(transformToNumeric)
autoVector.persist()
autoVector.collect()
#Centering and scaling. To perform this every value should be subtracted
#from that column's mean and divided by its Std. Deviation.
#Perform statistical Analysis and compute mean and Std.Dev for every column
from pyspark.mllib.stat import Statistics
autoStats=Statistics.colStats(autoVector)
colMeans=autoStats.mean()
colVariance=autoStats.variance()
colStdDev=map(lambda x: math.sqrt(x), colVariance)
#place the means and std.dev values in a broadcast variable
bcMeans=sc.broadcast(colMeans)
bcStdDev=sc.broadcast(colStdDev)
def centerAndScale(inVector) :
global bcMeans
global bcStdDev
meanArray=bcMeans.value
stdArray=bcStdDev.value
valueArray=inVector.toArray()
retArray=[]
for i in range(valueArray.size):
retArray.append( (valueArray[i] - meanArray[i]) /\
stdArray[i] )
return Vectors.dense(retArray)
csAuto = autoVector.map(centerAndScale)
csAuto.collect()
#Create a Spark Data Frame
autoRows=csAuto.map( lambda f:Row(features=f))
autoDf = sqlContext.createDataFrame(autoRows)
autoDf.select("features").show(10)
from pyspark.ml.clustering import KMeans
kmeans = KMeans(k=3, seed=1)
model = kmeans.fit(autoDf)
predictions = model.transform(autoDf)
predictions.collect()
#Plot the results in a scatter plot
import pandas as pd
def unstripData(instr) :
return ( instr["prediction"], instr["features"][0], \
instr["features"][1],instr["features"][2],instr["features"][3])
unstripped=predictions.map(unstripData)
predList=unstripped.collect()
predPd = pd.DataFrame(predList)
import matplotlib.pylab as plt
plt.cla()
plt.scatter(predPd[3],predPd[4], c=predPd[0])
|
c21e3de892f3b3de13635a7e60678a5d09d03c8e | lixiang2017/leetcode | /problems/0003.0_Longest_Substring_Without_Repeating_Characters.py | 2,118 | 3.78125 | 4 | '''
two pointers / sliding window
T: O(N)
S: O(26 + 26 + 10 + 1) = O(1)
Runtime: 112 ms, faster than 38.09% of Python3 online submissions for Longest Substring Without Repeating Characters.
Memory Usage: 14 MB, less than 49.19% of Python3 online submissions for Longest Substring Without Repeating Characters.
'''
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
seen = set()
n = len(s)
ans = 0
i = j = 0
while j < n:
if s[j] not in seen:
seen.add(s[j])
ans = max(ans, j - i + 1)
j += 1
else:
while i < j and s[j] in seen:
seen.remove(s[i])
i += 1
return ans
'''
no use for i < j
Runtime: 100 ms, faster than 46.88% of Python3 online submissions for Longest Substring Without Repeating Characters.
Memory Usage: 14.1 MB, less than 49.19% of Python3 online submissions for Longest Substring Without Repeating Characters.
'''
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
seen = set()
n = len(s)
ans = 0
i = j = 0
while j < n:
if s[j] not in seen:
seen.add(s[j])
ans = max(ans, j - i + 1)
j += 1
else:
while s[j] in seen:
seen.remove(s[i])
i += 1
return ans
'''
just one while
Runtime: 66 ms, faster than 85.44% of Python3 online submissions for Longest Substring Without Repeating Characters.
Memory Usage: 14 MB, less than 93.04% of Python3 online submissions for Longest Substring Without Repeating Characters.
'''
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
seen = set()
n = len(s)
ans = 0
i = j = 0
while j < n:
if s[j] not in seen:
seen.add(s[j])
ans = max(ans, j - i + 1)
j += 1
else:
seen.remove(s[i])
i += 1
return ans
|
92e38e84ce3eec08256ecaeb1db2d5cfedc3a6f9 | rubyway/lintcode-python | /最大连续乘积子数组.py | 716 | 3.703125 | 4 | def maxlist(aList):
maxMul = aList[0]
for i in xrange(len(aList)):
temp = 1
for j in xrange(i, len(aList)):
temp *= aList[j]
if temp > maxMul:
maxMul = temp
return maxMul
a = [-2.5, 4, 0, 3, 0.5, 8, -1]
print maxlist(a)
def newMaxMul(aList):
maxend = aList[0]
minend = aList[0]
maxResult = aList[0]
for i in xrange(1, len(aList)):
end1 = maxend* a[i]
end2 = minend* a[i]
maxend = max(max(end1, end2), a[i])
minend = min(min(end1, end2), a[i])
maxResult = max(maxResult, maxend)
return maxResult
a = [-2.5, 4, 0, 3, 0.5, 8, -1]
print newMaxMul(a)
|
b2b7153ac65ffea4d3dde5da19e45945a2048b3f | Electron847/MasterFile | /IntroToProgramming/seth_weber_hw3_extra_credit.py | 603 | 3.953125 | 4 | numbers = [76, 93, 3, 35, 30, 74, 8, 27, 19, 96, 33, 16, 16, 56, 98, 28, 19, 14, 63, 53, 2, 60, 4, 93, 61,
3, 56, 31, 25, 74]
x=numbers
y=[]
a=[]
print('Welcome')
print('Would you like to count the odd numbers (type 1), or count the even numbers (type 2)?')
x=eval(input('Enter 1 or 2 here: '))
if x==1:
for num in numbers:
if num%2==1:
y.append(num)
print('There are ', len(y), 'odd numbers in the list')
if x==2:
for num in numbers:
if num%2==0:
a.append(num)
print('There are', len(a), 'even numbers in the list')
|
2f1aeeeec6e89c21ab1f82d9fed1f72f8f772878 | bholaa72429/01_Maths_HW_Assign | /00_MHC_base_v10.py | 9,848 | 3.953125 | 4 | # import statement
import pandas
import operator
# ********** Function Area **********
# checks units, accepts cm, mm, m, question repeated if user response invalid
def num_check(question,error,int_error,value,place):
valid = False
while not valid:
try:
if place == "integer" :
number = int(input(question))
else:
number = float(input(question))
#comparing number >= value-0 for decimal place and 1 for Number check
if operator.__ge__(number,value):
return number
else:
deci_place_value = ""
print(int_error)
except ValueError:
deci_place_value = ""
print(error)
def checker(question,list_ch,error):
valid = False
while not valid:
# ask question and put response in lowercase
# answer = answer of the user
answer = input(question).lower()
# check if input any space
response = answer.replace(" ","")
for var_item in list_ch:
if response == var_item:
return response
elif response == var_item[0]:
return var_item
print(error)
#Function to check the string
def string_check(choice, options):
is_valid = "yes"
chosen = ""
for var_list in options:
# if the shape is in one of the lists, return the full
if choice in var_list:
# Get full name of shape abd put it in title case so it looks nice when outputted
chosen = var_list[0].title()
is_valid = "yes"
break
# if the chosen option is not valid, set is_valid to no
else:
is_valid = "no"
# if the snack is not OK - ask question again.
if is_valid == "yes":
return chosen
else:
return "invalid choice"
# Function get shape
def get_shape():
# llist of valid shape inputs <full name, letter code (a -e)
# , and possible abbreviations etc>
valid_shape = [
["circle", "c","ci", "cir", "a"],
["rectangle", "r","re", "rec", "tangle", "b"],
["square", "s","sq", "squ", "squa", "c"],
["triangle", "t","tr", "tri","d"],]
# holds shape order for a single user.
wanted_shape = ""
while wanted_shape !="xxx":
# ask user for desired shape and put it in lowercase
print()
wanted_shape = input("Enter Shape: ").lower()
# remove white space around shapes
wanted_shape = wanted_shape.strip()
# check if shape is valid
shape_choice = string_check(wanted_shape,valid_shape)
if shape_choice == "invalid choice":
print(" Please enter a valid Shape Option ")
# check that shape is not the exit code before adding
if shape_choice != "xxx" and shape_choice != "invalid choice":
return shape_choice
# Function for Rectangle
def rectangle_ap(side_one,side_two):
# get the two input of the side
side_one = num_check(side_one,"Whoops! Please enter an integer ","ohh! Please enter an number more than zero",1,"float")
side_two = num_check(side_two,"Whoops! Please enter an integer ","ohh! Please enter an number more than zero",1,"float")
# calculate area and perimeter of rectangle
area = side_one*side_two
peri = 2*(side_one+side_two)
# adding dimensions of the shape to the list
given_data = "|Length: {}| Width: {} |".format(side_one, side_two)
dimensions.append(given_data)
return area, peri
def circle_area_peri(ans):
valid = False
error = "Whoops! Please enter an integer. "
int_error = "oops! Please enter an number more than zero. "
while not valid:
try:
enterd = ans
if enterd == "yes":
# get users input (radius)
radius = float(input("Please Enter Radius. "))
# if user has the diameter
else:
diameter = float(input("Please Enter Diameter. "))
# work out teh radius
radius = diameter / 2
# print("Calculating ...")
# check if its more than 0 nad then calculate
if radius > 0:
area = 3.14*radius*radius
peri = 2 * 3.14 * radius
# adding dimensions of the shape to the list
given_data = "|Radius: {} |".format(radius)
dimensions.append(given_data)
return area, peri
# if not more than zero show error
else:
print()
print(int_error)
radius = ""
# If integer is not entered, show error
except ValueError:
print(error)
def square_ap(side_one):
# get the two input of the side
side_one = num_check(side_one,"Whoops! Please enter an integer ","ohh! Please enter an number more than zero",1,"float")
# calculate area and perimeter of rectangle
area = side_one*side_one
peri = 4*side_one
# adding dimensions of the shape to the list
given_data = "|Side: {} |".format(side_one)
dimensions.append(given_data)
return area, peri
def triangle_ap(side1,side2,base1):
# inputs of the three sides
valid = False
error = "Invalid Input: Make Sure sum of two sides of triangle > Base of the triangle"
print()
while not valid:
try:
side_1 = num_check(side1,"Whoops! Please enter an integer ","ohh! Please enter an number more than zero",1,"float")
side_2 = num_check(side2,"Whoops! Please enter an integer ","ohh! Please enter an number more than zero",1,"float")
base = num_check(base1,"Whoops! Please enter an integer ","ohh! Please enter an number more than zero",1,"float")
# calculating perimeter
peri = side_1+side_2+base
# heron's law
# using peri(p)to calculate area
p = peri/2
area_squared = (p*(p-side_1)*(p-side_2)*(p-base))
if area_squared <= 0:
print("Oops!! This is not possible")
print()
continue
else:
area = (p*(p-side_1)*(p-side_2)*(p-base))**0.5
# adding dimensions of the shape to the list
given_data = "|Side: {} |Side: {} |Base: {} |".format(side_1, side_2,base)
dimensions.append(given_data)
return area, peri
except TypeError:
side_1 = ""
side_2 = ""
base = ""
print(error)
# ********** -Main Routine- **********
# Ask the user if they have used the program before & show instruction if required
# Loop to get ' shapes' input
# Set up dictionaries / lists needed to hold data
all_shapes = []
dimensions =[]
all_area = []
all_peri = []
area_peri_dict = {
"Shape": all_shapes,
"Given Dimensions":dimensions,
"Area": all_area,
"Perimeter": all_peri
}
to_check = ["yes", "no"]
to_check1 = ["m", "cm", "meter","centimeter","mm","inches"]
#decimal place option
round_place = int(num_check("Enter the number of Decimal Place ",
"Whoops! Please enter an integer","Opps! Please enter an number more than or equal to zero",0,"integer"))
unit_1 = checker("Please Enter the UNIT of the measurement",to_check1,"Please Enter a Valid unit like mm / cm / m / inch")
keep_going = ""
while keep_going == "":
# Set up dictionaries / lists needed to hold data
# Start of Shape Calculation Loop
# checking if insert shape by user is verified
# --- and calculate the Area & Perimeter according to that
insert_shape = get_shape()
print(insert_shape)
# --- Calculate the Area & Perimeter
if insert_shape == "Rectangle":
# asking for the the sides
area_1, peri_1 = rectangle_ap("Please Enter Length of the rectangle ",
"Please enter width of the rectangle")
# if circle
elif insert_shape == "Circle":
# Asking about the radius of the circle
rad_dia = checker("Do you have Radius of the Circle ? ",to_check,"Please Answer (yes / no). ")
area_1, peri_1 = circle_area_peri(rad_dia)
# if square
elif insert_shape == "Square":
area_1, peri_1 = square_ap("Please Enter side of the square ")
# if triangle
else:
area_1, peri_1 = triangle_ap("Please Enter first side of triangle",
"Please Enter second side of triangle",
"Please Enter the base of triangle")
# print calculations
if round_place == 0:
area = int(area_1)
peri = int(peri_1)
else:
area = round(area_1, round_place)
peri = round(peri_1, round_place)
print("Calculating...")
print("Area of {} is {} sq {} " .format(insert_shape, area, unit_1))
print("Perimeter of {} is {} {}".format(insert_shape, peri, unit_1))
area_unit = "{} sq{}".format(area,unit_1)
peri_unit = "{} {}".format(peri,unit_1)
# adding the items to the lists
all_shapes.append(insert_shape)
all_area.append(area_unit)
all_peri.append(peri_unit)
# print(all_shapes,all_area,all_peri) # trial purpose to see what is adding into list
keep_going = input("Press <enter> to calculate more or any key to quit")
# ********** Printing Area **********
# The summary of shapes and their calculations
# print details
print()
print("**** Calculation Summary ****")
print()
# # Set up columns to be printed...
# pandas.set_option('display.max_columns', None)
calc_data_frame = pandas.DataFrame(area_peri_dict)
print(calc_data_frame)
#write dataframe to csv file
calc_data_frame.to_csv("AP_Calc.csv")
# End of Shape Calculation Loop
# farewell user at end of game.
print("Thank you")
|
5f7959f188b48f058c1c065c646a5f73e31f4c60 | graalumj/CS362_In-Class_Testing | /test_word_count.py | 708 | 3.84375 | 4 | # Word Count Unittest
# By: Jason Graalum
import unittest
import word_count
class test_wordcount(unittest.TestCase):
def test_true1(self):
self.assertEqual(word_count.count("To be or not to be"), 6)
def test_true2(self):
self.assertEqual(word_count.count(""), 0)
def test_true3(self):
self.assertEqual(word_count.count("Hello there"), 2)
def test_false1(self):
self.assertNotEqual(word_count.count("Hello"), 2)
def test_false2(self):
self.assertNotEqual(word_count.count("All the worlds a stage"), 6)
def test_false3(self):
self.assertNotEqual(word_count.count("Me Myself and I"), 3)
if __name__ == '__main__':
unittest.main()
|
fd6b76ca1a79628904c19f0861aef01323601023 | Daviswww/Toys | /Python Programming/EXC 031 - 7-1-0.py | 881 | 4.1875 | 4 | list2 = [5, 6, 7, 8]
print('(1):')
list1 = [1, 2, 3, 4]
list1.append(list2)
print("Append: ", list1)
list1 = [1, 2, 3, 4]
list1.extend(list2)
print('Extend', list1)
print('(2):')
list2 = ['t', 'e', 's', 't']
list1 = [1, 2, 3, 4]
list1.append(list2)
print("Append: ", list1)
list1 = [1, 2, 3, 4]
list1.extend('test')
print("Extend: ", list1)
print('(3):')
list2 = ['a', 'b', 'c']
list1 = [1, 2, 3, 4]
list1.append(list2)
print("Append: ", list1)
list1 = [1, 2, 3, 4]
list1.extend(list2)
print("Extend: ", list1)
print('(4):')
list2 = ['阿貓', '阿狗']
list1 = [1, 2, 3, 4]
list1.append(list2)
print("Append: ", list1)
list1 = [1, 2, 3, 4]
list1.extend(list2)
print("Extend: ", list1)
print('(5):')
list1 = [1, 2, 3, 4]
list1.append(0)
print("Append: ", list1)
list1 = [1, 2, 3, 4]
list1.extend(0)
print("Extend: ", list1)
|
0262a14f51d867207b6e8c0d458fd6a5b14cf5ae | hashrm/Learning-Python-3 | /Python Is Easy Assignments - Hash/03 If Statement/main.py | 1,333 | 4.46875 | 4 | """
Create a function that accepts 3 parameters and checks for equality between any two of them.
Your function should return True if 2 or more of the parameters are equal, and false is none of them are equal to any of the others.
# Extra Credits:
Modify your function so that strings can be compared to integers if they are equivalent.
For example, if the following values are passed to your function: 6,5,"5"
You should modify it so that it returns true instead of false.
# Hint:
there's a built in Python function called "int" that will help you convert strings to Integers.
"""
#function that accepts 3 parameters
def equality(x,y,z):
#converting strings to integers for extra credits.
a = int(x)
b = int(y)
c = int(z)
#comparing values whether any 2 or all 3 values match.
if a == b:
bool = True
print(bool)
elif a == c:
bool = True
print(bool)
elif b == a:
bool = True
print(bool)
elif b == c:
bool = True
print(bool)
elif c == a:
bool = True
print(bool)
elif c == b:
bool = True
print(bool)
elif a == b == c:
bool = True
print(bool)
else:
bool = False
print(bool)
#calling the function
function_call = equality(6,"5",5)
|
41b7bba94dd017ce7a75f9cf07bd09a130e74ff1 | bensonCode/tensonflowTest | /neuralNetwork/cnn.py | 3,671 | 3.53125 | 4 | # https://github.com/fchollet/keras/blob/master/examples/mnist_cnn.py
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
# 定義梯度下降批量
batch_size = 128
# 定義分類數量
num_classes = 10
# 定義訓練週期
epochs = 12
# 定義圖像寬、高
img_rows, img_cols = 28, 28
# 載入 MNIST 訓練資料
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 保留原始資料,供 cross tab function 使用
y_test_org = y_test
# channels_first: 色彩通道(R/G/B)資料(深度)放在第2維度,第3、4維度放置寬與高
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else: # channels_last: 色彩通道(R/G/B)資料(深度)放在第4維度,第2、3維度放置寬與高
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
# 轉換色彩 0~255 資料為 0~1
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
# y 值轉成 one-hot encoding
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
# 建立簡單的線性執行的模型
model = Sequential()
# 建立卷積層,filter=32,即 output space 的深度, Kernal Size: 3x3, activation function 採用 relu
model.add(Conv2D(32, kernel_size=(3, 3),
activation='relu',
input_shape=input_shape))
# 建立卷積層,filter=64,即 output size, Kernal Size: 3x3, activation function 採用 relu
model.add(Conv2D(64, (3, 3), activation='relu'))
# 建立池化層,池化大小=2x2,取最大值
model.add(MaxPooling2D(pool_size=(2, 2)))
# Dropout層隨機斷開輸入神經元,用於防止過度擬合,斷開比例:0.25
model.add(Dropout(0.25))
# Flatten層把多維的輸入一維化,常用在從卷積層到全連接層的過渡。
model.add(Flatten())
# 全連接層: 128個output
model.add(Dense(128, activation='relu'))
# Dropout層隨機斷開輸入神經元,用於防止過度擬合,斷開比例:0.5
model.add(Dropout(0.5))
# 使用 softmax activation function,將結果分類
model.add(Dense(num_classes, activation='softmax'))
# 編譯: 選擇損失函數、優化方法及成效衡量方式
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
# 進行訓練, 訓練過程會存在 train_history 變數中
train_history = model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test))
# 顯示損失函數、訓練成果(分數)
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# 計算『混淆矩陣』(Confusion Matrix),顯示測試集分類的正確及錯認總和數
import pandas as pd
predictions = model.predict_classes(x_test)
pd.crosstab(y_test_org, predictions, rownames=['實際值'], colnames=['預測值'])
# 模型結構存檔
from keras.models import model_from_json
json_string = model.to_json()
with open("cnn.config", "w") as text_file:
text_file.write(json_string)
# 模型訓練結果存檔
model.save_weights("cnn.weight")
|
64bbea2e01fc88e8bc422fc6474f5afa9cc1f0a7 | edu-athensoft/ceit4101python_student | /ceit_191116/py200111/output_1_format.py | 894 | 3.875 | 4 | """
output formatting
string format()
string template
"""
greeting = "Hello, Athens. How are you?"
# print(greeting)
greeting = "Hello, Helen. How are you?"
# print(greeting)
greeting = "Hello, Marie. How are you?"
# print(greeting)
greeting = "Hello, Cindy. How are you?"
# print(greeting)
# placeholder
name1 = 'Obama'
name2 = 'Helen'
name3 = 'Marie'
name4 = "Cindy"
greeting1 = "morning!"
greeting2 = "afternoon!"
greeting3 = "evening!"
print("Hello, {}! How are you?".format(name1))
print("Hello, {}! How are you?".format(name2))
print("Hello, {}! How are you?".format(name3))
print("Hello, {}! How are you?".format(name4))
print("Good {}, {}! Long time no see".format(greeting1, name1))
print("Good {}, {}! Long time no see".format(greeting2, name2))
print("Good {}, {}! Long time no see".format(greeting3, name3))
print("Good {}, {}! Long time no see".format(name3,greeting3))
|
31e98cdca36c16490b1bc25aaf0d7da9950a7c07 | Northwestern-CS348/assignment-3-part-2-uninformed-solvers-drewmyles15 | /student_code_game_masters.py | 13,959 | 3.65625 | 4 | from game_master import GameMaster
from read import *
from util import *
class TowerOfHanoiGame(GameMaster):
def __init__(self):
super().__init__()
def produceMovableQuery(self):
"""
See overridden parent class method for more information.
Returns:
A Fact object that could be used to query the currently available moves
"""
return parse_input('fact: (movable ?disk ?init ?target)')
def getGameState(self):
"""
Returns a representation of the game in the current state.
The output should be a Tuple of three Tuples. Each inner tuple should
represent a peg, and its content the disks on the peg. Disks
should be represented by integers, with the smallest disk
represented by 1, and the second smallest 2, etc.
Within each inner Tuple, the integers should be sorted in ascending order,
indicating the smallest disk stacked on top of the larger ones.
For example, the output should adopt the following format:
((1,2,5),(),(3, 4))
Returns:
A Tuple of Tuples that represent the game state
"""
### student code goes here
peg1_tuple = ()
peg1_list = []
ask1 = parse_input("fact: (on ?X peg1)")
answer = self.kb.kb_ask(ask1)
if answer != False:
for ans in answer.list_of_bindings:
disk = ans[0].bindings[0].constant.element.split('disk',1)[1]
peg1_list.append(disk)
peg1_list.sort()
for disk in peg1_list:
peg1_tuple = peg1_tuple + (int(disk),)
peg2_tuple = ()
peg2_list = []
ask2 = parse_input("fact: (on ?X peg2)")
answer2 = self.kb.kb_ask(ask2)
if answer2 != False:
for ans in answer2.list_of_bindings:
disk = ans[0].bindings[0].constant.element.split('disk',1)[1]
peg2_list.append(disk)
peg2_list.sort()
for disk in peg2_list:
peg2_tuple = peg2_tuple + (int(disk),)
#peg2_tuple = peg2_tuple.sort()
peg3_tuple = ()
peg3_list = []
ask3 = parse_input("fact: (on ?X peg3)")
answer3 = self.kb.kb_ask(ask3)
if answer3 != False:
for ans in answer3.list_of_bindings:
disk = ans[0].bindings[0].constant.element.split('disk',1)[1]
peg3_list.append(disk)
peg3_list.sort()
for disk in peg3_list:
peg3_tuple = peg3_tuple + (int(disk),)
#peg3_tuple = peg3_tuple.sort()
state_tuple = (peg1_tuple,peg2_tuple,peg3_tuple)
return state_tuple
def makeMove(self, movable_statement):
"""
Takes a MOVABLE statement and makes the corresponding move. This will
result in a change of the game state, and therefore requires updating
the KB in the Game Master.
The statement should come directly from the result of the MOVABLE query
issued to the KB, in the following format:
(movable disk1 peg1 peg3)
Args:
movable_statement: A Statement object that contains one of the currently viable moves
Returns:
None
"""
### Student code goes here
disk = movable_statement.terms[0].term.element
initial = movable_statement.terms[1].term.element
goal = movable_statement.terms[2].term.element
#### Add the disk to the new stack and remove the facts of it being on the old one
r1 = parse_input("fact: (on " + disk + " " + initial + ")")
self.kb.kb_retract(r1)
r2 = parse_input("fact: (isTopofStack " + disk + " " + initial + ")")
self.kb.kb_retract(r2)
stat1 = parse_input("fact: (on " + disk + " " + goal + ")")
self.kb.kb_assert(stat1)
stat2 = parse_input("fact: (isTopofStack " + disk + " " + goal + ")")
self.kb.kb_assert(stat2)
## Determine if any disks are on the initial peg
ask1 = parse_input("fact: (on ?X " + initial + ")")
answer = self.kb.kb_ask(ask1)
if answer == False: #If no disks are on the initial peg
empty_stat = parse_input("fact: (isempty " + initial + ")")
self.kb.kb_assert(empty_stat)
else:
disks_on_initial = []
for ans in answer.list_of_bindings:
disks_on_initial.append(int(ans[0].bindings[0].constant.element.split('disk',1)[1]))
ask_top = parse_input("fact: (isTopofStack ?X " + initial + ")")
top_ans = self.kb.kb_ask(ask_top)
disks_on_initial.sort()
if top_ans:
for ans in top_ans.list_of_bindings:
if int(ans[0].bindings[0].constant.element.split('disk',1)[1]) != disks_on_initial[0]:
retract = parse_input("fact: (isTopofStack " + ans[0].bindings[0].constant.element + " " + initial + ")")
self.kb.kb_retract(retract)
assert1 = parse_input("fact: (isTopofStack disk" + str(disks_on_initial[0]) + " " + initial + ")")
self.kb.kb_assert(assert1)
goal_ask = parse_input("fact: (on ?X " + goal + ")")
goal_answer = self.kb.kb_ask(goal_ask)
disks_on_goal = []
for ans in goal_answer.list_of_bindings:
disks_on_goal.append(int(ans[0].bindings[0].constant.element.split('disk',1)[1]))
ask_topg = parse_input("fact: (isTopofStack ?X " + goal + ")")
top_ansg = self.kb.kb_ask(ask_topg)
disks_on_goal.sort()
if top_ansg:
for ans in top_ansg.list_of_bindings:
if int(ans[0].bindings[0].constant.element.split('disk',1)[1]) != disks_on_goal[0]:
retract = parse_input("fact: (isTopofStack " + ans[0].bindings[0].constant.element + " " + goal + ")")
self.kb.kb_retract(retract)
ask2 = parse_input("fact: (isempty " + goal + ")")
answer2 = self.kb.kb_ask(ask2)
if answer2:
self.kb.kb_retract(ask2)
def reverseMove(self, movable_statement):
"""
See overridden parent class method for more information.
Args:
movable_statement: A Statement object that contains one of the previously viable moves
Returns:
None
"""
pred = movable_statement.predicate
sl = movable_statement.terms
newList = [pred, sl[0], sl[2], sl[1]]
self.makeMove(Statement(newList))
class Puzzle8Game(GameMaster):
def __init__(self):
super().__init__()
def produceMovableQuery(self):
"""
Create the Fact object that could be used to query
the KB of the presently available moves. This function
is called once per game.
Returns:
A Fact object that could be used to query the currently available moves
"""
return parse_input('fact: (movable ?piece ?initX ?initY ?targetX ?targetY)')
def getGameState(self):
"""
Returns a representation of the the game board in the current state.
The output should be a Tuple of Three Tuples. Each inner tuple should
represent a row of tiles on the board. Each tile should be represented
with an integer; the empty space should be represented with -1.
For example, the output should adopt the following format:
((1, 2, 3), (4, 5, 6), (7, 8, -1))
Returns:
A Tuple of Tuples that represent the game state
"""
### Student code goes here
#print(":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
row1_tuple = ()
row1_list = {}
ask1 = parse_input("fact: (on ?X ?Y pos1)")
answer1 = self.kb.kb_ask(ask1)
if answer1 != False:
for ans in answer1.list_of_bindings:
tile = ans[0].bindings[0].constant.element
if len(tile.split('tile',1)) > 1:
tile = int(tile.split('tile',1)[1])
else:
tile = -1
pos = (ans[0].bindings[1].constant.element).split('pos',1)[1]
row1_list[int(pos)] = tile
#print("ROW1: ", len(row1_list))
for i in range(len(row1_list)):
val = row1_list[i+1]
#print(val)
row1_tuple = row1_tuple + (val,)
row2_tuple = ()
row2_list = {}
ask2 = parse_input("fact: (on ?X ?Y pos2)")
answer2 = self.kb.kb_ask(ask2)
if answer2 != False:
for ans in answer2.list_of_bindings:
tile = ans[0].bindings[0].constant.element
if len(tile.split('tile',1)) > 1:
tile = int(tile.split('tile',1)[1])
else:
tile = -1
pos = (ans[0].bindings[1].constant.element).split('pos',1)[1]
row2_list[int(pos)] = tile
#print("ROW2: ", len(row2_list))
for i in range(len(row2_list)):
val = row2_list[i+1]
row2_tuple = row2_tuple + (val,)
row3_tuple = ()
row3_list = {}
ask3 = parse_input("fact: (on ?X ?Y pos3)")
answer3 = self.kb.kb_ask(ask3)
if answer3 != False:
for ans in answer3.list_of_bindings:
tile = ans[0].bindings[0].constant.element
if len(tile.split('tile',1)) > 1:
tile = int(tile.split('tile',1)[1])
else:
tile = -1
pos = (ans[0].bindings[1].constant.element).split('pos',1)[1]
row3_list[int(pos)] = tile
#print("ROW3: ", len(row3_list))
for i in range(len(row3_list)):
val = row3_list[i+1]
row3_tuple = row3_tuple + (val,)
#print("-----------------------------------------------------------------------------------------------")
state_tuple = (row1_tuple,row2_tuple,row3_tuple)
#print(state_tuple)
return state_tuple
def makeMove(self, movable_statement):
"""
Takes a MOVABLE statement and makes the corresponding move. This will
result in a change of the game state, and therefore requires updating
the KB in the Game Master.
The statement should come directly from the result of the MOVABLE query
issued to the KB, in the following format:
(movable tile3 pos1 pos3 pos2 pos3)
Args:
movable_statement: A Statement object that contains one of the currently viable moves
Returns:
None
"""
### Student code goes here
tile = movable_statement.terms[0].term.element
initialX = movable_statement.terms[1].term.element
initialY = movable_statement.terms[2].term.element
goalX = movable_statement.terms[3].term.element
goalY = movable_statement.terms[4].term.element
r1 = parse_input("fact: (on " + tile + " " + initialX + " " + initialY + ")")
self.kb.kb_retract(r1)
r2 = parse_input("fact: (on empty " + goalX + " " + goalY + ")")
self.kb.kb_retract(r2)
stat1 = parse_input("fact: (on " + tile + " " + goalX + " " + goalY + ")")
self.kb.kb_assert(stat1)
stat2 = parse_input("fact: (on empty " + initialX + " " + initialY + ")")
self.kb.kb_assert(stat2)
#for facts in self.kb.facts:
# print(facts.statement)
#print("\n\n")
##Need to handle adjacentTo
'''ask = parse_input("fact: (adjacentTo empty ?tile)")
answer = self.kb.kb_ask(ask)
empty_adj = []
if answer:
for ans in answer.list_of_bindings:
adjTile = ans[0].bindings[0].constant.element
if adjTile != tile:
rt = parse_input("fact: (adjacentTo empty " + adjTile + ")")
self.kb.kb_retract(rt)
#print("RMOVINGGGG")
#print(rt)
rt1 = parse_input("fact: (adjacentTo " + adjTile + " empty)")
self.kb.kb_retract(rt1)
empty_adj.append(adjTile) #All of empty's adjacent tiles'''
#for facts in self.kb.facts:
# print(facts.statement)
#print("::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
'''ask1 = parse_input("fact: (adjacentTo " + tile + " ?tile)")
answer1 = self.kb.kb_ask(ask1)
if answer1:
for ans in answer1.list_of_bindings:
adjTile = ans[0].bindings[0].constant.element
if adjTile != "empty":
stat = parse_input("fact: (adjacentTo empty " + adjTile + ")")
self.kb.kb_assert(stat)
radj1 = parse_input("fact: (adjacentTo " + tile + " " + adjTile + ")")
self.kb.kb_retract(radj1)
radj2 = parse_input("fact: (adjacentTo " + adjTile + " " + tile + ")")
self.kb.kb_retract(radj2)
for tiles in empty_adj:
stat = parse_input("fact: (adjacentTo " + tile + " " + tiles + ")")
self.kb.kb_assert(stat)'''
def reverseMove(self, movable_statement):
"""
See overridden parent class method for more information.
Args:
movable_statement: A Statement object that contains one of the previously viable moves
Returns:
None
"""
pred = movable_statement.predicate
sl = movable_statement.terms
newList = [pred, sl[0], sl[3], sl[4], sl[1], sl[2]]
self.makeMove(Statement(newList))
|
93d8d5661e0064a14f6bc1a1d29949c7ab30991a | bingo957/MyStudyProject | /MyProjects/workspace/甲鱼Class/lect22/power.py | 144 | 3.90625 | 4 | """
计算x的y次幂
"""
def power(x, y):
if y == 1:
return x
else:
return power(x, y - 1) * x
print(power(2, 10))
|
d503b867ca704df3ad0f37b50f097f781a115aec | lifez/bahttext | /test_bahttext.py | 5,702 | 3.53125 | 4 | # -*- coding: utf-8 -*-
# Convert float decimal number to Thai text number
# Copyright (C) 2014, Morange Solution Co.,LTD.
# This file is distributed under the same license as the bahttext package.
# All rights reserved.
# Seksan Poltree <[email protected]>, 2014.
import unittest
from bahttext import bahttext
class TestBahtText(unittest.TestCase):
def test_input_is_a_number_then_can_convert_to_string(self):
self.assertIsInstance(bahttext(1.0), str)
def test_input_is_not_number_then_raise_error(self):
with self.assertRaises(TypeError) as ex:
bahttext('text input')
self.assertIsInstance(ex.exception, TypeError)
def test_input_integer_one_digit_can_convert(self):
self.assertEqual(bahttext(0.0), 'ศูนย์บาทถ้วน')
self.assertEqual(bahttext(1.0), 'หนึ่งบาทถ้วน')
self.assertEqual(bahttext(2.0), 'สองบาทถ้วน')
self.assertEqual(bahttext(5.0), 'ห้าบาทถ้วน')
def test_number_in_multiple_could_show_sip(self):
self.assertEqual(bahttext(10.0), 'สิบบาทถ้วน')
self.assertEqual(bahttext(20.0), 'ยี่สิบบาทถ้วน')
self.assertEqual(bahttext(50.0), 'ห้าสิบบาทถ้วน')
self.assertEqual(bahttext(11.0), 'สิบเอ็ดบาทถ้วน')
self.assertEqual(bahttext(15.0), 'สิบห้าบาทถ้วน')
def test_input_one_integer_wth_decimal_can_convert(self):
self.assertEqual(bahttext(1.10), 'หนึ่งบาทสิบสตางค์')
self.assertEqual(bahttext(2.50), 'สองบาทห้าสิบสตางค์')
self.assertEqual(bahttext(3.75), 'สามบาทเจ็ดสิบห้าสตางค์')
def test_number_ending_with_one_could_show_edd(self):
self.assertEqual(bahttext(4.81), 'สี่บาทแปดสิบเอ็ดสตางค์')
def test_number_start_with_two_could_show_yee(self):
self.assertEqual(bahttext(2.21), 'สองบาทยี่สิบเอ็ดสตางค์')
def test_number_hundred_should_show_roi(self):
self.assertEqual(bahttext(100.0), 'หนึ่งร้อยบาทถ้วน')
self.assertEqual(bahttext(101.0), 'หนึ่งร้อยเอ็ดบาทถ้วน')
self.assertEqual(bahttext(200.0), 'สองร้อยบาทถ้วน')
self.assertEqual(bahttext(201.0), 'สองร้อยเอ็ดบาทถ้วน')
def test_number_thousand_should_show_pan(self):
self.assertEqual(bahttext(1000.0), 'หนึ่งพันบาทถ้วน')
self.assertEqual(bahttext(2000.10), 'สองพันบาทสิบสตางค์')
self.assertEqual(
bahttext(3211.51), 'สามพันสองร้อยสิบเอ็ดบาทห้าสิบเอ็ดสตางค์')
self.assertEqual(bahttext(8000.31), 'แปดพันบาทสามสิบเอ็ดสตางค์')
def test_number_ten_thousand_should_show_muern(self):
self.assertEqual(bahttext(30000.0), 'สามหมื่นบาทถ้วน')
self.assertEqual(
bahttext(98765.10), 'เก้าหมื่นแปดพันเจ็ดร้อยหกสิบห้าบาทสิบสตางค์')
self.assertEqual(
bahttext(30211.21), 'สามหมื่นสองร้อยสิบเอ็ดบาทยี่สิบเอ็ดสตางค์')
def test_number_hundred_thousand_should_show_saan(self):
self.assertEqual(bahttext(800000.0), 'แปดแสนบาทถ้วน')
self.assertEqual(
bahttext(258065.81), 'สองแสนห้าหมื่นแปดพันหกสิบห้าบาทแปดสิบเอ็ดสตางค์')
def test_number_million_should_show_laan(self):
self.assertEqual(bahttext(3500000.0), 'สามล้านห้าแสนบาทถ้วน')
def test_number_multiple_million_should_show_multiple_laan(self):
self.assertEqual(bahttext(12000000.0), 'สิบสองล้านบาทถ้วน')
self.assertEqual(bahttext(21000000.0), 'ยี่สิบเอ็ดล้านบาทถ้วน')
self.assertEqual(
bahttext(51000000000000.51), 'ห้าสิบเอ็ดล้านล้านบาทห้าสิบเอ็ดสตางค์')
self.assertEqual(
bahttext(10000000680000.51), 'สิบล้านล้านหกแสนแปดหมื่นบาทห้าสิบเอ็ดสตางค์')
def test_negative_minus_prefix_number_should_print_loub(self):
self.assertEqual(bahttext(-1.10), 'ลบหนึ่งบาทสิบสตางค์')
self.assertEqual(bahttext(-1000.0), 'ลบหนึ่งพันบาทถ้วน')
self.assertEqual(
bahttext(-258065.81), 'ลบสองแสนห้าหมื่นแปดพันหกสิบห้าบาทแปดสิบเอ็ดสตางค์'
)
def test_fraction_number_should_not_have_tuan(self):
self.assertEqual(bahttext(12000000.0), 'สิบสองล้านบาทถ้วน')
self.assertNotEqual(bahttext(12000000.0), 'สิบสองล้านบาทสตางค์')
if __name__ == '__main__':
unittest.main()
|
b33d74155fa553207d4b7bee21c1974a84ad90b0 | cybelewang/leetcode-python | /code301RemoveInvalidParentheses.py | 6,158 | 3.90625 | 4 | """
301 Remove Invalid Parentheses
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
Note: The input string may contain letters other than the parentheses ( and ).
Examples:
"()())()" -> ["()()()", "(())()"]
"(a)())()" -> ["(a)()()", "(a())()"]
")(" -> [""]
"""
class Solution:
# Best OJ solution, see explanations at the end
def removeInvalidParentheses(self, s):
"""
:type s: str
:rtype: List[str]
"""
def remove(s, res, last_i, last_j, par):
diff = 0 # difference between par[0] and par[1]
for i in range(last_i, len(s)):
if s[i] == par[0]:
diff += 1
if s[i] == par[1]:
diff -= 1
# any time we see extra par[1] in i, we remove all possible par[1] in position (<=i)
if diff < 0:
for j in range(last_j, i + 1):
if s[j] == par[1] and (j == last_j or s[j-1] != par[1]):
remove(s[:j]+s[j+1:], res, i, j, par)
# must return now because s has extra par[1] so we need to bypass the below code
break
else:
# the below code will be run if diff >= 0 for the whole range of i
# reverse s and remove extra '(', the above code removed extra ')'
reversed = s[::-1]
if par[0] == '(':
remove(reversed, res, 0, 0, [')','('])
else:
res.append(reversed)
# main
res = []
remove(s, res, 0, 0, ['(', ')'])
return res
# https://www.cnblogs.com/grandyang/p/4944875.html
# DFS, track numbers of extra '(' and ')'
# remove all possible extras, easier to understand
def removeInvalidParentheses2(self, s):
"""
:type s: str
:rtype: List[str]
"""
def isValid(s):
count = 0
for c in s:
if c == '(':
count += 1
elif c == ')':
if count == 0:
return False
else:
count -= 1
return count == 0
def helper(s, start, cnt1, cnt2, res):
if cnt1 == 0 and cnt2 == 0:
if isValid(s):
res.append(s)
return
for i in range(start, len(s)):
if i != start and s[i] == s[i-1]: # negnect continuous same character from the second one, such as '(((' and ')))', we only process the first '(' or ')', same trick as permutations with duplicates
continue
if cnt1 > 0 and s[i] == '(':
helper(s[:i] + s[i+1:], i, cnt1 - 1, cnt2, res)
if cnt2 > 0 and s[i] == ')':
helper(s[:i] + s[i+1:], i, cnt1, cnt2 - 1, res)
# main
# cnt1 : number of extra '('
# cnt2 : number of extra ')'
cnt1, cnt2 = 0, 0
for c in s:
if c == '(':
cnt1 += 1
if c == ')':
if cnt1 == 0:
cnt2 += 1
else:
cnt1 -= 1
res = []
helper(s, 0, cnt1, cnt2, res)
return res
test_case = ')('
obj = Solution()
print(obj.removeInvalidParentheses2(test_case))
"""
https://leetcode.com/problems/remove-invalid-parentheses/discuss/75027/Easy-Short-Concise-and-Fast-Java-DFS-3-ms-solution
Key Points:
Generate unique answer once and only once, do not rely on Set.
Do not need preprocess.
Runtime 3 ms.
Explanation:
We all know how to check a string of parentheses is valid using a stack. Or even simpler use a counter.
The counter will increase when it is ‘(‘ and decrease when it is ‘)’. Whenever the counter is negative, we have more ‘)’ than ‘(‘ in the prefix.
To make the prefix valid, we need to remove a ‘)’. The problem is: which one? The answer is any one in the prefix. However, if we remove any one, we will generate duplicate results, for example: s = ()), we can remove s[1] or s[2] but the result is the same (). Thus, we restrict ourself to remove the first ) in a series of concecutive )s.
After the removal, the prefix is then valid. We then call the function recursively to solve the rest of the string. However, we need to keep another information: the last removal position. If we do not have this position, we will generate duplicate by removing two ‘)’ in two steps only with a different order.
For this, we keep tracking the last removal position and only remove ‘)’ after that.
Now one may ask. What about ‘(‘? What if s = ‘(()(()’ in which we need remove ‘(‘?
The answer is: do the same from right to left.
However a cleverer idea is: reverse the string and reuse the code!
Here is the final implement in Java.
Java
public List<String> removeInvalidParentheses(String s) {
List<String> ans = new ArrayList<>();
remove(s, ans, 0, 0, new char[]{'(', ')'});
return ans;
}
public void remove(String s, List<String> ans, int last_i, int last_j, char[] par) {
for (int stack = 0, i = last_i; i < s.length(); ++i) {
if (s.charAt(i) == par[0]) stack++;
if (s.charAt(i) == par[1]) stack--;
if (stack >= 0) continue;
for (int j = last_j; j <= i; ++j)
if (s.charAt(j) == par[1] && (j == last_j || s.charAt(j - 1) != par[1]))
remove(s.substring(0, j) + s.substring(j + 1, s.length()), ans, i, j, par);
return;
}
String reversed = new StringBuilder(s).reverse().toString();
if (par[0] == '(') // finished left to right
remove(reversed, ans, 0, 0, new char[]{')', '('});
else // finished right to left
ans.add(reversed);
}
""" |
1fa1f0f1addfc3dfca0f0a9c5d6417ef214026de | sava666/savyakPI3 | /lab62.py | 478 | 3.671875 | 4 | #python3
# coding=utf-8
import sys
import math
import random
year = int(input('Enter number of years you want to wait (years) '))
sumget = int(input('Enter sum what you have (UAH) '))
proc = float(input('Enter rate what you want (%) '))
proc = (proc/100)
def banc(sumget, proc, year):
count = 0
while year > count :
sumget = sumget+sumget*proc
count=count + 1
sumall= round (sumget,2)
return sumall;
print('You will have ' + str(banc(sumget, proc, year)) + ' UAH')
|
50baac72d16f1c34dd8f303a2703a733a3338fe0 | Mounika2010/20186099_CSPP-1 | /cspp1-practice/sample-assignment/Practice_problems/Same first digit/Solution.py | 355 | 3.734375 | 4 | def same_first_digit(x, y):
'''
return True, if first digit in both the numbers are equal
otherwise return False
'''
temp1 = str(abs(x))
temp2 = str(abs(y))
i=0
if temp1[i] == temp2[i]:
return True
return False
def main():
x = int(input())
y = int(input())
print(same_first_digit(x,y))
main() |
f58f0ddb5d03c5ddee50bb40f0fb3e384c585bac | GWSzeto/code_Qs | /WordPattern.py | 726 | 3.859375 | 4 | def wordPattern(pattern, str):
pattern_map = {}
word_map = {}
words = str.split(" ")
if not len(words) == len(pattern):
return False
for i in range(len(words)):
if pattern[i] not in pattern_map:
pattern_map[pattern[i]] = words[i]
if not pattern_map[pattern[i]] == words[i]:
return False
if words[i] not in word_map:
word_map[words[i]] = pattern[i]
if not word_map[words[i]] == pattern[i]:
return False
return True
print(wordPattern("abba", "dog cat cat dog"))
print(wordPattern("abba", "dog cat cat fish"))
print(wordPattern("aaaa", "dog cat cat dog"))
print(wordPattern("abba", "dog dog dog dog"))
|
78c508c90b618449bdf697e924e04399fd046387 | jcolaso/Python-For-Data-Science | /Codes and Data/Codes/Data Manipulation.py | 5,286 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 04 12:45:21 2016
@author: Gunnvant
"""
import pandas as pd
from pandas import DataFrame,Series
import numpy as np
import os
os.chdir('\')
data=pd.read_csv('oj.csv')
print data.head()
print data.shape
print type(data['brand'])
print type(data[['brand']])
print type(data.brand)
## Data Manipulation tasks:
# Filtering data
# Selecting columns
# Sorting data
# Adding new columns
# Group By aggregations
# Handling dates
# Handling text
# Merging dataframes
# Treating Missing Values
#### Filtering data
# Using logical subsets
# Using query to subset
# All rows corresponding to brand tropicana
FLT1= data[data.brand=='tropicana']
print FLT1.shape
# Multiple subsets: Or and AND conditions
FLT2=data.query("brand=='tropicana' or brand=='minute.maid'")
FLT2.shape
FLT3=data.query("brand=='tropicana' & feat==1")
print FLT3.head()
print FLT3.shape
FLT2=data[(data['brand']=='tropicana') | (data['brand']=='minute.maid') ]
FLT2.shape
#### Selecting Columns
# Selecting columns corresponding to brand and feat
SEL1=data[['brand','feat']]
SEL1.shape
#### Selecting Rows
# Selecting rows numbered 3,9,8
SEL2=data.ix[[3,9,8]]
SEL2.shape
#### Sorting data
SOR=data.sort_values('INCOME')
SOR.head()
SOR1=data.sort_values('INCOME',ascending=False)
SOR1.head()
SOR2=data.sort_values(['INCOME',"AGE60"],ascending=[False,True])
SOR2.head()
SOR3=data.sort_values(['brand','week'],ascending=[True,False])
SOR3.head()
#### Adding new columns to the data
#log of income
data=data.assign(log_inc=np.log(data.INCOME))
data['new_col']=np.log(data.HHLARGE)
data=data.assign(new_col1=np.log(data.INCOME),new_col2=np.log(data.INCOME))
#### Group by aggregations
# Grouping by one or more variable(s) and aggregating one column
# Grouping by one or more variable(s) and aggregating multiple columns in same way
# Grouping by one or more variable(s) and aggregating multiple columns differently
#Finding average price across brands
data.groupby('brand',as_index=False)['price'].mean()
#Finding average age, price across brands
data.groupby('brand',as_index=False)[['price','AGE60']].mean()
# Finding average age, total price across brands
data.groupby('brand',as_index=False).agg({'price':np.sum,'AGE60':np.mean}).rename(columns={'price':'Mean_price','AGE60':'Total_Age'})
# What if we want the names of new columns to be also changed
data.groupby('brand',as_index=False).agg({'price':{'Total_Price':np.sum},'AGE60':{'Mean_age':np.mean}})
a=data.groupby('brand',as_index=False).agg({'price':{'Total_Price':np.sum},'AGE60':{'Mean_age':np.mean}})
a.columns
# Finding average age, total price across brands and feature advertisements run
data.groupby(['brand','feat'],as_index=False).agg({'price':np.mean,'AGE60':np.sum}).rename(columns={'price':'Mean_price','AGE60':'Total_Age'})
###Window functions using transform
#Sorting data within group
data['logmove']=data.groupby('brand')['logmove'].transform(lambda x:x.sort_values(ascending=False))
data[['logmove','brand','price']].groupby('brand').head(5)
#### Handling dates
flt=pd.read_csv('Fd.csv')
print flt.dtypes
flt['FlightDate'].head(2)
flt['FlightDate']=pd.to_datetime(flt['FlightDate'],format="%d-%b-%y")
print flt.dtypes
m=flt.FlightDate.dt.month
m.head(2)
w=flt.FlightDate.dt.dayofweek #0=Monday,6=Sunday
print w.head(3)
#Generic Time classes in pandas
pd.to_datetime('15-06-16')
pd.Timestamp('15-06-16')
# Time stamps are different from time intervals
pd.to_datetime('15-06-16')-pd.to_datetime('14-06-16')
a=pd.to_datetime('15-06-16')-pd.to_datetime('14-06-16')
a/365
a/pd.to_timedelta(365,unit='D')
#If time interval is added to a timestamp we will get a future timestamp
pd.Timestamp('15-06-16')+pd.to_timedelta(365,unit='D')
#String manipulations
st=pd.read_csv("\")
print st.head()
st['Income_M'].mean()
st['Income_M']=st['Income_M'].str.replace("Rs","")
print st.head()
st['Income_M']=st['Income_M'].str.replace("/-","")
print st.head()
st['Income_M'].mean()
st.Income_M=st.Income_M.astype('float32')
st.Income_M.mean()
## Handling missing values
# Counting the number of missing values in each column
dat_m=pd.read_csv('\Credit.csv',na_values=['Missing',""])
# Number of missing values
dat_m.isnull().sum()
#Subsetting by missing values
dat_m[dat_m['MonthlyIncome'].isnull()]['DebtRatio']
#Replacing missing values
dat_m['age']=dat_m['age'].fillna(20)
## Joining data frames
dat1=data[['store','brand']]
dat2=data[['week','feat']]
pd.concat([dat1,dat2],axis=1)
dat3=dat1.ix[0:150]
dat4=dat1.ix[151:300]
pd.concat([dat3,dat4],axis=0)
pd.concat([dat3,dat4],axis=1)
## Merging DataFrames
df1=DataFrame({'CustomerID':[1,2,3,4,5,6],'Product':['Toaster','Toaster','Toaster','Radio','Radio','Radio']})
df2=DataFrame({'CustomerID':[2,4,6],'State':['Alabama','Alabama','Ohio']})
pd.merge(df1,df2,how='outer',on='CustomerID')
pd.merge(df1,df2,how='inner',on='CustomerID')
pd.merge(df1,df2,how='left',on='CustomerID')
pd.merge(df1,df2,how='right',on='CustomerID')
df1=DataFrame({'CustomerId':[1,2,3,4,5,6],'Product':['Toaster','Toaster','Toaster','Radio','Radio','Radio']})
df2=DataFrame({'CustomerID':[2,4,6],'State':['Alabama','Alabama','Ohio']})
pd.merge(df1,df2,how='inner',left_on='CustomerId',right_on='CustomerID').drop('CustomerID',axis=1)
|
17ec93843fe18dda15e740fab1895faad9810cfd | brianchiang-tw/leetcode | /No_0162_Find Peak Element/find_peak_element_by_binary_search.py | 1,872 | 4.09375 | 4 | '''
A peak element is an element that is greater than its neighbors.
Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that nums[-1] = nums[n] = -∞.
Example 1:
Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:
Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5
Explanation: Your function can return either index number 1 where the peak element is 2,
or index number 5 where the peak element is 6.
Note:
Your solution should be in logarithmic complexity.
'''
from typing import List
class Solution:
def helper(self, nums, left, right):
if left == right:
# base case:
return left
mid = ( left + right ) // 2
if nums[mid] > nums[mid+1]:
return self.helper(nums, left, mid)
else:
return self.helper(nums, mid+1, right)
def findPeakElement(self, nums: List[int]) -> int:
return self.helper( nums, 0 , len(nums)-1)
# n : the length of input nums
## Time Complexity: O( log n )
#
# The overhead in time is the cost of binary search, which is of O( log n )
## Space Complexity: O( log n)
#
# The overhead in space is to maintain call stack for recursion on binary search, which is of O( log n)
def test_bench():
test_data = [
[1,2,3,1],
[1,2,1,3,5,6,4],
[1]
]
# expected output:
'''
2
5
0
'''
for test_sequence in test_data:
print( Solution().findPeakElement(test_sequence) )
return
if __name__ == '__main__':
test_bench() |
54f169342b7e01ef6a07ed88f35b62f301f048b6 | janerleonardo/Python3CodigoFacilito | /funciones/asignarfuncion_variable.py | 300 | 3.53125 | 4 | """
Se puede asignar una funcion a variable de la siguiente manera se crea la variable y se igual a la funcion sin los
paretesis
"""
def centigrados_farhenheit(grados):
return grados * 1.8 +32
function_variable= centigrados_farhenheit
resultado = function_variable(32)
print(resultado) |
1675e657bf9c7faa1f126c72ea07a05e1866a298 | lqo202/assignment7 | /lqo202/script_as7.py | 1,478 | 3.59375 | 4 | """Program for question 1: Uses a Matrix class (which is a subclass or numpy) and calculates the arrays asked in Q1
The function used returns a list of arrays of the answers
"""
import numpy as np
import functools
__author__ = 'lqo202'
class ExceptionMatrix:
def __init__(self, msg):
self.msg = msg
class Matrix:
def __init__(self):
self._array = np.transpose(np.resize(np.arange(1, 15, 1), (3, 5)))
#This part of the code was modified from the original in stackoverflow#
def __getattr__(self, attributematrix):
try:
return getattr(self._array, attributematrix)
except AttributeError:
f = getattr(np, attributematrix, None)
if hasattr(f, '__call__'):
return functools.partial(f, self._array)
else:
raise AttributeError(attributematrix)
def obtainnewarrays(self):
arraysecondfourthrow = self._array[(1, 3), :]
arraysecondcolumn = self._array[:, 1]
arrayselection = self._array[1:-1, 0:]
arrayelements = self._array[(self._array>3) & (self._array<11)]
return [arraysecondfourthrow, arraysecondcolumn, arrayselection, arrayelements]
def __repr__(self):
newmatrix = ["%.2f" % x for x in Matrix.obtainnewarrays(self)]
for i in range(len(Matrix.obtainnewarrays(self))):
printstring = 'Result %s is ' %i + str(newmatrix[i])
print printstring
integ=Matrix()
|
514d39889e67c505d3260adee40f1e4f38a4c85f | Introduction-to-Programming-OSOWSKI/3-10-reversal-KatyMartin23 | /main.py | 143 | 3.96875 | 4 | def reversal(w):
word = ""
for i in range(len(w), 0, -1):
word = word + w[i-1]
return word
print(reversal("potato")) |
1ccc0da9cd5900f098153e5e3ccc663e1b92bacd | TheCrazyCoder28/HacktoberFest-Starter | /Python/TicTacToe.py | 5,721 | 4.15625 | 4 | # Write a python program to make a game called Tic Tac Toe.
import random
import time
name = input("\nWhat is your name? : ")
name = name.lower()
board_positions = [' ' for position in range(10)]
def InsertLetter(letter, position):
board_positions[position] = letter
def IsSpaceFree(position):
return board_positions[position] == ' '
def PrintBoard(board_positions):
print('\n | | ')
print(' ' + board_positions[1] + ' | ' + board_positions[2] + ' | ' + board_positions[3])
print(' | | ')
print('===========')
print(' | | ')
print(' ' + board_positions[4] + ' | ' + board_positions[5] + ' | ' + board_positions[6])
print(' | | ')
print('===========')
print(' | | ')
print(' ' + board_positions[7] + ' | ' + board_positions[8] + ' | ' + board_positions[9])
print(' | | ')
def IsBoardFull(board_positions):
if board_positions.count(' ') > 1:
return False
else:
return True
def IsWinner(board_positions, letter):
return ((board_positions[1] == letter and board_positions[2] == letter and board_positions[3] == letter) or
(board_positions[4] == letter and board_positions[5] == letter and board_positions[6] == letter) or
(board_positions[7] == letter and board_positions[8] == letter and board_positions[9] == letter) or
(board_positions[1] == letter and board_positions[4] == letter and board_positions[7] == letter) or
(board_positions[2] == letter and board_positions[5] == letter and board_positions[8] == letter) or
(board_positions[3] == letter and board_positions[6] == letter and board_positions[9] == letter) or
(board_positions[1] == letter and board_positions[5] == letter and board_positions[9] == letter) or
(board_positions[3] == letter and board_positions[5] == letter and board_positions[7] == letter))
def PlayerMove():
run = True
while run:
move = input("\nPlease select a position to enter the 'X' between 1 to 9 : ")
try:
move = int(move)
if 0 < move < 10:
if IsSpaceFree(move):
run = False
InsertLetter('X', move)
else:
print("\nWarning : Sorry, this space is occupied!")
else:
print("\nWarning : Please type a number between 1 and 9")
except:
print("\nNote : Please type a number!")
def ComputerMove():
possible_moves = [position for position, letter in enumerate(board_positions) if letter == ' ' and position != 0 ]
move = 0
for move_letter in ['O', 'X']:
for move_position in possible_moves:
positions_copy = board_positions[:]
positions_copy[move_position] = move_letter
if IsWinner(positions_copy, move_letter):
move = move_position
return move
open_corners = []
for possible_move in possible_moves:
if possible_move in [1, 3, 7, 9]:
open_corners.append(possible_move)
if len(open_corners) > 0:
move = SelectRandom(open_corners)
return move
if 5 in possible_moves:
move = 5
return move
open_edges = []
for possible_move in possible_moves:
if possible_move in [2, 4, 6, 8]:
open_edges.append(possible_move)
if len(open_edges) > 0:
move = SelectRandom(open_edges)
return move
def SelectRandom(letter):
letters_length = len(letter)
random_position = random.randrange(0, letters_length)
return letter[random_position]
def main():
time.sleep(2)
print("\n------------------------------")
print("\tWelcome to Tic Tac Toe")
print("------------------------------")
time.sleep(2)
PrintBoard(board_positions)
while not(IsBoardFull(board_positions)):
if not(IsWinner(board_positions, 'O')):
PlayerMove()
PrintBoard(board_positions)
else:
time.sleep(2)
print("\n-------------------------")
print("\tSorry, You loose!")
print("-------------------------")
break
if not(IsWinner(board_positions, 'X')) or IsBoardFull(board_positions):
move = ComputerMove()
if move == None:
print(" ")
else:
InsertLetter('O', move)
print("\nComputer placed an 'O' on position", move)
PrintBoard(board_positions)
else:
time.sleep(2)
print("\n----------------")
print("\tYou won!")
print("----------------")
break
if IsBoardFull(board_positions):
time.sleep(2)
print("\n------------------")
print("\tGame Tied!")
print("------------------")
def Starter():
time.sleep(1)
permission = input(f"\nHello {name}, Do you want to play Tic Tac Toe? ( Yes/No ) : ")
permission = permission.capitalize()
if permission == "Yes":
main()
elif permission == "No":
time.sleep(2)
print("\n----------------------")
print("\tOk, Good Luck!")
print("----------------------")
else:
time.sleep(2)
print("\n\"I think, you can't write the words correctly.\"")
Starter()
if __name__ == '__main__':
Starter()
while True:
time.sleep(4)
answer = input("\nIf you want to play again then press 'Y' or press any key to Quit : ")
answer = answer.capitalize()
if answer == "Y":
board_positions = [' ' for position in range(10)]
main()
else:
quit()
|
9f68e841d13da0f5b575e14dcea3821c6135a42b | Anish0494/BikeShare | /bikeshare_project_1.py | 6,991 | 4.3125 | 4 | import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
print("which city you want to look for chicago, new york city, washington?")
city=input()
city=city.lower()
if (city not in CITY_DATA):
print("OOPS!!!wrong input please try again")
get_filters()
# TO DO: get user input for month (all, january, february, ... , june)
print("which month do you want for data to get filter ")
month=input()
month=month.lower()
months = ['january', 'february', 'march', 'april', 'may', 'june']
if (month not in months):
print("OOPS!!!wrong input please try again")
get_filters()
# TO DO: get user input for day of week (all, monday, tuesday, ... sunday)
print("Which day of week you want to get data filter")
day=input()
day=day.lower()
week=['monday', 'tuesday', 'wednesday','thrusday','friday','saturday','sunday']
if(day not in week):
print("OOPS!!!wrong input please try again")
get_filters()
print('-'*40)
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
df=pd.DataFrame(pd.read_csv(CITY_DATA[city]))
df['Start Time']=pd.to_datetime(df['Start Time'])
df['month']=df['Start Time'].dt.month
df['day_of_week'] = df['Start Time'].dt.weekday_name
b=0
b=input('How would want to filter the data? enter both, month or days\n')
if(b.lower() == 'both' or b.lower() == 'month'):
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = months.index(month) + 1
df = df[df['month'] == month]
if (b.lower() == 'both' or b.lower() == 'days'):
df = df[df['day_of_week'] == day.title()]
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# TO DO: display the most common month
m=df['month'].mode()[0]
print("most common month(in numeric) is:-",m)
# TO DO: display the most common day of week
d=df['day_of_week'].mode()[0]
print("most common day of week is:-",d)
# TO DO: display the most common start hour
sh=df['Start Time'].dt.hour.mode()[0]
print("most popular start time:-",sh)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# TO DO: display most commonly used start station
print("Most commonly used start station:-",df['Start Station'].mode()[0])
# TO DO: display most commonly used end station
print("Most commonly used end station:-",df['End Station'].mode()[0])
# TO DO: display most frequent combination of start station and end station trip
l=df['Start Station']+df['End Station']
print("Most frequent combination of the start station and end station:-",l.mode()[0])
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# TO DO: display total travel time
print("Total travel time:-",df['Trip Duration'].sum())
# TO DO: display mean travel time
print("Mean travel Time:-",df['Trip Duration'].mean())
print("\nThis took %s seconds." % (time.time() - start_time))
print("-"*40)
start_time = time.time()
print("\nDisplaying more detail of subscriber and customer....\n")
s=df[df['User Type']=='Subscriber']
c=df[df['User Type']=='Customer']
st=s['Trip Duration'].sum()
ct=c['Trip Duration'].sum()
print("Total time travel by subscriber---",st)
print("Total time travel by customer---",ct)
print("Mean travel time by subscriber---",s['Trip Duration'].mean())
print("Mean travel time by customer--",c['Trip Duration'].mean())
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# TO DO: Display counts of user types
print("Displaying the type of the user-------\n")
print(df['User Type'].value_counts())
# TO DO: Display counts of gender
print("\nDisplaying the counts of gender----\n")
try:
print(df['Gender'].value_counts())
except KeyError:
print("No Gender data to display")
# TO DO: Display earliest, most recent, and most common year of birth
print("\nDisplaying the details about the birth year......\n")
try:
print("Most earliest year of birth:-",df['Birth Year'].min())
print("Most recent year of birth:-",df['Birth Year'].max())
print("Most common year of birth:-",df['Birth Year'].mode()[0])
except KeyError:
print("No birth data to display")
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def display(df):
a=input('\ndo you want to know the data of individual? enter yes or no\n')
if(a.lower() != 'no'):
h=0
while(True):
print(df[0+h:5+h])
cycle=input('do you want to stop displaying more data? enter yes or no\n')
if(cycle.lower() == 'yes'):
break
h+=5
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
display(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
80f39b99794219e3e722fe58c5e91d1632afb219 | MD-Levitan/cryptanalyst | /DiscreteLog/BSGS.py | 1,100 | 3.5 | 4 | # A baby-step giant-step
import math
def russian_peasant(x, y, z):
s = 1
while x > 0:
if x % 2 == 1:
s = (s*y) % z
x = x//2
y = (y*y) % z;
return int(s)
def egcd(a, b):
if a == 0:
return b, 0, 1
else:
g, x, y = egcd(b % a, a)
return g, y - (b // a) * x, x
def compute_m(p):
m = math.ceil(math.sqrt(p-1))
return m
def baby_list(g, p):
m = int(compute_m(p))
# b = list(range(0, m))
# s = map((lambda x: pow(g, x, p)), b) # create list of powers
# x = dict(zip(s, b)) # zip list of powers and positions into a dictionary
#
# Faster
x = dict()
pow_ = 1
for i in range(0, m):
x[pow_] = i
pow_ = pow_ * g % p
return x
def compare_giant(y, g, p):
if y == 1:
return 0
hash_table = baby_list(g, p)
m = int(compute_m(p))
_, inv, _ = egcd(g, p)
inv = inv % p
a = russian_peasant(m, inv, p)
z = y
for i in range(1, m):
z = (z * a) % p
if z in hash_table:
return i * m + hash_table[z]
|
43a3efcf6e2b9b206cf6cfc917e0d467ed629626 | jk990803/Python_Study_Plan | /Test100/Test17.py | 462 | 4.125 | 4 | # -*- coding:utf-8 -*-
# 题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符
# 的个数。
s = raw_input('input a string:\n ')
letters = 0
space =0
digit=0
others=0
for c in s:
if c.isdigit():
digit+=1
elif c.isalpha():
letters+=1
elif c.isspace():
space+=1
else:
others +=1
print 'char = %d,space = %d,digit = %d,others = %d' \
% (letters,space,digit,others) |
07ef259cda98d129c98ea23660267fda8efbc5df | xuelang201201/FluentPython | /08_对象引用、可变性和垃圾回收/fp_07_为一个包含另一个列表的列表做浅复制.py | 789 | 3.84375 | 4 | # http://www.pythontutor.com
l1 = [3, [66, 55, 44], (7, 8, 9)]
l2 = list(l1) # l2 是 l1 的浅复制副本。
l1.append(100) # 把 100 追加到 l1 中,对 l2 没有影响。
l1[1].remove(55) # 把内部列表 l1[1] 中的 55 删除。这对 l2 有影响,因为 l2[1] 绑定的列表与 l1[1] 是同一个。
print('l1:', l1)
print('l2:', l2)
# 对可变的对象来说,如 l2[1] 引用的列表,+= 运算符就地修改列表。这次修改在 l1[1] 中也有体现,因为它是 l2[1] 的别名。
l2[1] += [33, 22]
# 对元组来说,+= 运算符创建一个新元组,然后重新绑定给变量 l2[2]。这等同于 l2[2] = l2[2] + (10, 11)。
# 现在,l1 和 l2 中最后位置上的元组不是同一个对象。
l2[2] += (10, 11)
print('l1:', l1)
print('l2:', l2)
|
b4210ae728eea5e5a44e833f8eaa0762457cf9d5 | marshalloffutt/files_and_exceptions | /common_words.py | 726 | 4.15625 | 4 | def common_words(filename, word):
"""Count the number of times a specific word appears"""
try:
with open(filename, encoding='utf-8') as file_object:
contents = file_object.read()
except FileNotFoundError:
message = "Sorry, the file " + filename + " was not found."
print(message)
else:
# Count the number of times a specific word was used
count = contents.count(word.lower())
print("The word " + word + " appears " + str(count) + " times in this text.")
# Call common_words and pass it in the arguments
common_words('text_files/lorem.txt', 'ipsum')
common_words('text_files/lorem.txt', 'ridiculus')
common_words('text_files/lorem.txt', 'fringilla')
|
af5a8c855b5e55415004540bdcccdc2bd1e5a890 | iromeroh/c-tools | /dynamic_LCS/dynamic_lcs.py | 1,717 | 3.53125 | 4 | #!/usr/bin/env python
def naive_LCS_len(str1,str2,m,n):
#print "running "+str(m)+" | "+str(n) + "\n"
if m==0 or n ==0:
return 0
# if the last characters of str1 and str2 are the same, the LCS len has at least 1 plus the length of
# LCS of str1[0..m-1],str2[0..n-1]
if str1[m-1] == str2[n-1]:
return naive_LCS_len(str1, str2, m-1, n-1) +1
#if they are not the same, the LCS len is the biggest one of either
# LCS ( str1[0..m-1], str2[0..n] ) or LCS ( str1[0..m], str2[0..n-1] )
return max( naive_LCS_len(str1, str2, m-1, n), naive_LCS_len(str1, str2, m, n-1))
def LCS_len(str1,str2,m,n,lookup):
#print "running "+str(m)+" | "+str(n)
instance = str(m)+" | "+str(n)
if m==0 or n ==0:
return 0
if instance not in lookup:
# if the last characters of str1 and str2 are the same, the LCS len has at least 1 plus the length of
# LCS of str1[0..m-1],str2[0..n-1]
if str1[m-1] == str2[n-1]:
lookup[instance] = LCS_len(str1, str2, m-1, n-1, lookup) +1
#if they are not the same, the LCS len is the biggest one of either
# LCS ( str1[0..m-1], str2[0..n] ) or LCS ( str1[0..m], str2[0..n-1] )
else:
lookup[instance] = max( LCS_len(str1, str2, m-1, n, lookup), LCS_len(str1, str2, m, n-1, lookup))
return lookup[instance]
lookup = {}
s1 = "Anita lava la tina"
s2 = "Anita limpia muy bien la tina"
print "s1 is "+s1
print "s2 is "+s2
l = LCS_len(s1, s2, len(s1),len(s2), lookup)
print "Largest common string length of s1 and s2 is: "+str( l )
ln = naive_LCS_len(s1, s2, len(s1),len(s2))
print "Naively, the largest common string length of s1 and s2 is: "+str( ln )
|
1356c78b68e2b7cbab1be221e84fd72a94d7ea77 | Mar2ck/DotaPlayerPerformaceCalculator | /src/main.py | 7,812 | 3.671875 | 4 | #!/usr/bin/env python3
"""
Program Frontend - CLI/GUI Interface
"""
# Built-in modules
import argparse
# Local modules
import player_performance_score
import data_scraper
def DisplayMenuOptions():
options = ["Set up match", "List all players"] ##Always add new menu options here
for i in range(len(options)): ##Prints out all the options
print(str(i + 1) + ": " + options[i])
print("9: Quit\n") ##Always outputs quit as 9 // Make sure no more than 8 options!
def SetUpMatch():
menuChoice = ""
print ("Sorting all players...")
sortedPlayers = MergeSort(data_scraper.ListAllPlayerIDs()) ##Sorts all players by name
print ("Sorted " + str(len(data_scraper.ListAllPlayerIDs())) + " players total")
team1 = []
team2 = []
while (menuChoice != "9"):
if (len(team1) > 0): ##Only prints the teams if they have at least one player
print ("Team 1: ")
for i in team1:
print (data_scraper.DictPlayerInfo(i)["name"])
else:
print ("Team 1 is empty")
if (len(team2) > 0):
print ("Team 2: ")
for i in team2:
print (data_scraper.DictPlayerInfo(i)["name"])
else:
print("Team 2 is empty")
if (len(team1) > 0 and len(team2) > 0):
prob = player_performance_score.GetProbability(player_performance_score.TotalPPS(team1),player_performance_score.TotalPPS((team2))) ##Gets the probability of winning
print ("There is a " + str(prob * 100) + "% chance that team 1 will beat team 2")
print ("1: Add player to team 1")
print ("2: Add player to team 2")
print ("3: Remove player from team 1")
print ("4: Remove player from team 2")
print ("9: Quit\n")
try:
menuChoice = int(input("Select menu item: ")) ##Checks if the input is an int
except:
print("Please enter a suitable input")
else:
if (menuChoice == 9): ##Exits the loop
break
elif (menuChoice == 1): ##Add a player to team 1
temp = GetPlayer(sortedPlayers) ##Gets a player from the user
if (temp != -1): ##Checks if the player exists
if(len(team1) == 5): ##Checks if the team is full
print("Max amount of players have been added")
else:
if (nameChecker(temp, (team1 + team2)) == False): ##Checks if the player is already in use
team1.append(temp) ##Adds the player to team 1
else:
print (data_scraper.DictPlayerInfo(temp)["name"] + " is already in use")
else:
print("Player not found")
elif (menuChoice == 2):##Add a player to team 2
temp = GetPlayer(sortedPlayers)
if (temp != -1):
if(len(team2) == 5):
print("Max amount of players have been added")
else:
if (nameChecker(temp, (team1 + team2)) == False):
team2.append(temp)
else:
print (data_scraper.DictPlayerInfo(temp)["name"] + " is already in use")
else:
print("Player not found")
elif (menuChoice == 3):#Remove a player from team 1
if(len(team1) == 0): ##Checks if the team has players
print("Please enter a player before removing")
else:
removePlayer(team1) ##Removes the player from team 1
elif (menuChoice == 4): ##Remove a player from team 2
if(len(team2) == 0):
print("Please enter a player before removing")
else:
removePlayer(team2)
else:
print("Please enter a suitable input")
def removePlayer(team):
playerName = input("Please enter the player's name: ") ##Gets the user's input
counter = 0 ##Counts index
for player in team: ##Loops for each player
if data_scraper.DictPlayerInfo(player)["name"] == playerName: ##Checks if names match
print(data_scraper.DictPlayerInfo(player)["name"] + " has been removed")
del team[counter] ##Removes the player from the team
return
counter = counter + 1
print(playerName + " isn't found") ##Displays issue to user
def nameChecker(playerName, team):
if(len(team) == 0): ##Checks if the list is empty
return False
else:
for name in team: ##Checks all inputted names to see if it is there already
if (name == playerName):
return True
return False
def GetPlayer(allPlayers): ##Get player id from user's player selection
name = input("Please enter the player's name: ")
playerID = SearchPlayers(allPlayers, name)
return playerID
def SearchPlayers(array, item): ##Searches for a player based on name
mIndex = (len(array)) // 2 ##Finds the midpoint
if (len(array) == 1):
if (data_scraper.DictPlayerInfo(array[mIndex])["name"] == item):
return array[mIndex] ##Returns the player's ID
else:
return -1 ##-1 is returned if the player is not there
else:
if (data_scraper.DictPlayerInfo(array[mIndex])["name"] == item):
return array[mIndex] ##Returns the player's ID
else:
if (item < data_scraper.DictPlayerInfo(array[mIndex])["name"]): ##Checks if the item is less or more than the midpoint
return SearchPlayers(array[:mIndex], item)
else:
return SearchPlayers(array[mIndex:], item)
def OutputAllPlayers():
for x in data_scraper.ListAllPlayerIDs(): ##Loops through every player
print(data_scraper.DictPlayerInfo(x)["name"] + ": " + str(int(player_performance_score.playerPPS[x]))) ##Outputs the player's names
print()
def MergeSort(array): ##Sorts the array based on name
if (len(array) > 1): ##Checks if the array is split down to one player
mIndex = (len(array)) // 2 ##Finds the midpoint
left = array[:mIndex]
right = array[mIndex:]
MergeSort(left) ##Sorts the left half of the array
MergeSort(right) ##Sorts the right half of the array
i = 0
j = 0
k = 0
while i < len(left) and j < len(right): ##Checks if there are players in both lists
if (data_scraper.DictPlayerInfo(left[i])["name"] < data_scraper.DictPlayerInfo(right[j])["name"]): ##Compares the two players
array[k] = left[i] ##Adds the player to the sorted array
i += 1
else:
array[k] = right[j]
j += 1
k += 1
while i < len(left):
array[k] = left[i]
i += 1
k += 1
while j < len(right):
array[k] = right[j]
j += 1
k += 1
return array ##Returns the sorted array
#### Main ####
while True:
DisplayMenuOptions() ##Displays the main menu options
try:
menuChoice = int(input("Select main menu item: ")) ##Checks if the input is an integer
except ValueError:
print("Please enter a suitable input")
else: ##Always add new menu options here
if (menuChoice == 1):
SetUpMatch() ##Sets up a new match
elif (menuChoice == 2):
OutputAllPlayers() ##Lists all players
elif (menuChoice == 9):
break ##Exits the program
else: ##Checks if the input is an option
print("Please enter a suitable input")
print("Thanks for coming")
|
70b37934368233bbf85c71890d59cd65f994ddda | plum-umd/tech-plus-research-PBT | /ex3.py | 1,302 | 4.34375 | 4 | ''' Reverse a list.
E.g. reverse([1,2,3]) = [3,2,1]
Example property:
- reverse(reverse(l)) is equal to l
'''
def reverse(l):
if len(l) > 0:
return l[::-1]
''' Remove every occurrence of an element from a list.
E.g. remove(2,[1,2,3]) = [1,3]
Example property:
- the result of remove(x, l) does not contain x
'''
def remove(x, l):
if len(l) == 0:
return []
for i in range(len(l)):
if l[i] == x:
return l[:i] + l[(i+1):]
''' Insert an item into a sorted list.
E.g. insert(0,[1,2,3]) = [0,1,2,3]
Example properties:
- the result of insert(x, l) contains all the elements originally in l
- if l is sorted, then insert(x, l) is sorted
'''
def insert(x, l):
new_l = []
for i in range(len(l)):
if l[i] < x:
new_l.append(l[i])
else:
return [x] + l[i:]
return [x] + new_l
''' Remove adjacent duplicates from a list.
E.g. dedup([1,1,2,1,3,3]) = [1,2,1,3]
Example property:
- dedup(l) is the same as dedup(dedup(l))
'''
def dedup(l):
i = 0
new_l = []
for i in range(0, len(l), 2):
if l[i] == l[i+1]:
new_l.append(l[i])
else:
new_l.append(l[i])
new_l.append(l[i+1])
return new_l
|
945f91983196ffdd6d50b88bda15f00caf67c16a | YooGunWook/coding_test | /탐욕법/조이스틱.py | 1,378 | 3.625 | 4 | import string
'''
우선 위 아래는 간단하기 때문에 이 과정을 먼저 함수로 구현
그 다음 양옆으로 가는 것을 구현해야되는데, A의 여부에 따라 판단하면 좋을 듯 하다
'''
def count_alpha(alpha):
up = 0
down = 0
alpha_list = list(string.ascii_uppercase)[1:]
alpha_list_reverse = alpha_list[::-1]
if alpha == 'A':
return up
for alpha_up in alpha_list:
if alpha != alpha_up:
up += 1
if alpha == alpha_up:
up += 1
break
for alpha_down in alpha_list_reverse:
if alpha != alpha_down:
down += 1
if alpha == alpha_down:
down += 1
break
if up == down:
return up
if up > down:
return down
if up < down:
return up
def solution(name):
count = [count_alpha(i) for i in name]
answer = 0
where = 0
while True:
answer += count[where]
print(answer)
count[where] = 0
print(count)
if sum(count) == 0:
break
left = 1
right = 1
while count[where - left] <= 0:
left += 1
while count[where + right] <= 0:
right += 1
answer += left if left < right else right
where += -left if left < right else right
return answer
|
9f12682201ec27ebe49c335e6b5907b8cd0b720b | blakely4206/package_delivery_website | /graph.py | 1,153 | 3.671875 | 4 |
class Vertex(object):
def __init__(self, label):
self.label = label
def __str__(self):
return self.label
class Graph(object):
def __init__(self):
self.adj_list = {}
self.distances = {}
def load_graph(self, number_of_vertices):
for i in range(number_of_vertices):
self.add_vertex(Vertex(i))
def add_vertex(self, vertex: Vertex):
self.adj_list[vertex] = []
def insert_edge(self, vertex_A, vertex_B, dist):
self.distances[(vertex_A, vertex_B)] = dist
self.adj_list[vertex_A].append(vertex_B)
self.distances[(vertex_B, vertex_A)] = dist
self.adj_list[vertex_B].append(vertex_A)
def return_vertex(self, loc_id):
for v in self.adj_list:
if(v.label == loc_id):
return v
return None
def return_weight(self, vertex_A, vertex_B):
return self.distances[(vertex_A, vertex_B)]
def return_weight_with_id(self, id_A, id_B):
vertex_a = self.return_vertex(id_A)
vertex_b = self.return_vertex(id_B)
return self.distances[vertex_a, vertex_b] |
87b92583b498e4001e067625305fb40bd6c79286 | abhishek-jana/Leetcode-Solutions | /easy/268-Missing-Number.py | 605 | 4.0625 | 4 | '''
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
Example 1:
Input: [3,0,1]
Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
'''
class Solution:
def missingNumber(self, nums):
n = len(nums)
if (n*(n+1)/2 == sum(nums)):
return 0
else:
res = n*(n+1)/2 - sum(nums)
return int(res)
print (Solution().missingNumber([9,6,4,2,3,5,7,0,1]))
|
1a35670807d8fa529ad24032c82bae164714f9a9 | harishtm/learningpython | /coding_programs/ProblemSolving/subset_sum.py | 661 | 3.953125 | 4 | def subset_sum(numbers, target, partial=[]):
"""
# For product combination
if len(partial) == 2:
s = partial[0] * partial[1]
else:
s = 0
"""
s = sum(partial)
# check if the partial sum is equals to target
if s == target:
print("sum(%s)=%s" % (partial, target))
if s >= target:
return # if we reach the number why bother to continue
for i in range(len(numbers)):
n = numbers[i]
remaining = numbers[i+1:]
subset_sum(remaining, target, partial + [n])
if __name__ == "__main__":
# subset_sum(list(range(23, 34)), 957)
subset_sum(list(range(23, 34)), 77) |
9a7a68fbecc54af9e35d0ae07988a8315d2409e3 | natp75/homework_5 | /homework_7/homework_7_3.py | 2,385 | 3.65625 | 4 |
#Реализовать программу работы с органическими клетками, состоящими из ячеек.
#Необходимо создать класс Клетка.
#В его конструкторе инициализировать параметр, соответствующий количеству ячеек клетки (целое число).
#В классе должны быть реализованы методы перегрузки арифметических операторов:
# - сложение (__add__())
# - вычитание (__sub__())
# - умножение (__mul__())
# - деление (__truediv__()).
class Cell:
__count: int
def __init__(self, count: int):
assert count > 0, "Количество ячеек должно быть больше 0"
self.__count = count
def __add__(self, other: 'Cell'):
self.validate_item(other)
value = self.count + other.count
return Cell(value)
def __sub__(self, other: 'Cell'):
self.validate_item(other)
value = self.count - other.count
assert value > 0, "Разность ячеек меньше 0"
return Cell(value)
def __mul__(self, other: 'Cell'):
self.validate_item(other)
value = self.count * other.count
return Cell(value)
def __truediv__(self, other: 'Cell'):
self.validate_item(other)
value = round(self.count / self.count)
return Cell(value)
def __str__(self):
return str(self.__count)
def validate_item(self, other):
assert isinstance(other, self.__class__), "Операции допустимы только между клетками"
@property
def count(self) -> int:
return self.__count
@staticmethod
def make_order(cell_object: 'Cell', count_per_row: int) -> str:
items = '*' * cell_object.count
chunks = [
items[idx:idx + count_per_row]
for idx in range(0, len(items), count_per_row)
]
return '\n'.join(chunks)
first = Cell(3)
second = Cell(2)
huge = Cell(12)
print(first + second) # 3 + 2 = 5
print(first - second) # 3 - 2 = 1
print(first * second) # 3 * 2 = 6
print(first / second) # 3 / 2 = 1 (округление)
print(Cell.make_order(huge, 5))
|
e41314770c26fc8daa61d32e23e30776086abc90 | will-hossack/Python | /examples/optics/lens/RayAberrations.py | 592 | 3.96875 | 4 | """
Example program to plot the Ray Aberrations for a lens
Author: Will Hossack, The Unievsrity of Edinburgh
"""
import optics.lens as len
import optics.wavelength as wl
import matplotlib.pyplot as plt
import optics.wavefront as a
import math
import tio
def main():
# Get lens and other info
lens = len.DataBaseLens()
angle = math.radians(tio.getFloat("Angle in degrees"))
wave = tio.getFloat("Wavelength of plot",wl.Default)
wa = a.WaveFrontAnalysis(lens)
wa.drawAberrationPlot(angle,wave=wave,legend = "lower left")
plt.show()
main()
|
c93f756049b856974d76bbbd4de5b4130d138574 | GhalyaJohar/edge-project-2021 | /seats available.py | 1,462 | 4.09375 | 4 | # print("python project")
# #Day 1
# s#Hello, Welcome to S&G's cenima! Type Hey to see the available services!
# s# 1-List of movies + Age requirement
# s# 2-Ehtraz if vaccinated y if not vaccinated print "sorry you cannot access the cenima"
# s# 3-List of movie showtime (each movie printed with it's showtime)
# g# 4-if age >13 not allowed without parent quardian if age 18=< print please choose seat
# s# 5-list = available seats, row a n/ row n/
# s# 6-print the seat chosen (seat A3) (it will be deleted from the og list)
# g# 7-available food (butter popcorn caramel popcorn, cheese popcorn, nachos, hotdog, fries, slush, water, coca cola, sprite )
# g# 8-do you want the food delivered to your seat or pickup.
# g# Thank you, enjoy your movie
#
# Movie names: The purge | Cruella | The Conjouring
# Seat list: A1-A5 | B1-B5 | C1-C5 | D1-D5
# command = input("Hey, how old are you ? ")
# while command!= [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17] :
# if command == [18,19]:
# print("which movie")
# command= input("thats a great choice")
# print("sorry, you cant choose this movie")
Seats-Room1 = ["A1","A2","A3","A4","A5","B1","B2","B3","B4","B5","C1","C2","C3","C4","C5","D1","D2","D3","D4","D5"]
Seats-Room2 = ["A1","A2","A3","A4","A5","B1","B2","B3","B4","B5","C1","C2","C3","C4","C5","D1","D2","D3","D4","D5"]
Seats-Room3 = ["A1","A2","A3","A4","A5","B1","B2","B3","B4","B5","C1","C2","C3","C4","C5","D1","D2","D3","D4","D5"]
|
cbe1269dfe396b590938bc62b5355e46a5f99804 | steellsas/fundementals1 | /100 chalenge of singnals/find_common__num_in2string/Itertools Kit/Rock Paper Scissors.py | 785 | 3.84375 | 4 | """
The greatest ever Rock-Paper-Scissors Championship will take place in your town!
The best players will battle each other to see who's the best player in the world.
Each player will compete against each other player twice, once home and once away.
Given the list of the players, your task is to come up with the list of all the games between them, and return them sorted lexicographically.
Example
For players = ["trainee", "warrior", "ninja"], the output should be
"""
from itertools import permutations
def rockPaperScissors(players):
return list(permutations(sorted(players), 2))
# list(permutations(sorted(players), 2))
# sorted([[x[0],x[1]] for x in list(permutations(players,2))])
players = ["trainee", "warrior", "ninja"]
print(rockPaperScissors(players)) |
95e9340b4ba1a86ead551aea75bf55c8005724f7 | Shiesu/ProjectEuler | /ProjectEuler5.py | 456 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 07 16:53:02 2016
Project Euler #5
Time Complexity: O(1)
@author: Jan Henrik Wiik
"""
import time
from math import *
start_time = time.clock()
#-----------------------------------------------------------------------------
output = 16*9*5*7*11*13*17*19
#-----------------------------------------------------------------------------
end_time = time.clock()
print output
print "Time elapsed: %fs"%(end_time-start_time) |
762f269c2fd917f734e55d2bb6c47d2237cd859f | nelsonhenrique/Nelson-Henrique-Duarte | /Estruturas de Repetição e Dados/Lista 1 - Animais Zoologico.py | 549 | 3.53125 | 4 | qtdC = 0
qtdM = 0
mediaT = 0
pesoT = 0
qtdT = 0
def add():
tipo = input("")
peso = float(input(""))
pais = input("")
if tipo == 'macaco':
global qtdM
qtdM = qtdM + 1
elif tipo == 'cobra' and pais == 'Venezuela':
global qtdC
qtdC = qtdC + 1
elif tipo == 'tigre':
global pesoT
global qtdT
pesoT = pesoT + peso
qtdT = qtdT + 1
add()
i = input("")
while i == 'continuar':
add()
i = input("")
print(qtdM)
if qtdT != 0:
mediaT = pesoT / qtdT
else:
mediaT = 0
print(round(mediaT, 2))
print(qtdC)
|
60bcfb78f0457e4d459c989051b85b554b1756a4 | ShubhamKulkarni1495/List_python | /List/even_odd_avg.py | 498 | 3.90625 | 4 | elements = [23, 14, 56, 12, 19, 9, 15, 25, 31, 42, 43]
i=0
sum=0
sum1=0
count=0
count1=0
while(i<len(elements)):
if(elements[i]%2==0):
sum=sum+elements[i]
count+=1
else:
sum1=sum1+elements[i]
count1+=1
i+=1
print("the sum of Even numbers:",sum)
print("count of odd numbers",count)
print("the Average of Even numbers:",sum/count)
print("the sum of Odd numbers:",sum1)
print("count of odd number",count1)
print("the Average of Odd numbers:",sum1/count1)
|
9fedbcda18aa5199fee768fc3ee0fa73c41f906e | ASairithwikmahateja/cspp-1-assignment | /Exam/p3/digit_product.py | 695 | 4.1875 | 4 | '''
Given a number int_input, find the product of all the digits
example:
input: 123
output: 6
'''
def main():
'''
Read any number from the input, store it in variable int_input.
'''
int_input = int(input())
prod = 1
prod1 = 1
if int_input > 0:
while int_input > 0:
temp = int_input%10
prod = prod*temp
int_input = int_input//10
print(prod)
elif int_input < 0:
while abs(int_input) > 0:
temp = int_input%10
prod = prod*temp
int_input = int_input//10
prod1 = -1*prod
print(prod1)
else:
print(0)
if __name__ == "__main__":
main()
|
f72890fb046a5bfb59ea74e58003677bf61ed9a5 | xiaomuding/project | /1128/test.py | 1,482 | 3.9375 | 4 | import string
#去除空格
a = " sdf dfg "
print(a.strip())
print(a.rstrip())
print(a.lstrip())
print(a)
#字符串链接
s1 = "sdf"
s2 = "fghf"
print(s1+s2)
#大小写
s = "dgfdgfdg"
print(s.upper())
print(s.upper().lower())
print(s.capitalize())
#位置比较
s1 = "sdfsdfdsg"
s2 = "dfdgfsdsfsdf"
print(s1.index("dsg"))
try:
print(s2.index("kjhh"))
except ValueError:
print("not found")
print(s1 == s1)
print(s1 > s2)
print(s1 < s2)
print(len(s1) > len(s2))
print(len(s1) < len(s2))
print(len(""))
print(len(" "))
#分割和链接
s = ", sdf,dfg,,dfg,dfg"
splitted = s.split(",")
print(splitted)
print(type(splitted))
s = """
sdf
dfg
dfg
wer
fdgg
"""
sp = s.split("\n")
sp1 = s.splitlines()
print(sp)
print(sp1)
s = ["ddf","dfg","dfg","dfg"]
print("\t".join(s))
#常用判断
s = "sdgfdgfdg"
print(s.startswith("sdg"))
print(s.endswith("g"))
print("2324sdfs".isalnum())
print("sdfdsf\t".isalnum())
print("sdfds".isalpha())
print("234535".isdigit())
print(" ".isspace())
print("sfsdf".islower())
print("234sdF".islower())
print("2354D".isupper())
print("Wsdf".istitle())
#数字,字符产转化
print(type(str(5.3689)))
print(int("5"))
print(float(5.5689))
print(int("1111",2))
x = None
if x is None:
print("nome")
else:
print("not")
str = "4568dfgfd"
for i in str:
print(i)
for i in range(0,100):
if i < 10:
pass
if i<30:
continue
elif i<35:
print(i)
else:
breakpoint()
|
b17fff2eedf5e6c0c9bda2b8588e4f1c2b1e6ba8 | suyashpujari/PythonTrial | /assignment_using_functions.py | 1,801 | 4.3125 | 4 | # 1) Reverse a String and print it on console "Python Skills"
print("\n---Answer 1---")
str="Python Skills"
print("\nOriginal string: ",str)
print("\nReversed string: ",str[::-1])
# 2) Assign String to x variable in DD-MM-YYYY format extract and print Year from String.
print("\n---Answer 2---")
import datetime
date = "19-08-2021"
format = "%d-%m-%Y"
dt_object = datetime.datetime.strptime(date, format)
print("\nYear using function : ", dt_object.year)
print("\nYear using slice operator:",date[6:])
# 3) In a small company, the average salary of three employees is Rs1000 per week. If one employee earns Rs1100 and other earns Rs500, how much will the third employee earn? Solve by using java programm
print("\n---Answer 3---")
#import os.path,subprocess
#output = subprocess.check_output("java average", stderr=subprocess.PIPE)
#print(output)
avg=1000
e1=1100
e2=500
e3=(avg*3)-(e1+e2)
print("\nFirst employee salary = ",e1,"\nSecond employee salary =",e2,"\nThird employee salary = ",e3,"\nAverage =",avg)
# 4) Write Program - convert a percentage to a fraction (To convert a percentage into fraction let say 30% to a fraction)
print("\n---Answer 4---")
percent=30
n=percent
d=100
num=n/10
den=d/10
print("\nConversion of 30 percent into fraction is equal to : ",int(num),"/",int(den))
# 5) Write Program - A train 340 m long is running at a speed of 45 km/hr. what time will it take to cross a 160 m long tunnel?
print("\n---Answer 5---")
train_length=340
tunnel_length=160
#Total distance to be travelled by train
distance=train_length+tunnel_length
print("Total distance to be travelled by train:",distance,"meter")
#Conversion of km per hour into m per seconds
speed=(45*5)/18
print("Speed=",speed,"m/sec")
time=distance/speed
print("Time taken by train to cross the tunnel=",time,"sec")
|
17d8ce9e037818cf3f7ab97be7e60a423e180a37 | gijs/python-design-patterns | /adapter.py | 875 | 3.953125 | 4 | #!/usr/bin/env python
"""Example of the adapter pattern.
The Adapter Pattern is useful to either either map two different interfaces or
to just modify (wrap) an existing API.
"""
from datetime import datetime
class AnnoyingAPI(object):
def method_with_annoying_arguments(self, month, date, year, minute, second):
return str(month) + '/' + str(date) + '/' + str(year)
class AnnoyingAdapter(object):
def __init__(self):
self.annoying_api = AnnoyingAPI()
def nicer_method(self, time_object):
mo = time_object.month
d = time_object.day
y = time_object.year
mi = time_object.minute
s = time_object.second
return self.annoying_api.method_with_annoying_arguments(mo, d, y, mi, s)
if __name__ == '__main__':
adapter = AnnoyingAdapter()
r = adapter.nicer_method(datetime.now())
print(r) |
cc49dd75ecc558189b66be7cb5742f134b77fd7f | oleksiiberezhnyi/BeetrootAcademy | /Graphs/dfs_task1.py | 1,715 | 3.640625 | 4 | from collections import defaultdict
class Graph:
def __init__(self, count_of_vertex):
self.count = count_of_vertex
self.graph = defaultdict(list)
def add_edge(self, start, end):
self.graph[start].append(end)
def dfs(self, vertex, visited_vertex):
visited_vertex[vertex] = True
print(f'|{vertex}|', end='')
for i in self.graph[vertex]:
if not visited_vertex[i]:
self.dfs(i, visited_vertex)
def fill_order(self, vertex, visited_vertex, stack):
visited_vertex[vertex] = True
for i in self.graph[vertex]:
if not visited_vertex[i]:
self.fill_order(i, visited_vertex, stack)
stack = stack.append(vertex)
def transpose(self):
graph_transpose = Graph(self.count)
for i in self.graph:
for j in self.graph[i]:
graph_transpose.add_edge(j, i)
return graph_transpose
def print_scc(self):
stack = []
visited_vertex = [False] * self.count
for i in range(self.count):
if not visited_vertex[i]:
self.fill_order(i, visited_vertex, stack)
graph = self.transpose()
visited_vertex = [False] * self.count
while stack:
i = stack.pop()
if not visited_vertex[i]:
graph.dfs(i, visited_vertex)
print("")
g = Graph(11)
g.add_edge(0, 1)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(1, 3)
g.add_edge(3, 4)
g.add_edge(4, 5)
g.add_edge(5, 3)
g.add_edge(6, 5)
g.add_edge(6, 7)
g.add_edge(7, 8)
g.add_edge(8, 9)
g.add_edge(9, 6)
g.add_edge(10, 9)
print("Strongly Connected Components:")
g.print_scc()
|
107b23adc0bda9b34dd68247e31bddcf25e99982 | msuriar/euler | /029/solution.py | 270 | 3.5625 | 4 | #!/usr/bin/env python
def distinct_powers(a,al,b,bl):
data = set()
for base in xrange(a,al+1):
for power in xrange(b,bl+1):
data.add(base ** power)
return data
def main():
print len(distinct_powers(2,100,2,100))
if __name__ == "__main__":
main()
|
2b8961c816f63170583433859108d5232645d4a1 | rithotwheelz/perry2017 | /Decoder.py | 12,057 | 3.609375 | 4 | """
Program is used to decode the data from CAN bus messages originating from the
BMS. Program takes in a large string containing bytes in hex form. Multiple CAN
bus messages are contained in this string. Each CAN bus message is 36 bytes long.
Program updates paramter values for the BMS from these CAN bus messages and
also prints any detected faults to the command line.
"""
from defTest import *
bmsData = [0, 0, 0, 0, 0, 0, 0]
bmsFaults = [0, 0, 0, 0, 0, 0, 0]
contData = [0, 0, 0, 0, 0, 0, 0, 0]
contFaults = [0, 0, 0, 0, 0, 0, 0]
def decoder(message):
"""
Function to decode a large byte hex string. The BMS data parameters are
overwritten after each message is decoded. Faults are printed to the
console. Function only recognizes 2 message IDs in each message.
Input: message (str) - A large byte string containing hex values. This
string contains multiple can bus messages
Output: none.
"""
#Number indicating the index of the first important hex value in each
# can bus message.
first = 48
#Number indicating the index of the last important hex value in each
# can bus message
last = 72
#The number of CAN messages which will be read in each message string. Each
# can bus message is 36 bytes. The first number of messages will be read. #The rest will be ignored.
line_num = 3
#Variable to keep track of the current can bus message index in each
# message string
line_count = 1
#Variable containing current index of first important hex value in each
# can bus message
min_idx = line_count * first
#Variable containing current index of last important hex value in each
# can bus message
max_idx = line_count * last
#Loop through the number of indicated CAN messages in each message string,
# decoding each message, either a data message or a fault message
while line_count <= (line_num + 1):
#Use the current first and last indices to get the CAN ID and data
# bytes for the current 36 byte CAN bus message
good = message[min_idx:max_idx]
#Check if the current CAN ID matches the BMSDataID in order to use the
# corresponding data bytes to update the dictionary values. Store
# the hex values in decimal
if good[0:8] == BMSDataID:
bmsData[0] = int(good[8:12], 16)
bmsData[1] = int(good[12:16], 16)
bmsData[2] = int(good[16:18], 16)
bmsData[3] = int(good[18:20], 16)
bmsData[5] = int(good[20:22], 16)
bmsData[4] = int(good[22:24], 16)
#Else if the CAN ID matches the BMSFaultID, then check the
# corresponding data bytes to find faults. Each byte in the data
# section is converted to binary. Each bit in each byte corresponds
# to a fault. A '1' indicates a fault, '0' indicates normal operation.
# Print each detected fault to the command line
elif good[0:8] == BMSFaultID:
#convert bytes to binary
binary0 = hextobin(good[8:10])
binary1 = hextobin(good[10:12])
binary2 = hextobin(good[12:14])
#Variable to keep track of index of current bit in each byte
i = 0
#Clear previous bms faults
reset(bmsFaults)
#Loop through each byte and check for active faults. Print them
while i < 8:
if binary0[i] == "1":
for j in range(0,7):
if bmsFaults[j] == 0:
bmsFaults[j] = BMSFaultList0[i]
break
else:
try:
bmsFaults.remove(BMSFaultList0[i])
except ValueError:
pass
#Increment index variable
i += 1
#Reset index variable
i = 0
while i < 8:
if binary1[i] == "1":
for j in range(0,7):
if bmsFaults[j] == 0:
bmsFaults[j] = BMSFaultList1[i]
break
else:
try:
bmsFaults.remove(BMSFaultList1[i])
except ValueError:
pass
#Increment index variable
i += 1
#Reset index variable
i = 0
while i < 5:
if binary2[i] == "1":
for j in range(0,7):
if bmsFaults[j] == 0:
bmsFaults[j] = BMSFaultList2[i]
break
else:
try:
bmsFaults.remove(BMSFaultList2[i])
except ValueError:
pass
#Increment index variable
i += 1
#Last 3 bits of third byte correspond to current battery level
# (e.g. If 5th index is high, battery level is high)
# Battery levels stored in BMS data parameter dictionary.
# High: 3, Medium: 2, Low: 1
if binary2[5] == "1":
bmsData[6] = 3
elif binary2[6] == "1":
bmsData[6] = 2
elif binary2[7] == "1":
bmsData[6] = 1
elif good[0:8] == controllerData0:
con0 = good[10:12] + good[8:10]
con1 = good[14:16] + good[12:14]
con2 = good[18:20] + good[16:18]
con3 = good[22:24] + good[20:22]
contData[0] = int(con0, 16)
contData[1] = int(con1, 16)
contData[2] = int(con2, 16)
contData[3] = int(con3, 16)
elif good[0:8] == controllerData1:
con4 = good[10:12] + good[8:10]
con5 = good[14:16] + good[12:14]
con6 = good[18:20] + good[16:18]
con7 = good[22:24] + good[20:22]
contData[4] = int(con4, 16)
contData[5] = int(con5, 16)
contData[6] = int(con6, 16)
contData[7] = int(con7, 16)
elif good[0:8] == controllerFaults:
binary0 = hextobin(good[8:10])
binary1 = hextobin(good[10:12])
binary2 = hextobin(good[12:14])
binary3 = hextobin(good[14:16])
binary4 = hextobin(good[16:18])
binary5 = hextobin(good[18:20])
binary6 = hextobin(good[20:22])
binary7 = hextobin(good[22:24])
#Variable to keep track of index of current bit in each byte
i = 0
#Clear previous controller faults
reset(contFaults)
#Loop through each byte and check for active faults. Print them
while i < 8:
if binary0[i] == "1":
for j in range(0,7):
if contFaults[j] == 0:
contFaults[j] = controllerFaults0[i]
break
else:
try:
contFaults.remove(controllerFaults0[i])
except ValueError:
pass
#Increment index variable
i += 1
#Reset index variable
i = 0
while i < 8:
if binary1[i] == "1":
for j in range(0,7):
if contFaults[j] == 0:
contFaults[j] = controllerFaults1[i]
break
else:
try:
contFaults.remove(controllerFaults1[i])
except ValueError:
pass
#Increment index variable
i += 1
#Reset index variable
i = 0
while i < 8:
if binary2[i] == "1":
for j in range(0,7):
if contFaults[j] == 0:
contFaults[j] = controllerFaults2[i]
break
else:
try:
contFaults.remove(controllerFaults2[i])
except ValueError:
pass
#Increment index variable
i += 1
#Reset index variable
i = 0
while i < 8:
if binary3[i] == "1":
for j in range(0,7):
if contFaults[j] == 0:
contFaults[j] = controllerFaults3[i]
break
else:
try:
contFaults.remove(controllerFaults3[i])
except ValueError:
pass
#Increment index variable
i += 1
#Reset index variable
i = 0
while i < 8:
if binary4[i] == "1":
for j in range(0,7):
if contFaults[j] == 0:
contFaults[j] = controllerFaults4[i]
break
else:
try:
contFaults.remove(controllerFaults4[i])
except ValueError:
pass
#Increment index variable
i += 1
#Reset index variable
i = 0
while i < 8:
if binary5[i] == "1":
for j in range(0,7):
if contFaults[j] == 0:
contFaults[j] = controllerFaults5[i]
break
else:
try:
contFaults.remove(controllerFaults5[i])
except ValueError:
pass
#Increment index variable
i += 1
#Reset index variable
i = 0
while i < 8:
if binary6[i] == "1":
for j in range(0,7):
if contFaults[j] == 0:
contFaults[j] = controllerFaults6[i]
break
else:
try:
contFaults.remove(controllerFaults6[i])
except ValueError:
pass
#Increment index variable
i += 1
#Reset index variable
i = 0
while i < 8:
if binary7[i] == "1":
for j in range(0,7):
if contFaults[j] == 0:
contFaults[j] = controllerFaults7[i]
break
else:
try:
contFaults.remove(controllerFaults7[i])
except ValueError:
pass
#Increment index variable
i += 1
#Increment counter variable
line_count += 1
#Increase index for first important hex value in each message
min_idx = (line_count * first) + 24
#Increase index for last important hex value in each message
max_idx = line_count * last
def reset(f):
# Reset the faults
for x in range(0,7):
f[x] = 0
def hextobin(hexval):
'''
Takes a string representation of hex data with
arbitrary length and converts to string representation
of binary. Includes padding 0s.
Returns binary in reverse
'''
thelen = len(hexval) * 4
binval = bin(int(hexval, 16))[2:]
while len(binval) < thelen:
binval = '0' + binval
return binval[::-1]
def updateAll(message):
decoder(message)
return [bmsData, bmsFaults, contData, contFaults]
|
7223fca65f0ae3de6f02c8cbbdfb17827c4b8be6 | Ruia-ruia/Small-Tools | /atoi.py | 681 | 3.625 | 4 | def integer(x):
digits = list('0123456789')
found = list()
#correspond and preserve index of digit to string present in x string
for j in x:
i = 0
while i < len(digits):
if digits[i] == j:
found.append(i)
i += 1
final = 0;
counter = 0;
lim = len(found) - 1
#use unit positions to turn indices into magnitudes (1's, 10's, 100's, etc.)
while lim >= 0:
final += (10**counter) * found[lim]
counter += 1
lim -= 1
#check if negative sign in original string
if x[0] == '-':
return final * (-1)
else:
return final
|
6563b2526edb897f9008acb74f3a77d338f45a03 | RakaPKS/StructuresAlgorithmsAndConcepts | /exercises/Arrays and Strings/stringCompression.py | 763 | 4.375 | 4 | # implement a method to perform basic string compression using the
# counts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3.
# if the compressed string would not become smaller then return the original string
# string only has upper and lower case characters
def stringCompression(s):
changed = False
currentChar = ""
count = 0
output = ""
for character in s:
if currentChar == character:
count += 1
changed = True
else:
if currentChar:
output += currentChar + str(count)
currentChar = character
count = 1
return output if changed else s
print(stringCompression("abc"))
print(stringCompression("aabcccccaaa"))
|
3ba0362641fa997d9c9d07c925a869e1a4c84a22 | silviafrigatto/python-exercicios | /e033_MaiorMenor.py | 727 | 4.125 | 4 | # Faça um programa que leia três números e mostre qual é o maior e qual
# é o menor.
n1 = int(input("Primeiro número: "))
n2 = int(input("Segundo número: "))
n3 = int(input("Terceiro número: "))
if n1 > n2 and n2 > n3:
print(f"O maior número é {n1}.\nO menor número é {n3}.")
elif n1 > n3 and n3 > n2:
print(f"O maior número é {n1}.\nO menor número é {n2}")
elif n2 > n1 and n1 > n3:
print(f"O maior número é {n2}.\nO menor número é {n3}.")
elif n2 > n3 and n3 > n1:
print(f"O maior número é {n2}.\nO menor número é {n1}.")
elif n3 > n1 and n1 > n2:
print(f"O maior número é {n3}.\nO menor número é {n2}.")
else:
print(f"O maior número é {n3}.\nO menor número é {n1}.")
|
c5f3da4fcbbee9a45bd181a63b9810ae925090b5 | umanav/Lab206 | /Python/Fundamentals/Stars.py | 1,165 | 4.125 | 4 | #Stars
#Part I
#Create a function called draw_stars() that takes a list of numbers and prints out *.
# def draw_stars(arr):
# for index in range(len(arr)):
# counter = 0
# string = ""
# while counter < arr[index]:
# string += "*"
# counter+=1
# print string
# draw_stars([4, 6, 1, 3, 5, 7, 25])
#Part II
#Modify the function above. Allow a list containing integers and strings to be passed to the draw_stars() function. When a string is passed, instead of displaying *, display the first letter of the string
def draw_stars(arr):
for index in range(len(arr)):
counter = 0
string = ""
if isinstance(arr[index],str)==True:
while counter < len(arr[index]):
string += arr[index][0]
counter+=1
print string
elif isinstance(arr[index],int)==True:
while counter < arr[index]:
string += "*"
counter+=1
print string
draw_stars([4, "Tom", 1, "Michael", 5, 7, "Jimmy Smith"])
#commented the first function so you can see what was done in part I
|
389c617c4dc3ac0ea5e32706b860890502a73efe | beb777/Python-3 | /001.py | 239 | 4.09375 | 4 | grade = float(input('enter your result '))
if grade >= 90:
print(f' congratulation !!!\n "A"')
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
elif grade >= 65:
print("D")
else:
print("Failing grade")
|
e92d2546f58e3b1c07ebe46e15f2d661b0f58647 | Krystalllll/newtry | /hw1_answer.py | 5,418 | 3.609375 | 4 | # import cv2
import numpy as np
def cross_correlation_2d(img, kernel):
'''Given a kernel of arbitrary m x n dimensions, with both m and n being
odd, compute the cross correlation of the given image with the given
kernel, such that the output is of the same dimensions as the image and that
you assume the pixels out of the bounds of the image to be zero. Note that
you need to apply the kernel to each channel separately, if the given image
is an RGB image.
Inputs:
img: Either an RGB image (height x width x 3) or a grayscale image
(height x width) as a numpy array.
kernel: A 2D numpy array (m x n), with m and n both odd (but may not be
equal).
Output:
Return an image of the same dimensions as the input image (same width,
height and the number of color channels)
'''
m, n = kernel.shape
m2, n2 = m // 2, n // 2
mn = m * n
kernel = np.ravel(kernel)
newImg = np.empty(img.shape)
if img.ndim == 3:
h, w, chans = img.shape
else:
chans = 1
h, w = img.shape
# Make img always end up with 3 dimensions
img = img[:, :, np.newaxis]
paddedWorkspace = np.zeros((h + m - 1, w + n - 1, chans), dtype=img.dtype)
# Pad the original image in our reusable workspace
paddedWorkspace[m2:m2+h, n2:n2+w] = img
for x in xrange(w):
for y in xrange(h):
# Extract the area from the workspace we are cross-correlating
# and compute dot product
sliced = np.reshape(paddedWorkspace[y:y+m, x:x+n], (mn, chans))
newImg[y, x] = np.dot(kernel, sliced)
return newImg
def convolve_2d(img, kernel):
'''Use cross_correlation_2d() to carry out a 2D convolution.
Inputs:
img: Either an RGB image (height x width x 3) or a grayscale image
(height x width) as a numpy array.
kernel: A 2D numpy array (m x n), with m and n both odd (but may not be
equal).
Output:
Return an image of the same dimensions as the input image (same width,
height and the number of color channels)
'''
return cross_correlation_2d(img, np.flipud(np.fliplr(kernel)))
def gaussian_blur_kernel_2d(sigma, width, height):
'''Return a Gaussian blur kernel of the given dimensions and with the given
sigma. Note that width and height are different.
Input:
sigma: The parameter that controls the radius of the Gaussian blur.
Note that, in our case, it is a circular Gaussian (symmetric
across height and width).
width: The width of the kernel.
height: The height of the kernel.
Output:
Return a kernel of dimensions width x height such that convolving it
with an image results in a Gaussian-blurred image.
'''
# Radius of Gaussian
rx, ry = (1 - width) * 0.5, (1 - height) * 0.5
# We assume each element of the kernel takes its value from the
# distance of its midpoint to the center of the Gaussian
kernelX = np.arange(rx, rx + width, 1.0) ** 2
kernelY = np.arange(ry, ry + height, 1.0) ** 2
# Formula for Gaussian is exp(-(x^2+y^2)/(2sigma^2))/(2pi*sigma^2)
# However we will compute the kernel from the outer product of two vectors
twoSig2 = 2 * sigma * sigma
kernelX = np.exp(- kernelX / twoSig2)
kernelY = np.exp(- kernelY / twoSig2) / (twoSig2 * np.pi)
# Kernel is outer product
kernel = np.outer(kernelX, kernelY)
# We need to normalize the kernel
s = np.sum(kernelY) * np.sum(kernelX)
return kernel / s
def low_pass(img, sigma, size):
'''Filter the image as if its filtered with a low pass filter of the given
sigma and a square kernel of the given size. A low pass filter supresses
the higher frequency components (finer details) of the image.
Output:
Return an image of the same dimensions as the input image (same width,
height and the number of color channels)
'''
return convolve_2d(img, gaussian_blur_kernel_2d(sigma, size, size))
def high_pass(img, sigma, size):
'''Filter the image as if its filtered with a high pass filter of the given
sigma and a square kernel of the given size. A high pass filter suppresses
the lower frequency components (coarse details) of the image.
Output:
Return an image of the same dimensions as the input image (same width,
height and the number of color channels)
'''
return img - low_pass(img, sigma, size)
def create_hybrid_image(img1, img2, sigma1, size1, high_low1, sigma2, size2,
high_low2, mixin_ratio):
'''This function adds two images to create a hybrid image, based on
parameters specified by the user.'''
high_low1 = high_low1.lower()
high_low2 = high_low2.lower()
if img1.dtype == np.uint8:
img1 = img1.astype(np.float32) / 255.0
img2 = img2.astype(np.float32) / 255.0
if high_low1 == 'low':
img1 = low_pass(img1, sigma1, size1)
else:
img1 = high_pass(img1, sigma1, size1)
if high_low2 == 'low':
img2 = low_pass(img2, sigma2, size2)
else:
img2 = high_pass(img2, sigma2, size2)
img1 *= 2 * (1 - mixin_ratio)
img2 *= 2 * mixin_ratio
hybrid_img = (img1 + img2)
return (hybrid_img * 255).clip(0, 255).astype(np.uint8)
|
3c45f0a6f3f432901fc9f612d51aacefbfc4cbac | Krzemyksc/python_bootcamp_2018 | /zjazd_4/mathematica/algebra/matrices.py | 1,030 | 3.609375 | 4 | # def add_matrices():
# X = [[12, 7, 3],
# [4, 5, 6],
# [7, 8, 9]]
#
# Y = [[5, 8, 1],
# [6, 7, 3],
# [4, 5, 9]]
#
# result = [[0, 0, 0],
# [0, 0, 0],
# [0, 0, 0]]
#
# licznik_r = []
#
# for i in range(len(X)):
# for j in range(len(X[0])):
# result[i][j] = X[i][j] + Y[i][j]
#
# for r in result:
# licznik_r.append(r)
# print("r", r)
# print("Licznik r", licznik_r)
def add_matrices(X,Y):
result = []
for row_i in range(len(X)):
new_row = []
for col_i in range(len(X[row_i])):
new_row.append((X[row_i][col_i] + Y[row_i][col_i]))
result.append(new_row)
return result
def sub_matrices(X, Y):
result = []
for row_i in range(len(X)):
new_row = []
for col_i in range(len(X[row_i])):
new_row.append((X[row_i][col_i] - Y[row_i][col_i]))
result.append(new_row)
return result
# a = add_matrices()
# print(a)
|
a99ace172c436e9ebf88490ae7952dbd20d745a5 | emilwillems/adventofcode_2020 | /day1/part2.py | 546 | 3.671875 | 4 | INPUTFILE = "day1/input"
puzzle_input = set(int(l) for l in open(INPUTFILE, "r").readlines())
def find_solution(puzzle):
for pi1 in puzzle:
for pi2 in puzzle:
if pi1 == pi2:
continue
for pi3 in puzzle:
if pi1 == pi3 or pi2 == pi3:
continue
if pi1 + pi2 + pi3 == 2020:
return (pi1, pi2, pi3)
s1, s2, s3 = find_solution(puzzle_input)
print(f"{s1} + {s2} + {s3} = 2020, {s1} * {s2} * {s3} = {s1 * s2 * s3}")
|
9e71f039dd2f93ace59526c3ee0fd4e075590965 | SurrealAI/torchx-public | /torchx/utils/tracker.py | 5,591 | 3.625 | 4 | import time
from contextlib import contextmanager
from threading import Thread, Lock
class SimpleTimer(object):
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.interval = self.end - self.start
print('elapsed', self.interval)
class MovingAverageRecorder:
"""
Records moving average
"""
def __init__(self, decay=0.95):
self.decay = decay
self.cum_value = 0
self.normalization = 0
def add_value(self, value):
self.cum_value *= self.decay
self.cum_value += value
self.normalization *= self.decay
self.normalization += 1
return self.cum_value / self.normalization
def cur_value(self):
"""
Returns current moving average, 0 if no records
"""
if self.normalization == 0:
return 0
else:
return self.cum_value / self.normalization
class ThreadSafeMovingAverageRecorder(MovingAverageRecorder):
def __init__(self, decay=0.95):
super().__init__()
self.lock = Lock()
def add_value(self, value):
with self.lock:
return super().add_value(value)
def cur_value(self):
with self.lock:
return super().cur_value()
class TimeRecorder:
"""
Records average of whatever context block it is recording
Don't call time in two threads
"""
def __init__(self, decay=0.9995, max_seconds=10):
"""
Args:
decay: Decay factor of smoothed moving average
Default is 0.9995, which is approximately moving average
of 2000 samples
max_seconds: round down all time differences larger than specified
Useful when the application just started and there are long waits
that might throw off the average
"""
self.moving_average = ThreadSafeMovingAverageRecorder(decay)
self.max_seconds = max_seconds
self.started = False
@contextmanager
def time(self):
pre_time = time.time()
yield None
post_time = time.time()
interval = min(self.max_seconds, post_time - pre_time)
self.moving_average.add_value(interval)
def start(self):
if self.started:
raise RuntimeError('Starting a started timer')
self.pre_time = time.time()
self.started = True
def stop(self):
if not self.started:
raise RuntimeError('Stopping a timer that is not started')
self.post_time = time.time()
self.started = False
interval = min(self.max_seconds, self.post_time - self.pre_time)
self.moving_average.add_value(interval)
def lap(self):
if not self.started:
raise RuntimeError('Stopping a timer that is not started')
post_time = time.time()
interval = min(self.max_seconds, post_time - self.pre_time)
self.moving_average.add_value(interval)
self.pre_time = post_time
@property
def avg(self):
return self.moving_average.cur_value()
class PeriodicWakeUpWorker(Thread):
"""
Args:
@target: The function to be called periodically
@interval: Time between two calls
@args: Args to feed to target()
@kwargs: Key word Args to feed to target()
"""
def __init__(self, target, interval=1, args=None, kwargs=None):
Thread.__init__(self)
self.target = target
self.interval = interval
self.args = args
self.kwargs = kwargs
def run(self):
if self.args is None:
self.args = []
if self.kwargs is None:
self.kwargs = {}
while True:
self.target(*self.args, **self.kwargs)
time.sleep(self.interval)
class TimedTracker(object):
def __init__(self, interval):
self.init_time = time.time()
self.last_time = self.init_time
self.interval = interval
def track_increment(self):
cur_time = time.time()
time_since_last = cur_time - self.last_time
enough_time_passed = time_since_last >= self.interval
if enough_time_passed:
self.last_time = cur_time
return enough_time_passed
class AverageValue(object):
"""
Keeps track of average of things
Always caches the latest value so no division by 0
"""
def __init__(self, initial_value):
self.last_val = initial_value
self.sum = initial_value
self.count = 1
def add(self, value):
self.last_val = value
self.sum += value
self.count += 1
def avg(self, clear=True):
"""
Get the average of the currently tracked value
Args:
@clear: if true (default), clears the cached sum/count
"""
ans = self.sum / self.count
if clear:
self.sum = self.last_val
self.count = 1
return ans
class AverageDictionary(object):
def __init__(self):
self.data = {}
def add_scalars(self, new_data):
for key in new_data:
if key in self.data:
self.data[key].add(new_data[key])
else:
self.data[key] = AverageValue(new_data[key])
def get_values(self, clear=True):
response = {}
for key in self.data:
response[key] = self.data[key].avg(clear=clear)
return response
|
a8a2321e0cf6cde920893cad152b825dcda76cfc | YasinRadi/DataStructures | /Tree/Red_Black_Tree/red_black_tree.py | 8,055 | 4.03125 | 4 | from collections import deque
from enum import Enum
# Possible colors of Red Black Tree nodes.
COLOR = Enum('COLOR', 'RED BLACK')
class Node:
""" Tree Node implementation class.
Attributes:
-----------
data : int
Data held by the node.
color : COLOR
Color of the node.
left : Node
Left child of the node.
right : Node
Right child of the node.
parent : Node
Parent of the node.
Parameters:
-----------
data : int
Data to be held by the node.
"""
def __init__(self, data):
self.data = data
self.color: COLOR = None
self.left: Node = None
self.right: Node = None
self.parent: Node = None
class RedBlackTree:
""" Red Black Tree implementation class.
Attributes:
-----------
root : Node
Root node of the red black tree.
"""
def __init__(self):
self.root: Node = None
def _BSTInsert(self, root: Node, node: Node):
""" Performs a STD BST insert.
Parameters:
----------
root : Node
Root of the tree.
node : Node
Node to be inserted.
Returns:
--------
The root of the tree or the same node if tree is empty.
"""
# If tree is empty return node
if root is None:
return node
# Otherwise, recurr down the tree
if node.data < root.data:
root.left = self._BSTInsert(root.left, node)
root.left.parent = root
elif node.data > root.data:
root.right = self._BSTInsert(root.right, node)
root.right.parent = root
# Return unchanged node
return root
def _inorderHelper(self, node: Node):
""" Recursive helper function for inorder traversal.
Parameters:
-----------
node : Node
Node whose content will be displayed.
"""
if node is None: return
self._inorderHelper(node.left)
print(node.data, end=' ')
self._inorderHelper(node.right)
def _levelOrderHelper(self, node: Node):
""" Helper function for level order traversal.
Parameters:
-----------
node : Node
Starting node for traversal content display.
"""
if node is None: return
# Queue of nodes to be displayed
q = deque()
q.append(node)
while len(q) > 0:
tmpNode = q.popleft()
print(tmpNode.data, end=' ')
if tmpNode.left is not None:
q.append(tmpNode.left)
if tmpNode.right is not None:
q.append(tmpNode.right)
def rotateLeft(self, node: Node):
""" Performs a subtree left rotation
starting at the given node.
Parameters:
-----------
node : Node
Starting point of subtree rotation.
"""
rightNode = node.right
node.right = rightNode.left
if node.right is not None:
node.right.parent = node
rightNode.parent = node.parent
if node.parent is None:
self.root = rightNode
elif node == node.parent.left:
node.parent.left = rightNode
else:
node.parent.right = rightNode
rightNode.left = node
node.parent = rightNode
def rotateRight(self, node : Node):
""" Performs a subtree right rotation
starting at the given node.
Parameters:
-----------
node : Node
Starting point of subtree rotation.
"""
leftNode = node.left
node.left = leftNode.right
if node.left is not None:
node.left.parent = node
leftNode.parent = node.parent
if node.parent is None:
self.root = leftNode
elif node == node.parent.left:
node.parent.left = leftNode
else:
node.parent.right = leftNode
leftNode.right = node
node.parent = leftNode
def fixViolation(self, node: Node):
""" Performs a fix of RB Tree properties
to a subtree with root a the given node.
Parameters:
-----------
node : Node
Root of the subtree to fix.
"""
parentNode = None
grandParentNode = None
while (node != self.root and node.color == COLOR.RED
and node.parent.color == COLOR.RED):
parentNode = node.parent
grandParentNode = parentNode.parent
# CASE A:
# Parent of node is left child of grand-parent of node
if parentNode == grandParentNode.left:
uncleNode = grandParentNode.right
# CASE 1:
# Uncle of node is also red
# Only recoloring required
if uncleNode is not None and uncleNode.color == COLOR.RED:
grandParentNode.color = COLOR.RED
parentNode.color = COLOR.BLACK
uncleNode.color = COLOR.BLACK
else:
# CASE 2:
# node is right child
# Left-rotation required
if node == parentNode.right:
self.rotateLeft(parentNode)
node = parentNode
parentNode = node.parent
# CASE 3:
# node is left child
# Right-rotation required
self.rotateRight(grandParentNode)
tmpColor = parentNode.color
parentNode.color = grandParentNode.color
grandParentNode.color = tmpColor
node = parentNode
# CASE B
# Parent of node is right child
else:
uncleNode = grandParentNode.left
# CASE 1:
# uncle is also red
# Only recoloring required
if uncleNode is not None and uncleNode.color == COLOR.RED:
grandParentNode.color = COLOR.RED
parentNode.color = COLOR.BLACK
uncleNode.color = COLOR.BLACK
node = grandParentNode
else:
# CASE 2:
# node is left child
# Right-rotation requred
if node == parentNode.left:
self.rotateRight(parentNode)
node = parentNode
parentNode = node.parent
# CASE 3:
# node is right child
# Left-rotation required
self.rotateLeft(grandParentNode)
tmpColor = parentNode.color
parentNode.color = grandParentNode.color
grandParentNode.color = tmpColor
node = parentNode
self.root.color = COLOR.BLACK
def insert(self, data):
""" Inserts a new node to tree.
Parameters:
-----------
data : int
Data to be inserted in a node and onto the tree.
"""
node = Node(data)
# Perform a normal BST insert
self.root = self._BSTInsert(self.root, node)
# Fix RB Tree violation
self.fixViolation(node)
def inorder(self):
""" Inorder traversal tree content display. """
self._inorderHelper(self.root)
print()
def levelOrder(self):
""" Level Order traversal tree content display. """
self._levelOrderHelper(self.root)
print() |
22792e4828fcb4a30cf4d1d18c68521c0e17caf7 | Chainso/HLRL | /hlrl/core/algos/algo.py | 4,210 | 3.859375 | 4 | from abc import ABC, abstractmethod
from typing import Any, Dict, Optional
class RLAlgo(ABC):
"""
An abstract reinforcement learning algorithm.
"""
def __init__(self, logger=None):
"""
Creates the reinforcement learning algorithm.
Args:
logger (Logger, optional): The logger to log results while training
and evaluating.
Properties:
logger (Logger): The logger to log results while training and
evaluating.
training_episodes (int): The number of episodes the algorithm
has been training for.
training_steps (int): The number of steps the algorithm has been
training for.
recurrent (bool): If the model is a recurrent model.
env_steps (int): The number of environment steps the algorithm has
been training for
"""
self.logger = logger
self.env_episodes = 0
self.training_steps = 0
self.env_steps = 0
@abstractmethod
def create_optimizers(self) -> None:
"""
Creates the optimizers for the algorithm, separate from the
intialization so that the model can be moved to a different device first
if needed.
"""
raise NotImplementedError
def process_batch(
self,
rollouts: Dict[str, Any],
) -> Dict[str, Any]:
"""
Processes a batch to make it suitable for training.
Args:
rollouts: The training batch to process.
Returns:
The processed training batch.
"""
return rollouts
def train_batch(
self,
rollouts: Dict[str, Any],
*args: Any,
**kwargs: Any
) -> Any:
"""
Processes a batch of rollouts then trains the network.
Args:
args: Positional training arguments.
kwargs: Keyword training arguments.
Returns:
The training return on the batch.
"""
processed_batch = self.process_batch(rollouts, *args, **kwargs)
return self.train_processed_batch(*processed_batch)
@abstractmethod
def train_processed_batch(
self,
rollouts: Dict[str, Any],
*args: Any,
**kwargs: Any
) -> Any:
"""
Trains the network for a batch of rollouts.
Args:
rollouts: The training batch to process.
args: Positional training arguments.
kwargs: Keyword training arguments.
"""
raise NotImplementedError
@abstractmethod
def step(self, observation):
"""
Get the model action for a single observation of gameplay.
Args:
observation: A single observation from the environment.
Returns:
The action from for the observation given.
"""
raise NotImplementedError
@abstractmethod
def save_dict(self) -> Dict[str, Any]:
"""
Saves in the current state of the algorithm in a dictionary.
Returns:
A dictionary of values to save this algorithm.
"""
raise NotImplementedError
@abstractmethod
def save(self, save_path):
"""
Saves the algorithm to a given save path.
"""
raise NotImplementedError
@abstractmethod
def load_dict(self, load_path):
"""
Reads and returns the load dictionary from the load path.
"""
raise NotImplementedError
@abstractmethod
def load(
self,
load_path: str = "",
load_dict: Optional[Dict[str, Any]] = None
):
"""
Loads the algorithm from a given save path. Will use the given state
dictionary if given, or load from a file otherwise.
"""
raise NotImplementedError
def reset_hidden_state(self):
"""
Resets the hidden state, if this is a recurrent algorithm.
"""
raise NotImplementedError |
d5dbadd2c097a39f94a1709f6acb98a8768a8eb0 | kranz912/ProjectEuler | /Problem 1 Multiplesof3and5.py | 84 | 3.84375 | 4 | sum =0
for x in range(3,1000):
if(x%3==0 or x%5 == 0):
sum+=x
print(sum) |
968efae7fbdc9620baadbcb129b804feb8538e51 | robin9804/RoadToDeepLearningKing | /Jinu/week3/example253.py | 202 | 3.65625 | 4 |
def fun(n) :
if n == 0:
return 1
elif n % 2 == 1:
return fun(n-1) * 2 - 1
else :
return fun(n-2) +3
for i in range(10) :
print(fun(i), end = ' ') |
0a55adf0f018a8b317d711564cd5f46103c4b7c0 | Xiaoyin96/Algorithms_Python | /interview_practice/66Questions/8. NextNode.py | 1,287 | 3.734375 | 4 | #!/usr/bin/env python
# encoding: utf-8
'''
@author: Xiaoyin
'''
'''
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
inorder traversal: pNode->left->right
'''
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
class Solution:
def Next(self, pNode):
if not pNode:
return None
# 如果该节点有右子树,那么下一个节点就是它右子树中的最左节点
if pNode.right != None: #
pNode = pNode.right
while pNode.left != None: # search for the leftest one
pNode = pNode.left
return pNode
# 如果一个节点没有右子树,,并且它还是它父节点的右子节点
elif pNode.next != None and pNode.next.right == pNode: # next pointer to parent node
while pNode.next != None and pNode.next.left != pNode # 父节点不是None,并且一直不是父节点的左孩子
pNode = pNode.next # 往父节点找,直到找到结点是父节点的左孩子
return pNode.next
|
b57abc18767bdcfcd30a15d54ba776b74fea91d0 | SOURADEEP-DONNY/WORKING-WITH-PYTHON | /souradeep codes/apparel.py | 1,801 | 3.78125 | 4 | class Apparel:
def __init__(self,apparelBrand,Type,price,InStock):
self.apparelBrand=apparelBrand
self.Type=Type
self.price=price
self.InStock=InStock
class Store:
def __init__(self,apparelList):
self.apparelList=apparelList
def checkApparelAvailability(self,strbr,strty,strsi,appreqd):
c1=0
c2=0
c3=0
for i in apparelList:
if strbr == i.apparelBrand and strty == i.Type:
c1=c1+1
for j in i.InStock:
if j == strsi:
c2=c2+1
if i.InStock[j] > appreqd:
c3=c3+1
i.InStock[j]=i.InStock[j]-appreqd
return(i.InStock)
if c1==0 and c2==0 and c3==0:
return None
if __name__=='__main__':
n=int(input())
apparelList=[]
for i in range(n):
apparelBrand=input()
Type=input()
price=int(input())
tot=int(input())
lsize=[]
lqty=[]
for j in range(tot):
size=input()
qty=int(input())
lsize.append(size)
lqty.append(qty)
InStock=dict(zip(lsize,lqty))
b=Apparel(apparelBrand,Type,price,InStock)
apparelList.append(b)
obj=Store(apparelList)
strbr=input()
strty=input()
strsi=input()
appreqd=int(input())
res=obj.checkApparelAvailability(strbr,strty,strsi,appreqd)
if res==None:
print('Size is not available.')
print('Apparel not Found')
else:
print('Size is available')
for i in res:
print(i,':',res[i])
|
10363f96b72bb070de8774dbb638447a420b26de | kuhlin/Python_MIT.6.00.1x | /BabySteps/W2 - 03 - Simple Algorithms/While Iteration 01.py | 888 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 19 18:12:07 2019
@author: gdiaconu
What is the value of the variable count that is printed out (at the print statement) on iteration 0?
What is the value of the variable count that is printed out (at the print statement) on iteration 1?
What is the value of the variable count that is printed out (at the print statement) on iteration 2?
What is the value of the variable count that is printed out (at the print statement) on iteration 3?
What is the value of the variable count that is printed out (at the print statement) on iteration 4?
"""
iteration = 0
count = 0
while iteration < 5:
# the variable 'letter' in the loop stands for every
# character, including spaces and commas!
for letter in "hello, world":
count += 1
print("Iteration " + str(iteration) + "; count is: " + str(count))
iteration += 1 |
cf990c9c278704dee7c3813e0a6d81ed5f7c0354 | FelixTheC/python_morsels | /format_ranges.py | 744 | 3.65625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@created: 16.10.19
@author: python morsels
"""
from collections import Counter
def format_ranges(numbers):
pairs = []
counts = Counter(sorted(numbers))
while counts:
start = end = None
for n in counts.keys():
counts[n] -= 1
if start is None:
start = n
elif n > end+1:
pairs.append((start, end))
start = n
end = n
pairs.append((start, end))
counts = +counts
pairs.sort()
return ",".join(f"{start}-{end}" if start != end else f"{start}" for (start, end) in pairs)
if __name__ == '__main__':
print(format_ranges([1, 9, 1, 7, 3, 8, 2, 4, 2, 4, 7]))
|
a9b945dec7d99694464ef803d56a24e4898279c3 | MNikov/Python-Advanced-September-2020 | /Tuples_and_Sets/05_softuni_party.py | 416 | 3.578125 | 4 | def collect_guests(n):
all_guests = [input() for _ in range(n)]
return all_guests
def get_not_arrived_guests(guests: list):
while True:
guest = input()
if guest == 'END':
break
guests.remove(guest)
print(len(guests))
[print(g) for g in sorted(guests)]
guests_count = int(input())
all_guests = collect_guests(guests_count)
get_not_arrived_guests(all_guests) |
69f88947ed85c7e764dd8dfb19fd604e4afb4555 | chandur626/ClassMateBot | /cogs/voting.py | 6,678 | 3.6875 | 4 | # Copyright (c) 2021 War-Keeper
"""
This File contains commands for voting on projects,
displaying which groups have signed up for which project.
"""
import csv
import discord
from discord.ext import commands
import os
class Voting(commands.Cog):
"""
Class provides various methods to manage voting of multiple groups.
"""
def __init__(self, bot):
self.bot = bot
@commands.command(name='vote', help='Used for voting for Project 2 and 3, \
To use the vote command, do: $vote \'Project\' <Num> \n \
(For example: $vote project 0)', pass_context=True)
async def vote(self, ctx, arg='Project', arg2='-1'):
"""
vote for the given project by adding the user to it.
Parameters:
ctx: used to access the values passed through the current context.
arg: the name of the project.
arg2: the number of the project.
Returns:
adds the user to the given project or returns an error if the project is invalid or
the user is not in a valid group.
"""
# load the groups from the csv
groups = load_groups()
# load the projects from the csv
projects = load_projects()
# get the arguments for the project to vote on
project_num = arg.upper() + ' ' + arg2
# get the name of the caller
member_name = ctx.message.author.display_name.upper()
# initialize which group the member in in
member_group = '-1'
# check which group the member is in
for key in groups.keys():
if member_name in groups[key]:
member_group = key
print(member_group)
# error handle if member is not in a group
if member_group == '-1':
await ctx.send(
"Could not fine the Group you are in,"
" please contact a TA or join with your group number")
raise commands.UserInputError
# if the project is a valid option
if project_num in projects:
# check if project has more than 6 groups voting on it
if len(projects[project_num]) == 6:
await ctx.send('A Project cannot have more than 6 Groups working on it!')
return
# check if you have already voted for another group
for key in projects.keys():
if member_group in projects[key]:
print(member_group)
await ctx.send('You already voted for ' + key.title())
return
# add the group to the project list
projects[project_num].append(member_group)
await ctx.send(member_group + ' has voted for ' + project_num.title() + '!')
print_projects(projects)
# error handling
else:
await ctx.send('Not a valid Project')
await ctx.send('Used for voting for Project 2 and 3, To use the vote command, '
'do: $vote \'Project\' <Num> \n (For example: $vote project 0)')
@vote.error
async def vote_error(self, ctx, error):
"""
this handles errors related to the vote command
"""
if isinstance(error, commands.UserInputError):
await ctx.send('To join a group, use the join command, do: $vote \'Project\' <Num> \n \
( For example: $vote Project 0 )')
@commands.command(name='projects', help='print projects with groups assigned to them',
pass_context=True)
@commands.dm_only()
async def projects(self, ctx):
"""
prints the list of current projects.
Parameters:
ctx: used to access the values passed through the current context.
Returns:
prints the list of current projects.
"""
projects = load_projects()
overall = ''
for key in projects.keys():
if key != 'PROJECT_NUM':
s = ''
temp = projects[key]
for num in temp:
s += num + ', '
if s != '':
overall += key + ': ' + s[:-2] + '\n'
else:
overall += key + ': \n'
await ctx.send(overall)
def load_projects() -> dict:
"""
Used to load the Project from the csv file into a dictionary.
"""
dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.chdir(dir)
os.chdir('data')
os.chdir('server_data')
with open('Project_mapping.csv', mode='r') as infile:
reader = csv.reader(infile)
student_pools = {
rows[0].upper(): [rows[1].upper(), rows[2].upper(), rows[3].upper(), rows[4].upper(),
rows[5].upper(), rows[6].upper()] for rows in reader}
for key in student_pools.keys():
student_pools[key] = list(filter(None, student_pools[key]))
return student_pools
def print_projects(projects):
"""
Used to print the Projects to the csv file.
"""
dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.chdir(dir)
os.chdir('data')
os.chdir('server_data')
with open('Project_mapping.csv', mode='w', newline="") as outfile:
writer = csv.writer(outfile)
for key in projects.keys():
while len(projects[key]) < 6:
projects[key].append(None)
writer.writerow([key] + projects[key])
def load_groups() -> dict:
"""
Used to load the groups from the csv file into a dictionary.
"""
dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.chdir(dir)
os.chdir('data')
os.chdir('server_data')
with open('groups.csv', mode='r') as infile:
reader = csv.reader(infile)
group = {rows[0].upper(): [rows[1].upper(), rows[2].upper(), rows[3].upper(), rows[4].upper(),
rows[5].upper(), rows[6].upper()] for rows in reader}
for key in group.keys():
group[key] = list(filter(None, group[key]))
return group
def print_groups(group):
"""
Used to print the groups to the csv file.
"""
with open('data/server_data/groups.csv', mode='w', newline="") as outfile:
writer = csv.writer(outfile)
for key in group.keys():
while len(group[key]) < 6:
group[key].append(None)
writer.writerow([key] + group[key])
def setup(bot):
"""
add the file to the bot's cog system.
"""
bot.add_cog(Voting(bot))
|
629439aa3b5c17d997042a977ae009fa80b61404 | gabriellaec/desoft-analise-exercicios | /backup/user_311/ch32_2019_04_04_16_35_39_112815.py | 155 | 4.03125 | 4 | x = input("dúvidas?")
while x != "não":
print ("pratique mais")
x = input("dúvidas?")
if x == "não":
print("Até a próxima") |
3c0628265dbcbecbfa37b94fa35cbf82a9c411dd | witameoliveira/lista_de_exercicios_pythonbrasil | /lista_de_exercicios_pythonbrasil/1_estrutura_sequencial/ex_004.py | 527 | 3.828125 | 4 | '''
Faça um Programa que peça as 4 notas bimestrais e mostre a média.
'''
bim_1 = float(input('Digite a primeira nota bimestral: '))
bim_2 = float(input('Digite a segunda nota bimestral: '))
bim_3 = float(input('Digite a terceira nota bimestral: '))
bim_4 = float(input('Digite a quarta nota bimestral: '))
media = (bim_1 + bim_2 + bim_3 + bim_4) / 4
print(f'A média das notas {bim_1}, {bim_2}, {bim_3} e {bim_4} é {media}.')
print('A média das notas {}, {}, {} e {} é {}.'.format(bim_1, bim_2, bim_3, bim_4, media))
|
3b822118c8f52131f43714b345dc26486a5c7a75 | conicRelief/Random-Things-from-my-Comp | /Miscellaneous Projects/Non Web/Miscellaneous Scripts/test_lists.py | 196 | 3.609375 | 4 | list_a = [10,11,13,14,15]
list_b = map(lambda x: x+10, list_a)
mergedlist = zip(list_a, list_b)
print mergedlist
a_dict = {'test': None, 'another_test': None}
for x in a_dict:
print "yo" |
10b8ab2d74230e7e1f0e683733b7b1ac79164eae | yoh786/HFHSpy | /Playground.py | 803 | 3.640625 | 4 | sumlist = []
for x in range (10):
sumlist.append(str(x))
print(str(sumlist))
def split_list(alist, size):
list_of_lists = []
while len(alist) > size:
abit = alist[:size]
list_of_lists.append(abit)
alist = alist[size:]
list_of_lists.append(alist)
return list_of_lists
def a_new_dict(alist):
new_object = {}
new_object["first"] = alist[0]
new_object["second"] = alist[1]
new_object["third"] = alist[2]
new_object["fourth"] = alist[3]
new_object["fifth"] = alist[4]
print(str(new_object))
return new_object
answer = split_list(sumlist, 5)
print(str(answer))
endArray = []
for v in answer:
print("mark")
one_obj = a_new_dict(v)
endArray.append(one_obj)
print(str(endArray))
|
9285f0e2adfe9f094693ba021b4efc24ebc37fb9 | SebastianPEZROE/Reto-18 | /main.py | 770 | 3.5 | 4 | class Gun:
def __init__(self, gun_charger):
self.bullet = 0
self.number_of_bullet = gun_charger
self.seguro = 0
def charger(self, bulletscharged):
if (bulletscharged + self.bullet) <= self.number_of_bullet:
self.bullet += bulletscharged
return 'cargada'
else:
self.bullet = self.number_of_bullet
bullets_wasted = bulletscharged + self.bullet-self.number_of_bullet
return bullets_wasted
def quitar_seguro(self):
self.seguro = 1
def poner_seguro(self):
self.seguro = 0
def shoot(self):
if self.bullet > 0 and self.seguro == 1:
self.bullet -= 1
return self.bullet
else:
return None |
5232777768b4a9ece1f94ab3dce3c949c505a219 | wajahata99/myrepo | /classes/helpers_2/cars_classes.py | 320 | 3.578125 | 4 | class car:
def __init__(self,price,engine):
self.price=price
self.engine=engine
def car_type(self):
if self.price > 10000 and self.engine < 1500:
str = "likely a sedan"
else:
str = "likely a cross over"
return print(str)
|
ed43ddd385f027f91df9c45bb48b1b5d1ff6c2e1 | KB-perByte/CodePedia | /Gen2_0_PP/Homeworks/leetcode_mostFrequentSubtreeSum.py | 868 | 3.578125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
if not root: return []
def helper(node):
nonlocal count
if node.left: helper(node.left) # 1
if node.right: helper(node.right) # 1
if node.left: node.val += node.left.val # 2
if node.right: node.val += node.right.val # 2
count[node.val] += 1 # 3
count = collections.defaultdict(int)
helper(root)
max_freq = max(count.values()) # 4
return [total for total in count if (count[total] == max_freq)] # 4 |
9bedc59e215e145afb0b0997fcccab6899262376 | NerdJain/Python | /empty_list.py | 756 | 3.859375 | 4 | def main():
l = []
#1st List
l1 = [1,2,'3',4.7,5]
l.append(l1)
#2nd list
l2 = []
l.append(l2)
#3rd list
l3 = ['A','b','h','i','s','h','e','k']
l.append(l3)
#4th list
l4 = ["Python","Numpy","Pandas","Lambda"]
l.append(l4)
#5th list
l5 = []
l.append(l5)
for item in l:
print("\nList")
print(item,end = ' ')
if len(item):
print("\nNot Empty")
else:
print("\nEmpty")
if __name__ == '__main__':
main()
#Output:
# C:\Users\DELL\py4e>python empty_list.py
# List
# [1, 2, '3', 4.7, 5]
# Not Empty
# List
# []
# Empty
# List
# ['A', 'b', 'h', 'i', 's', 'h', 'e', 'k']
# Not Empty
# List
# ['Python', 'Numpy', 'Pandas', 'Lambda']
# Not Empty
# List
# []
# Empty |
a04cfae37b908795299f9a244de01f581724045e | robin9804/RoadToDeepLearningKing | /YR/week3/problem213.py | 192 | 3.8125 | 4 | # probelm 213
num = input('new number')
while len(num) != 1:
new_num = 0
for i in num:
new_num += int(i)
new_num = str(new_num)
num = new_num
print(num)
|
64a91f42fcbbc1195ba3a11221826556bf93d735 | Mikcoolski/Python | /TaxCalculator.py | 609 | 4.375 | 4 | #This is a simple tax calculator and display prompt
#Obtain the name of user
name = input("What is your name?\n")
#obtain the amount the user purchased the product for
amount = float(input("How much did you spend on your product?\n"))
#obtian the tax bracket the user was taxed at
tax = float(input("What is the tax bracket you were charged at?\n"))
#Calculate the total
total = float(amount*tax)
#Displayt he calculated tax price the user was charged
promptMessage = "At the tax rate of {} and for a purchase order amount of {}, the total tax equates to {}"
print(promptMessage.format(tax,amount,total))
|
89ccec0a007e7922c9b6183afa6c8782986235e0 | LuceRest/learn-numpy | /Lat 4 - Indexing, Slicing, dan Iterasi/Main.py | 754 | 3.96875 | 4 | import numpy as np
a = np.arange(10) ** 2
print(a)
print("---------------------------------\n")
# -----------| Indexing (Mengambil Nilai) |-----------
print('Element ke 1 dari a adalah', a[0])
print('Element ke 7 dari a adalah', a[6])
print('Element ke akhir dari a adalah', a[-1])
print("---------------------------------\n")
# -----------| Slicing |-----------
print('Element dari 1-6 adalah', a[0:6]) # [<Start>:<End>]
print('Element dari 4 sampai akhir adalah', a[3:])
print('Element dari awal sampai 5 adalah', a[:5])
print("---------------------------------\n")
# -----------| Iterasi |-----------
for i in a:
print('Value =', i)
'''
NB :
- Indexing pada array numpy sama seperti indexing di list python.
'''
|
6ba2c0ddbc152c62b6847e46c58338f955885972 | KiranJoshi25/10_char_password_generator | /main.py | 1,002 | 3.71875 | 4 | import string
import random
def upper_char():
letters = ""
for i in range(2):
k = random.choice(string.ascii_uppercase)
letters+=k
return letters
def lower_char():
letters = ""
for i in range(4):
k = random.choice(string.ascii_lowercase)
letters += k
return letters
def symbol():
symbol_table = ["!","@","#","$","&"]
return random.choice(symbol_table)
def number():
numbers = ""
for i in range(3):
k = random.randint(0,9)
numbers+=str(k)
return numbers
def shuffle(arrray):
return random.shuffle(arrray)
def create(r):
password = ""
for i in range(len(r)):
password+=r[i]
return password
def generate_password():
u = upper_char()
l = lower_char()
s = symbol()
n = number()
choices = [u,l,s,n]
random.shuffle(choices)
password = create(choices)
return password
p = generate_password()
print(p)
|
34aabdc7d221d4e046d4c6dbb4071029e6f7ce32 | mr-rider/python_basic_07_09_20 | /homeworks/les2/task1.py | 624 | 3.90625 | 4 | '''
1. Создать список и заполнить его элементами различных типов данных.
Реализовать скрипт проверки типа данных каждого элемента. Использовать
функцию type() для проверки типа. Элементы списка можно не запрашивать
у пользователя, а указать явно, в программе.
'''
list_data = [1, 1.2, True, False, 'Some string', [1, 2, 3], (1 ,2, 3), {'key': 'value' } ]
for element in list_data:
print(element, type(element)) |
1e3093f172d1a85fe657dfd9032da8a0db022769 | AvishDhirawat/Python_Practice | /even_odd_cla.py | 257 | 3.734375 | 4 | import sys
print(sys.argv)
for i in range(1,len(sys.argv)):
sys.argv[i] = int(sys.argv[i])
if sys.argv[i]%2==0:
print('This is {} even number'.format(sys.argv[i]))
else:
print('This is {} odd number'.format(sys.argv[i]))
|
35ef6eae3d736486bbdc3e0969d54fdacd640901 | javedhassans/Headfirst_Python | /Harshad_number.py | 1,737 | 4.40625 | 4 | # write a function that determines if a number is a Harshad number
# and then uses this function to write another function that determines the ith Harshad number.
#
# A Harshad number is an integer that is divisible by the sum of its digits. For example, 81 is a Harshad number,
# because 8+1 = 9 and 81/9 = 9. The first Harshad number is 1.
#
# Assignment 2.1
#
# Write a function isHarshad that takes as input an integer and that has as output True,
# if the integer is a Harshad number, and False if it is not.
# For example, isHarshad(81) should have ouput True.
#
# Hint: Use str to convert the input to a string, see Chapter 8 of the Think Python book.
def isHarshad(n):
n_str = str(n)
sum_of_digits = 0
for i in n_str:
sum_of_digits = sum_of_digits + int(i)
if n == 0:
return False
elif n % sum_of_digits == 0:
return True
else:
return False
isHarshad(81)
# Assignment 2.2
#
# Write a function ithHarshad that takes as input an integer i and prints out a list of the ith Harshad numbers on screen.
# Make that function has no output, i.e., write a void function.
#
# For example, ithHarshad(25) should print:
#
# "The first 25 Harshad numbers are: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40,
# 42, 45, 48, 50, 54, 60]".
#
# Hint: use the isHarshad function above.
def ithharshad(arh):
i = 0 # counter checking of the number is harsh
j = 0 # counting the number of harsh numbers
hrash = []
while True:
if isHarshad(i):
hrash.append(i)
j += 1
if j == arh:
break
i += 1
print('The first ', arh, 'harshhard numbers are', hrash)
ithharshad(25)
|
4f95e116c01461d4b8c0c181dbd1269a8102e759 | kevich/projecteuler | /Problem0006.py | 769 | 3.84375 | 4 | #! /usr/bin/env python
# Sum square difference
# Problem 6
# The sum of the squares of the first ten natural numbers is,
# 12 + 22 + ... + 102 = 385
# The square of the sum of the first ten natural numbers is,
# (1 + 2 + ... + 10)2 = 552 = 3025
# Hence the difference between the sum of the squares of the
# first ten natural numbers and the square of the sum is 3025 - 385 = 2640.
# Find the difference between the sum of the squares of the
# first one hundred natural numbers and the square of the sum.
import math
sqrSum = pow(reduce(lambda res,x: res+x, xrange(1,101)),2)
sumSqr = reduce(lambda res,x: res+pow(x, 2), xrange(1,101))
print(str(sqrSum) + "-" + str(sumSqr) + "=" + str(sqrSum-sumSqr))
#./Problem6.py 0,01s user 0,01s system 37% cpu 0,057 total |
f1c0f14a15b3c8cc68b08ebf7106970ba757afff | AntoData/MarriageEqualityWorldwide | /Wrappers/MarriageEqualityChartGeneratorWrapper.py | 5,839 | 3.9375 | 4 | '''
Created on 21 jul. 2019
@author: ingov
'''
#We use pandas to create and manage dataframes and dataseries with our data
import pandas as pd
#We use matplotlib.pyplot to build and plot graphs
import matplotlib.pyplot as plt
#We use os to get our current folder so we can manage files
import os
#We use DonutChartGenerator to generate a donut graph
from API import DonutChartGenerator as dcg
def get_votes_by_party(data):
"""
@param data: Dataframe with our data
@return: A series, where we transform our 2D data frame to a 1D series
The format of that series is: [YesParty1, YesParty2, YesParty3,...,YesPartyN, NoParty1,...,
NoPartyN,...] so the outer region of our chart matches with the inner region. This way the
section with Yes votes for every party in the outer region of the chart, makes with the
section of Yes in the inner region and so on
"""
totals = []
#For each column, in this case for each possible option in the voting
for j in range(1,data.shape[1]):
#We get the votes for every political party
for i in range(0,data.shape[0]):
#We add it to our array
totals.append(data.loc[i][data.columns[j]])
#We turn our array into a series
ds = pd.Series(totals)
return ds
def get_annotations_marriage_equality(data):
"""
@param data: Dataframe with the data for our chart
@return: The annotations in the correct format for the outer region of the chart
"""
legend = []
#We just match key and value and give it the format: <Party> <Vote> and it to the array
#legend that we will return
for j in range(1,data.shape[1]):
for i in range(0,data.shape[0]):
item = "{0} {1}".format(data['Party'][i],data.columns[j])
legend.append(item)
return legend
def inner_donut_totals(df):
"""
@param df: Dataframe with the information
@return: A dataseries that contains the total of votes for every column/option.
In other words, the number of votes for Yes, No,... that we will use for the inner region
of our chart
"""
return df.drop(['Party'],axis=1).sum()
def marriage_equality_graph_generator(country,func_outer=get_votes_by_party,func_inner=inner_donut_totals,get_outer_annotations=get_annotations_marriage_equality,double=True,titleText="Marriage Equality",legendDict = {'green':'Yes','red':'No','yellow':'Abstained','grey':'Absent'}):
"""
@param country: Country where marriage equality was legalized and we are going to generate
a donut chart for the vote on marriage equality
@param func_outer: Function we are going to use to get the data to generate the outer region
of our doble donut chart. By default, get_votes_by_party defined previously
@param func_inner: Function we are going to use to get the data to generate the inner region
of our doble donut chart. By default, inner_donut_total defined previously
@param get_outer_annotations: Function we will use to get the data for the annotations for the outer
region of our donut chart. By default, get_annotations_marriage_equality defined previously
@param double: If True, we will build a double donut chart. If false a simple one.
By default True
@param titleText: Text for the graph, by default Marriage Equality
@param legendDict: Dictionary that contains the colors used for the inner region of this chart.
By default: green for Yes, red for No, yellow for Abstained and grey for Absent
@return A png file with our graph
This is a wrapper for the function graph generator in modile DonutChartGenerator in folder API
Basically just prepares the data and particular aspects of our problem which is building donut chart
that represent the votings for marriage equality in different countries
"""
try:
#We read the xlsx file that contais the information for the voting in that country
#and build a dataframe with it (all files have the same format)
df = pd.read_excel(os.getcwd()+"\..\data\{0}.xlsx".format(country))
#We add the country to the title of the graph
titleText = titleText + " " + country
#We use our graph generator to buld the graph
fig,ax = dcg.graph_generator(df, func_outer, func_inner, get_outer_annotations,double, titleText, legendDict)
#We save our graph as a png file that will be used later in the markers in the map
plt.savefig(os.getcwd()+"\..\pngFiles\{0}.png".format(country))
#We close our figure (which is important as we can't keep creating and displaying
#figures eternally)
plt.close(fig)
except FileNotFoundError:
#If we don't find the file for it, it means we have no information about that country
#and we just go on
pass
def gettingHTML(series):
"""
@param series: Dataseries that contains that information in the voting for same sex marriage
for a particular country
@returns: A string with HTML code that will display the graph we saved previously in
a png code in the pop-up for the marker
"""
doublePie = False
noinfo = False
if series['Voting'] == "Parliament":
doublePie = True
elif series['Voting'] == "-":
noinfo = True
if not noinfo:
marriage_equality_graph_generator(series['Country'], get_votes_by_party,inner_donut_totals,get_annotations_marriage_equality, doublePie, series['Date'], legendDict = {'green':'Yes','red':'No','yellow':'Abstained','grey':'Absent'})
path = os.getcwd()+"\..\pngFiles\{0}.png".format(series['Country'])
path = path.replace("\\","/")
strHTML = "<img src='"+path+"' alt='"+series['Date']+"'>"
else:
strHTML = strHTML = "<b>{0}</b>\n".format(series['Year'])
return strHTML |
Subsets and Splits