blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
0e5735b7e6c7038487a859e871f5133584916d40 | hyperion-mk2/git | /jumpgame1.py | 411 | 3.5625 | 4 | class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
l=len(nums)
s=0
for i in range(l):
s=max(s,i+nums[i])
if s>=(l-1):
return True
if i==s:
break
return False
if __name__ == '__main__':
print(Solution.canJump(Solution,[2,3,1,1,4])) |
8379d21b7aa4c339107ecab50ec35f04df582a41 | rainly/scripts-1 | /cpp2nd/e9-2.py | 296 | 3.8125 | 4 | def ex9_2():
'''
print the first N lines of file
'''
filename = raw_input('pls enter your filename:')
num = int(raw_input('how many lines do you want print:'))
f = open(filename)
index = 0
while index < num:
print f.next(),
index +=1
f.close()
|
a554b9fe96ccabb6e234f5c1eb8b12b5ab467e8c | ericf149/Practice_Projects | /coin_toss.py | 425 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 20:13:04 2021
@author: Eric
"""
from math import factorial as fac
def binomial(n,k):
if k==0: return 1
Bino = fac(n) // fac(k) // fac(n-k)
return int(Bino)
prob = binomial(100,60) / 2**100
def coinProb(n,k):
sums = []
for i in range(k,n):
sums.append(binomial(n,i)*.5**k*.5**(n-k))
return sum(sums)
print(coinProb(100, 60))
print(prob) |
b57534de1517b308cf8ed9ae42eb6fd24c55127c | anshuldante/ai-ds-ml-practical | /essential-math-for-machine-learning-python-edition/Exercise Files/iteration1/trials.py | 398 | 4.1875 | 4 | import pandas as pd
import matplotlib.pyplot as plt
# Create a dataframe with an x column containing values from -10 to 10
df = pd.DataFrame ({'x': range(-10, 11)})
# Add a y column by applying the solved equation to x
df['y'] = (3*df['x'] - 4) / 2
#Display the dataframe
print(df)
plt.plot(df['x'], df['y'], color='brown', marker='o')
plt.xlabel('x')
plt.ylabel('y')
plt.grid()
plt.show()
df. |
292307d7151aff58c940e88402e18e3b961f7ceb | Inimesh/PythonPracticeExercises | /4 Function exercises/Ex_89.py | 1,673 | 4.3125 | 4 | ## A function that will capitalise letters, like in a predictive text app.
# The letters to be caapitalised: "i" with a space either side, the first
# character in the string and the first non-space character after ".", "!", or
# "?". The function returns the corrected string. Main() program reads the
# string, capitalises it using the function and displays the result. ##
def CapIt(string):
test_str = string
lowercase = "abcdefghijklmnopqrstuvwxyz"
uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# Capitalising a letter after ".", "!", or "?".
for i in range(0,len(test_str)):
if test_str[i] in ".!?":
# Looking for first letter after punctuation, and only capitalising
# if it is lowercase
for j in range(i,len(test_str)):
if test_str[j] in uppercase:
break
if test_str[j] in lowercase:
test_str = test_str[0:j] + test_str[j].upper() + test_str[j+1:]
break
# Capitalising first letter of string, same method as above
for i in range(0,len(test_str)):
if test_str[i] in uppercase:
break
if test_str[i] in lowercase:
test_str = test_str[0:i] + test_str[i].upper() + test_str[i+1:]
break
# Capitalising " i "
test_str = test_str.replace(" i ", " I ")
test_str = test_str.replace(" i.", " I.")
test_str = test_str.replace(" i?", " I?")
test_str = test_str.replace(" i!", " I!")
test_str = test_str.replace(" i,", " I,")
return test_str
def main():
string = input("Please enter a string: ")
print(CapIt(string))
main()
|
e5243092faee9e758b6b3d45d51e194ef4e9f843 | moontree/leetcode | /version1/1349_Maximum_Students_Taking_Exam.py | 4,417 | 3.6875 | 4 | """
=========================
Project -> File: leetcode -> 1349_Maximum_Students_Taking_Exam.py
Author: zhangchao
=========================
Given a m * n matrix seats that represent seats distributions in a classroom.
If a seat is broken, it is denoted by '#' character otherwise it is denoted by a '.' character.
Students can see the answers of those sitting next to the left, right, upper left and upper right,
but he cannot see the answers of the student sitting directly in front or behind him.
Return the maximum number of students that can take the exam together without any cheating being possible..
Students must be placed in seats in good condition.
Example 1:
Input:
seats = [
["#",".","#","#",".","#"],
[".","#","#","#","#","."],
["#",".","#","#",".","#"]
]
Output:
4
Explanation:
Teacher can place 4 students in available seats so they don't cheat on the exam.
Example 2:
Input:
seats = [
[".","#"],
["#","#"],
["#","."],
["#","#"],
[".","#"]
]
Output:
3
Explanation:
Place all students in available seats.
Example 3:
Input: seats = [
["#",".",".",".","#"],
[".","#",".","#","."],
[".",".","#",".","."],
[".","#",".","#","."],
["#",".",".",".","#"]
]
Output:
10
Explanation:
Place students in available seats in column 1, 3 and 5.
Constraints:
seats contains only characters '.' and '#'.
m == seats.length
n == seats[i].length
1 <= m <= 8
1 <= n <= 8
"""
class Solution(object):
def maxStudents(self, seats):
"""
:type seats: List[List[str]]
:rtype: int
"""
r, c = len(seats), len(seats[0])
n = 2 ** c
counts = []
valid = [True for _ in range(n)]
for i in range(n):
res = 0
k = i
prev = None
while k:
res += k % 2
if k % 2 == prev == 1:
valid[i] = False
prev = k % 2
k /= 2
counts.append(res)
# print valid
previous_num = [0 for _ in range(n)]
for row in seats:
available = 0
dp = [0 for _ in range(n)]
for cc in row:
if cc == '.':
available = available * 2 + 1
else:
available = available * 2
for cur_status in range(n):
if not valid[cur_status]:
continue
if cur_status & available != cur_status:
dp[cur_status] = 0
else:
for last_status in range(n):
if valid[last_status] and cur_status & (last_status << 1) == 0 and cur_status & (last_status >> 1) == 0:
dp[cur_status] = max(dp[cur_status], previous_num[last_status] + counts[cur_status])
previous_num = dp
# print previous_num
return max(previous_num)
examples = [
{
"input": {
"seats": [
["#", ".", "#", "#", ".", "#"],
[".", "#", "#", "#", "#", "."],
["#", ".", "#", "#", ".", "#"]
]
},
"output": 4
}, {
"input": {
"seats": [
[".", "#"],
["#", "#"],
["#", "."],
["#", "#"],
[".", "#"]
]
},
"output": 3
}, {
"input": {
"seats": [
["#", ".", ".", ".", "#"],
[".", "#", ".", "#", "."],
[".", ".", "#", ".", "."],
[".", "#", ".", "#", "."],
["#", ".", ".", ".", "#"]
]
},
"output": 10
}, {
"input": {
"seats": [
["#", ".", "#"],
["#", "#", "."],
[".", "#", "."]
]
},
"output": 3
},
]
import time
if __name__ == '__main__':
solution = Solution()
for n in dir(solution):
if not n.startswith('__'):
func = getattr(solution, n)
print(func)
for example in examples:
print '----------'
start = time.time()
v = func(**example['input'])
end = time.time()
print v, v == example['output'], end - start
|
b22320e352ec7e2a27922b7b40100b551c2b4490 | ww35133634/chenxusheng | /ITcoach/xlrd_xlwt处理数据/第9章 Python函数技术/9.6 匿名函数写法及应用/9.6.1.py | 624 | 3.5625 | 4 | # d=lambda :'test'
# print(d())
# print((lambda :'test')())
#
#
# d1=lambda x,y,z:x+y+z
# print(d1(3,5,6))
# print((lambda x,y,z:x+y+z)(54,2,13))
# d2=lambda x,y,z=100:x+y+z
# print(d2(y=200,x=600))
# print((lambda x,y,z=100:x+y+z)(34,23))
# d3=lambda x,*y:x(y)
# print(d3(sum,5,23,7,1))
# print((lambda x,*y:x(y))(len,34,4,2,436564,66))
# d4=lambda x,**y:[(n,m(x)) for n,m in y.items()]
# print(d4([43,23,3,2,35],求和=sum,最大=max,最小=min))
# print((lambda x,**y:[(n,m(x)) for n,m in y.items()])([43,23,3,2,35],求和=sum,最大=max,最小=min))
# d5=lambda x,y: '成功' if x>y else '失败'
# print(d5(16,9))
|
ee00ebd9d4c7e1dfeb5bc47a4c9a3bce9363e836 | djpandit007/mini-metro | /station.py | 372 | 3.59375 | 4 | from enum import Enum, unique
@unique
class ShapeEnum(Enum):
CIRCLE = 1
SQUARE = 2
TRIANGLE = 3
class Station(object):
def __init__(self, shape):
try:
self.shape = ShapeEnum[shape.upper()]
except KeyError:
print("Shape '" + shape + "' not found in ShapeEnum")
def get_shape(self):
return self.shape
|
0a0b64ac70a00289ad3b31eaddf4d236c20a0279 | jiangjiane/Python | /pythonpy/third_xiti3.py | 291 | 3.921875 | 4 | #第三部分习题
#第三题
D={'a':1,'b':2,'c':3,'d':4,'e':5}
print('origin D: ',D,'\n')
Ks=list(D.keys())
Ks.sort()
print('sort D: ')
for k in Ks:print(k,D[k])
print('\n')
print('sorted D: ')
ks=D.keys()
for k in sorted(ks):print(k,D[k])
print('\n')
for k in sorted(D):print(k,D[k])
|
4fb862a1adda1daa3d3997e1d62a6088a81d2351 | p0leary/cs1301x | /5-2.py | 4,171 | 4.375 | 4 | #Write a function called string_search() that takes two
#parameters, a list of strings, and a string. This function
#should return a list of all the indices at which the
#string is found within the list.
# #
# #You may assume that you do not need to search inside the
# #items in the list; for examples:
# #
# # string_search(["bob", "burgers", "tina", "bob"], "bob")
# # -> [0,3]
# # string_search(["bob", "burgers", "tina", "bob"], "bae")
# # -> []
# # string_search(["bob", "bobby", "bob"])
# # -> [0, 2]
# #
# #Use a linear search algorithm to achieve this. Do not
# #use the list method index.
# #
# #Recall also that one benefit of Python's general leniency
# #with types is that algorithms written for integers easily
# #work for strings. In writing string_search(), make sure
# #it will work on integers as well -- we'll test it on
# #both.
# #Write your code here!
# def string_search(strList, str):
# locations = []
# for i in range(len(strList)):
# if strList[i] == str:
# locations.append(i)
# return locations
# #Feel free to add code below to test your function. You
# #can, for example, copy and print the test cases from
# #the instructions.
# print(string_search(['nope', 'nope', 'yeah', 'nope', 'yeah'], 'yeah'))
#Recall in Worked Example 5.2.5 that we showed you the code
#for two versions of binary_search: one using recursion, one
#using loops.
#
#In this problem, we want to implement a new version of
#binary_search, called binary_year_search. binary_year_search
#will take in two parameters: a list of instances of Date,
#and a year as an integer. It will return True if any date
#in the list occurred within that year, False if not.
#
#For example, imagine if listOfDates had three instances of
#date: one for January 1st 2016, one for January 1st 2017,
#and one for January 1st 2018. Then:
#
# binary_year_search(listOfDates, 2016) -> True
# binary_year_search(listOfDates, 2015) -> False
#
#You should not assume that the list is pre-sorted, but you
#should know that the sort() method works on lists of dates.
#
#Instances of the Date class have three attributes: year,
#month, and day. You can access them directly, you don't
#have to use getters (e.g. myDate.month will access the
#month of myDate).
#
#You may copy the code from Worked Example 5.2.5 and modify
#it instead of starting from scratch.
#
#Don't move this line:
from datetime import date
#Write your code here!
# V1 - Moving the index around a steady dateList. DONE and validated.
# def binary_year_search(dateList, searchYear):
# dateList.sort()
# maximum = len(dateList) - 1
# minimum = 0
# while maximum >= minimum:
# middle = minimum + ((maximum - minimum) // 2)
# # print('search year', searchYear)
# # print('min',minimum, dateList[minimum].year)
# # print('middle',middle, dateList[middle].year)
# # print('max',maximum, dateList[maximum].year, '\n')
# if dateList[middle].year == searchYear:
# return True
# elif dateList[middle].year > searchYear:
# maximum = middle - 1
# # repeat step 1
# elif dateList[middle].year < searchYear:
# # find new middle
# minimum = middle + 1
# # repeat step 1
# return False
#V2 - Modifying the dateList itself
def binary_year_search(dateList, searchYear):
dateList.sort()
while len(dateList) > 0:
middle = (len(dateList) - 1) // 2
# print('search year', searchYear)
# print(dateList)
if dateList[middle].year == searchYear:
return True
elif searchYear < dateList[middle].year:
dateList = dateList[:(middle - 1)]
elif searchYear > dateList[middle].year:
dateList = dateList[(middle + 1):]
return False
#The lines below will test your code. If it's working
#correctly, they will print True, then False, then True.
listOfDates = [date(2016, 11, 26), date(2014, 11, 29),
date(2008, 11, 29), date(2000, 11, 25),
date(1999, 11, 27), date(1998, 11, 28),
date(1990, 12, 1), date(1989, 12, 2),
date(1985, 11, 30)]
print(binary_year_search(listOfDates, 2016))
print(binary_year_search(listOfDates, 2007))
print(binary_year_search(listOfDates, 2008))
|
6a7f038240b615b16b63ebfef5e80fdd796ea4af | juandelima/Password-validation---Python | /password_validation.py | 2,086 | 3.65625 | 4 | #CREATED BY JUAN VALERIAN DELIMA
#the algorithm is made by juan
def create_lists(kata):
new_arr = []
for kata1 in kata:
for huruf in kata1:
new_arr.append(huruf)
return new_arr
def sorting_huruf(password):
arr = create_lists(password)
for index in range(1, len(password)):
current_word = arr[index]
index_huruf = index
while index_huruf > 0 and arr[index_huruf - 1] > current_word:
arr[index_huruf] = arr[index_huruf - 1]
index_huruf -= 1
arr[index_huruf] = current_word
return arr
def pencarian_huruf(password, cari): #teknik rekursif
arr = sorting_huruf(password)
if len(arr) == 0:
return False
else:
split_word = len(arr) // 2
if arr[split_word ] == cari:
return True
else:
if cari < arr[split_word]:
return pencarian_huruf(arr[:split_word], cari)
else:
return pencarian_huruf(arr[split_word + 1:], cari)
def cek_kata(password):
words = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz "
lists_wrd = create_lists(words)
check = False
for word in range(len(lists_wrd)):
if pencarian_huruf(password, lists_wrd[word]) != check:
check = True
return check
def cek_angka(password):
numbers = "0123456789"
list_num = create_lists(numbers)
check = False
for angka in range(len(list_num)):
if pencarian_huruf(password, list_num[angka]) != check:
check = True
return check
def program_utama():
while True:
password = input("Masukkan Password : ")
if len(password) < 6:
print("Panjang password harus lebih dari 6!")
continue
else:
if cek_kata(password) and cek_angka(password):
print("Password Valid!")
coba = input("Ulangi Program ? Y/N : ")
if coba == 'Y' or coba == 'y':
continue
else:
if coba == 'N' or coba == 'n':
break
else:
print("Password Tidak Valid!")
program_utama()
|
3aa0552dc1a61f5422a2acbb85009d49a575e772 | jlouiss/CS50 | /pset7/houses/roster.py | 607 | 3.65625 | 4 | from sys import argv, exit
import cs50
def main():
if (len(argv) != 2):
exit(1)
db = cs50.SQL("sqlite:///students.db")
result = db.execute("SELECT first, middle, last, birth FROM students WHERE house = ? ORDER BY last, first", argv[1])
for student in result:
first = student["first"]
middle = student["middle"] if student["middle"] != "NULL" else ""
last = student["last"]
birth = student["birth"]
print(first, end="")
if middle:
print(f" {middle}", end="")
print(f" {last}, born {birth}")
exit(0)
main() |
f589fc4c9761b52ad16487580a8b5975c39ed4b8 | wmy-one/python-project | /variableDemo.py | 608 | 4.09375 | 4 | # -*- coding:utf-8 -*-
#python语言的变量使用
'''
python语言的变量不用声明数据类型,可以直接赋值,既,给变量赋什么类型的数据,
变量的数据类型就是什么数据类型;赋值后,python的变量指向该数据所在内存单元的地址,
当重新给变量赋值时,该变量又指向了新的数据所在的内存单元的地址。可以使用id()函数
查看变量指向的内存单元的地址
'''
a = 12
b = 13
print 'a= ',a, id(a)
print 'b= ',b, id(b)
a=b
print 'a= ',a, id(a)
print 'b= ',b, id(b)
a=15
b=16
print 'a= ',a,id(a)
print 'b= ',b,id(b) |
38821832b76a0efa68b5b48b0176ed767cc25e4e | chjlarson/PythonPractice | /Arrays/ArrayPairSum/pairSum.py | 800 | 3.78125 | 4 | # Given an integer array, output all the unique pairs that sum up to a specific value K.
def pairSum(arr, k):
# Return if the length of the array is less than 2
# Edge case
if len(arr) < 2:
return
# Sets for tracking
seen = set()
output = set()
for num in arr:
# Looking for this value
target = k - num
# If the target isn't in the seen set, add it
# Otherwse, return the lowest value(num or target) and the
# highest value(num or target)
if target not in seen:
seen.add(num)
else:
output.add((min(num, target)), (max(num, target)))
# Map the list of the output to strings
print '\n'.join(map(str, list(output)))
|
28139eefa5ca456be8a2f4c0bc6454509e53ffa0 | N-eeraj/perfect_plan_b | /in_list_for.py | 175 | 3.9375 | 4 | import read
lst = read.ReadList()
key = read.Read(str, 'Key to Search')
for i in lst:
if i == key:
print(key, 'is in the list')
exit()
print(key, 'is not in the list')
|
4f0c115c9ced0b927829d3c9c0b1f4c364607cc1 | vansh-kapila/DSA_Class_Codes | /python/selectionSort.py | 384 | 3.78125 | 4 | if __name__=="__main__":
n = int(input("Enter the size of the array -> "))
arr=list(map(int,input("Enter the elements -> ").strip().split()))
print("Before sorting ->",arr)
for i in range(n):
idx=i
for j in range(i,n):
if arr[j]<arr[idx]:
idx=j
arr[i],arr[idx]=arr[idx],arr[i]
print("After sorting ->",arr)
|
1e3789c0183bca06b8d8091e830b449a4d55e375 | Aftabkhan2055/Machine_Learning | /python1/od.py | 131 | 3.65625 | 4 | n=int(input("enter the no"))
i=1
while i<=20:
print("table",n,"*",i,"=",n*i)
i=i+1
|
a8202dcf57405eae7d017617f40887be331f39ab | fbarenys/Frogger-git | /Cars.py | 1,577 | 3.703125 | 4 | from tkinter import *
class Vehicle:
def __init__(self, x, y, speed=5):
self.x = x
self.y = y
self.speed = speed
def move(self):
self.x+=self.speed
def stopMove(self):
self.x=self.x
class Car(Vehicle):
width=30
height=20
def __init__(self,x,y,speed=5):
super().__init__(x,y,speed)
#self.x=x
#self.y=y
#self.speed=speed
#self.width=30
def draw(self,w):
if self.speed>=0:
w.create_rectangle(self.x, self.y, self.x + self.width, self.y + self.height,fill="white")
w.create_line(self.x + self.width * 0.75, self.y , self.x + self.width * 0.75, self.y+self.height)
else:
w.create_rectangle(self.x, self.y, self.x + self.width, self.y + self.height,fill="yellow")
w.create_line(self.x + self.width * 0.25, self.y, self.x + self.width * 0.25, self.y + self.height)
class Lorry(Vehicle):
width = 60
height = 20
def __init__(self, x, y, speed=5):
super().__init__(x, y, speed) #java-> super(...)
def draw(self, w):
if self.speed >= 0:
w.create_rectangle(self.x, self.y, self.x + self.width, self.y + self.height,fill="white")
w.create_line(self.x + self.width * 0.80, self.y, self.x + self.width * 0.80, self.y + self.height)
else:
w.create_rectangle(self.x, self.y, self.x + self.width, self.y + self.height,fill="yellow")
w.create_line(self.x + self.width * 0.2, self.y, self.x + self.width * 0.20, self.y + self.height)
|
d746560e8bfb227e3b1c671637479daaa75a5ff6 | EMI322585/ILZE_course | /PYTHON/oop.py | 1,311 | 3.8125 | 4 | from datetime import datetime
class BasketballPlayer:
def __init__(self, first_name, last_name, height_cm, weight_kg, points, rebounds, assists):
self.first_name = first_name
self.last_name = last_name
self.height_cm = height_cm
self.weight_kg = weight_kg
self.points = points
self.rebounds = rebounds
self.assists = assists
def weight_to_lbs(self):
pounds = self.weight_kg * 2.20462262
return pounds
lebron = BasketballPlayer(first_name="Lebron", last_name="James", height_cm=203, weight_kg=113, points=27.2, rebounds=7.4, assists=7.2)
kev_dur = BasketballPlayer(first_name="Kevin", last_name="Durant", height_cm=210, weight_kg=108, points=27.2, rebounds=7.1, assists=4)
print(lebron)
'''class Human:
def __init__(self,name,birth_year):
self.full_name = name
self.year_of_the_birth = birth_year
def age(self, check_year=None):
if not check_year:
now = datetime.now()
check_year = now.year
return check_year - self.year_of_the_birth
janis = Human("Jānis", 1984)
anna = Human("Anna", 2000)
draugi = [janis, anna]
for draugs in draugi:
print("{} age is {}".format(full_name, draugs.age()))
print("{} age in 2035 will be {}".format(draugs.age(2035)))
''' |
ab7179425d164a7021c3a7ae8e935860a9972ff5 | Raushan-Raj2552/URI-solution | /2143.py | 244 | 3.796875 | 4 | while True:
a = int(input())
if a == 0 :
break
if a > 0 :
for i in range(a):
b = int(input())
if b%2 == 0:
print(2*b-2)
else:
print(2*b-1) |
4a54e9e0d69feefe825c8736bb44b7ba2cb99ba9 | DrewStock/python-intro | /00_python_class/PythonClass_DaysAlive.py | 497 | 4 | 4 | Name = raw_input ('Name: ')
print "Hello " + Name + "! We are going to find out how long you have been alive!"
Age = int(raw_input('How old are you?: '))
print "You are " + str(Age) + " years old."
Months = Age * 12
# 12 is the number of months in a year
Days = Age * 365
# 365 is the number of days in a year
print Name + " has been alive for about: " + str(Months) + " months and " + str(Days) + " days!"
# Hint: there are 525948 minutes in a year and 31556926 seconds in a year.
|
7586b227b2e3892b5df73bfadf37d9e6fc110ead | phelpsh/pythonQs | /elements.py | 2,385 | 4.34375 | 4 | # Find the element in a singly linked list that's m elements from the end.
# For example, if a linked list has 5 elements, the 3rd element from the end
# is the 3rd element.
# The function definition should look like question5(ll, m),
# where ll is the first node of a linked list and m is the "mth number from the end".
# You should copy/paste the Node class below to use as a representation of a node in
# the linked list. Return the value of the node at that position.
class Node(object):
def __init__(self, data, position, next_node=None):
self.data = data
self.next_node = next_node # first node in list has nothing to point at
self.position = position
def get_data(self):
return self.data
def get_next(self):
return self.next_node
def set_next(self, new_next):
self.next_node = new_next
def set_position(self, position):
self.position = position
# See more at: https://www.codefellows.org/blog/implementing-a-singly-linked-list-in-python/#sthash.OSXodfIP.dpuf
# a linked list is a string of nodes, sort of like a string of pearls,
# with each node containing both data and a reference to the next node
# in the list
class LinkedList:
def __init__(self, head = None):
self.head = head
def add_node(self, data, position = 0):
new_node = Node(data, position) # create a new node
if not self.head is None:
newpos = self.head.position + 1
new_node.set_position(newpos)
new_node.set_next(self.head) # link the new node to the 'previous' node.
self.head = new_node # set the current node to the new one.
def size(self):
current = self.head
count = 0
while current != None:
count += 1
current = current.get_next()
return count
def index(self, item):
current = self.head
while current != None:
if current.position == item:
return current.get_data()
else:
current = current.get_next()
print ("An error has occurred.")
# Function to get the nth node from the last of a linked list
# build a sample list
ll = LinkedList()
ll.add_node(9)
ll.add_node(122)
ll.add_node(1333)
ll.add_node(85555)
ll.add_node(45555)
m = 3
def Question5(ll, m):
print ll.index(m)
Question5(ll, m) |
5c0984cc0b0a40f72149458f3ac64e11e1f7080b | LEXW3B/PYTHON | /python/exercicios mundo 1/ex005/ex007.py | 516 | 4.25 | 4 | #faça um programa que leia uma frase pelo teclado e mostre.(quantas vezes aparece a letra 'a'),(em que posição aparece a primeira vez),(em que posição ela aparece a ultima vez).
frase = str(input('digite uma frase: ')).upper().strip()
print('a letra A aparece {} vezes na frase'.format(frase.count('A')))
print('a primeira letra A apareceu na posição {}'.format(frase.find('A')+1))
print('a letra A apareceu pela ultima vez na posição {}'.format(frase.rfind('A')+1))
#FIM//A\\
|
f35633d99c0b3f1be15fbb829d30d8d5fba0a801 | shrewdmaiden/Clue | /Rooms/Rooms.py | 2,263 | 4.25 | 4 | __author__ = 'gregory'
class Room(object):
'''All rooms have greeting, instructions, direction_choice, direction instructions, room instructions, and room name.
Dictionary that lists direction and corresponding room.'''
current_room = ''
def __init__(self,room_name):
self.greeting = "You are now in the %s." % room_name
self.room_name = room_name
self.connecting_rooms = {}
def connect_rooms(self,connecting_rooms):
self.connecting_rooms.update(connecting_rooms)
def enter_room(self):
print(self.greeting)
def change_room(self):
print("There are " + str(len(self.connecting_rooms)) + " rooms connected to the " + self.room_name + ".")
for key, value in sorted(self.connecting_rooms.items()):
if key == 'trapdoor':
print("A secret " + str(key) + " leads to the " + value.room_name + ".")
else:
print("Door " + str(key) + " leads to the " + value.room_name + ".")
dir_choice = raw_input("Choose your door: ")
while dir_choice not in self.connecting_rooms:
dir_choice = raw_input("Choose a door from the list: ")
for key, value in self.connecting_rooms.items():
if dir_choice == key:
return value
def current_room(self):
return self
Hallway = Room("Hallway")
Ballroom = Room("Ballroom")
Library = Room("Library")
Lounge = Room("Lounge")
Conservatory = Room("Conservatory")
Kitchen = Room("Kitchen")
Dining_Room = Room("Dining Room")
Billiard_Room = Room("Billiard Room")
Study = Room("Study")
Hallway.connect_rooms({'1':Ballroom,'trapdoor':Study})
Ballroom.connect_rooms({'1':Library,'2':Dining_Room,'3':Lounge,'4':Hallway})
Library.connect_rooms({'1':Lounge, '2':Study,'3':Ballroom})
Study.connect_rooms({'1':Library, '2':Billiard_Room, 'trapdoor':Hallway})
Billiard_Room.connect_rooms({'1':Conservatory, '2':Lounge, '3':Study})
Lounge.connect_rooms({'1':Billiard_Room,'2':Library, '3': Conservatory, '4':Ballroom})
Conservatory.connect_rooms({'1':Lounge,'2':Billiard_Room,'trapdoor':Kitchen})
Dining_Room.connect_rooms({"1":Kitchen, "2":Ballroom})
Kitchen.connect_rooms({"1":Dining_Room,"trapdoor":Conservatory})
start = Hallway
|
57d56f035ad8ff0917702f10cb08387acaf40fb8 | rafaelperazzo/programacao-web | /moodledata/vpl_data/31/usersdata/132/9653/submittedfiles/atividade.py | 305 | 3.71875 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
n=input('digite a quantidade de pontos:')
i=1
while(i<=n):
x=input(' digite o valor de x:')
y=input(' digite o valor de y:')
if x>=0 and y>=0 and x**2+y**2<=1:
print('SIM')
else:
print('NAO')
i=i+1 |
7dd00f700ba8abfa77321e8f53f97bf8d95565ef | bgbutler/PythonScripts | /Exercises/soundsBalls.py | 3,229 | 3.546875 | 4 | # Sound
# Bouncing Sounds
# This program draws a ball that makes sounds when it bounces
# off the side of the canvas.
import simplegui
import math
import random
# Global Variables
canvas_width = 400
canvas_height = 400
sound_a = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/week7-bounce.m4a")
sound_b = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/week7-brrring.m4a")
sound_c = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/week7-button.m4a")
sounds = [sound_a, sound_b, sound_c]
sound_index = 0
# Classes
class Ball:
def __init__(self, radius, color, bounds, sound):
self.radius = radius
self.pos = [bounds[0] // 2, bounds[1] // 2]
self.vel = self.get_random_vel()
self.color = color
self.bounds = bounds
self.sound = sound
# Draws the ball. Does not perform calculations
# or checks.
def draw(self, canvas):
canvas.draw_circle(self.pos, self.radius, 2, "White", self.color)
# Updates the position of the ball. If the ball goes
# out of bounds, its velocity is reversed and its
# current sound is rewound and played.
def update(self):
self.pos[0] += self.vel[0]
self.pos[1] += self.vel[1]
# Collision check and logic
if self.pos[0] - self.radius < 0 or self.pos[0] + self.radius > self.bounds[0]:
self.vel[0] = self.vel[0] * -1
# Rewinds and plays the sound.
self.sound.rewind()
self.sound.play()
if self.pos[1] - self.radius < 0 or self.pos[1] + self.radius > self.bounds[1]:
self.vel[1] = self.vel[1] * -1
# Rewinds and plays the sound.
self.sound.rewind()
self.sound.play()
def get_random_vel(self):
magnitude = random.random() * 3 + 2
angle = random.random() * (math.pi * 2)
return [magnitude * math.cos(angle), magnitude * math.sin(angle)]
# Sets the sound that the ball uses
def set_sound(self, s):
self.sound = s
def reset(self):
self.pos = [self.bounds[0] // 2, self.bounds[1] // 2]
self.vel = self.get_random_vel()
# Creating Class Instances
ball = Ball(25, "Red", [canvas_width, canvas_height], sounds[sound_index])
# Helper Functions
# Re-assigns the ball's sound based on the
# new sound_index
def change_sound(sign):
global sound_index
sound_index = (sound_index + sign) % len(sounds)
ball.set_sound(sounds[sound_index])
# Event Handlers
def draw(canvas):
ball.update()
ball.draw(canvas)
def keydown_handler(key):
if key == simplegui.KEY_MAP["left"]:
change_sound(-1)
elif key == simplegui.KEY_MAP["right"]:
change_sound(1)
def reset():
ball.reset()
# Frame and Timer
frame = simplegui.create_frame("Bouncing Sounds", canvas_width, canvas_height)
# Register Event Handlers
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown_handler)
frame.add_button("Reset", reset)
frame.add_label("Use the left and right arrow keys to change the sound!")
# Start
frame.start() |
91921a01967dd9dfe2d7e1a97e5b344e67d78e1f | loveplay1983/python_study | /21_oop/class_instance/class_method/pets/pets.py | 521 | 4.09375 | 4 | class Pets:
"""
The following code will cause problem when calling about()
method since python interpreter cannot distinguish which
class instance is about to call.
The correct version can be done by classmethod
"""
name = 'Pets name'
@staticmethod
def about():
print('This is {}'.format(Pets.name))
@classmethod
def info(cls):
print('This is {}'.format(cls.name))
class Dogs(Pets):
name = 'Doggy'
class Cats(Pets):
name = 'Catty'
|
e2bcdec61e0812a8c6abffb2b31072161ae2cf88 | spongebob03/Playground | /baekjoon/Bronze/b_10947.py | 172 | 3.78125 | 4 | import random
lotto=list()
for i in range(0,6):
r=random.randrange(1,45)
if r not in lotto:
lotto.append(r)
for i in lotto:
print(i,end=' ')
|
3d29aec9fdbc5c1aa7844a528c04f95d7b3c10ae | Luciana1012/Intech | /Term 5 - algorythms/Testing.py | 3,662 | 4.40625 | 4 | import unittest
def sum(array):
"""
This function will display the sum of all elements added together.
Input: array (list) array of numbers
Output: return the sum of all numbers in array.
"""
sumValue = 0
for element in range(0,len(array)):
sumValue += array[element]
return sumValue
#The range() function returns a sequence of numbers, starting from 0 by default,
# and increments by 1 (by default), and stops before a specified number.
#range(start -OPTIONAL, stop BEFORE -REQUIRED, stepINCREMENTATION PARAMETER -OPTIONAL)
class Test1 (unittest.TestCase): #This can be any name!!
def testcasefirst(self): #This can be any name!!
#a = 80
#self.assertTrue(a, 80)
#b = "testing"
#self.assertFalse(a, b)
#using self.assertXXXX() write:
#assign the value 80 to variable called "a", test that a is equal to 80
#assign the value "testing" to variable called "b", test that b is not equal to a
# assign tha array [1,2,3,4] to variable "c" and [2,3,4] to variable "d"
# test that c is not equal to d
# test that second element of C is equal to first element of d
# test that last element of c is equal to last element of d
# assign the array [1,2,3,4] to a variable "e", test that c is equal to e
#pass
#self.assertEquals(3, 4)
#EXAMPLE ONLY!!
#self.assertTrue(item1 == item2) or (item1 != item2)
#self.assertFalse(item1 == item2) or (item1 != item2)
#self.assertEquals(item1, item2) <----- (item1 == item2)
#self.assertTrue(sum([1,3,5,7]), 16)
#self.assertEquals(sum([1,3,5,7]) == 16)
#self.assertFalse(sum([1,3,5,7]) != 16)
#self.assertEquals(sum([2,4,6,8]), 20)
#self.assertTrue(sum([10,50,30,10]) == 100)
#unittest.main()
a = 80
self.assertTrue(a == 80)
b = "testing"
self.assertFalse(a == b)
c = [1,2,3,4]
d = [2,3,4]
self.assertFalse(c == d)
self.assertEquals(c[1], d[0])
self.assertEquals(c[-1], d[-1])
e = [1,2,3,4]
self.assertEquals(c, e)
def testSumFunction(self):
array = [1,3,5,7]
self.assertEquals(sum(array), 16)
self.assertEquals(sum([2,4,6,8]), 20)
self.assertEquals(sum([10,50,30,10]), 100)
unittest.main()
def calculateTax(income):
"""
This function calculate tax value based on income bracket.
Those income between 0 and 10,000 will pay 0%
10,001 - 40,000 will pay 5%
40,001 - 50,000 will pay 10%
50,001 - 70,000 will pay 15%
above 70,000 will pay 20%
Input: income (int)
Output: return the amount of tax needs to be paid
"""
if (income > 0 and income <= 10000) or (income <= 0):
return 0
elif income > 10000 and income <= 40000:
return 0.05 * income
elif income > 40000 and income <= 70000:
return 0.1 * income
elif income > 70000 and income <= 100000:
return 0.15 * income
else:
return 0.2 * income
class Test1 (unittest.TestCase):
def testcasefirst(self):
self.assertTrue(calculateTax(5000) == 0)
self.assertEquals(calculateTax(10000), 0)
self.assertTrue(calculateTax(17000) == 850)
self.assertTrue(calculateTax(40000) == 2000)
self.assertEquals(calculateTax(-1000), 0)
self.assertTrue(calculateTax(0) == 0)
self.assertTrue(calculateTax(-40000) == 0)
unittest.main() |
7cbb29af35d5df3e29b4e8994fa50743146ebf84 | deft727/FlaskRestApiWithETL-script | /script.py | 988 | 3.5 | 4 | import requests
import json
import sqlite3
with sqlite3.connect("mydatabase.db") as conn:
cur = conn.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
first_name TEXT,
last_name TEXT)'''
)
count=0
while count!=100:
url= requests.get('https://randomuser.me/api/')
if url.status_code==503:
url= requests.get('https://randomuser.me/api/')
if url.status_code!=503:
data=url.json()
else:
url= requests.get('https://randomuser.me/api/')
else:
data=url.json()
for i in data['results']:
if i['gender']=='male':
count+=1
print(i['name']['first'],count)
first_name=i['name']['first']
last_name=i['name']['last']
with conn:
cur = conn.cursor()
cur.execute("INSERT INTO users VALUES (NULL,?,?)",(first_name, last_name))
|
482a380dcf09d4d3e29565a27299cc38cdcdafce | kzeidlere/patstavigie-darbi | /patstavigais_darbs_2/main.py | 1,190 | 4.3125 | 4 | import random
wins = 0
loses = 0
while wins < 3 and loses < 3:
computer_choice = random.randint(1, 3)
if computer_choice == 1:
computer_turn = 'Rock'
elif computer_choice == 2:
computer_turn = 'Paper'
elif computer_choice == 3:
computer_turn = 'Scissors'
print('Enter 1 for rock, 2 for paper, 3 for scissors,')
user_choice = int(input('Your turn: '))
if user_choice == 1:
user_turn = 'Rock'
elif user_choice == 2:
user_turn = 'Paper'
elif user_choice == 3:
user_turn = 'Scissors'
print(f"{user_turn} vs. {computer_turn}")
user_wins = user_turn == 'Rock' and computer_turn == 'Scissors' or\
user_turn == 'Scissors' and computer_turn == 'Paper' or\
user_turn == 'Paper' and computer_turn == 'Rock'
if user_wins:
print("User wins this round")
wins += 1
elif user_turn == computer_turn:
print("Draw")
else:
print("Computer wins this round")
loses += 1
print(f"{wins}:{loses}")
if wins == 3:
print('Player wins!')
break
if loses == 3:
print('Computer wins!')
break
|
0e99ca72b873dca476964849dfc825f4726abedd | khanmaster/oop_4_pillars | /python.py | 411 | 3.59375 | 4 | from snake import Snake
class Python(Snake):
def __init__(self):
super().__init__()
self.large = True
self.lungs = True
def _change_skin(self): # hidden methods are created by using _
return " python sheds skin while growing up"
cobra = Python()
print(Python._change_skin(self=""))
#print(cobra)
#print(cobra.run)#
#print(cobra.breathe())
# print(cobra.change_skin()) |
35c9398f8db843fef05a0867e48e70242b4c7ff9 | Jasonzy1015/python-5 | /爬虫/Include/spider入门1/endecode.py | 211 | 3.546875 | 4 | #编码解吗模块
import urllib.request as urllib2
import urllib.parse
word={"name":"张三"}
word2=urllib.parse.urlencode(word)#编码操作
print(word2)
word3=urllib2.unquote(word2)#解吗操作
print(word3) |
a57b54748c0aab780dd02805ff39be7ed157b05f | JennieOhyoung/interview_practice | /rpn_evaluator.py | 2,548 | 4.0625 | 4 |
"""
Implement a RPN evaluator. It should be able to evaluate the following strings and answer with the corresponding numbers:
"1 2 +" = 3
"4 2 /" = 2
"2 3 4 + *" = 14
"3 4 + 5 6 + *" = 77
"13 4 -" = 9
And should provide an error message for the following types of errors
"1 +" (not enough arguments)
"a b +" (invalid number)
We should be able to evaluate a string from the command line in the following way:
$ python rpn.py "1 2 +"
In addition, implement your own string to number conversion function and use it in your RPN evaluator. Do not use any built-in method to convert your strings to numbers in your RPN evaluator.
"""
import sys
class Stack(object):
def __init__(self):
self.items = []
def __str__(self):
return str(self.items)
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def isEmpty(self):
return self.items == []
def str_to_num(string):
int_list = []
final_num = 0
string_list = list(string)
for char in string_list:
if 48 <= ord(char) <= 57:
int_list.append(ord(char)-48)
else:
return False
for i in range(len(int_list)):
value = int_list[-i-1]
place = 10**i
final_num += value*place
return final_num
# helper function to perform operations
def math(operator, first_num, second_num):
if operator =="*":
return first_num*second_num
elif operator == "/":
return first_num/second_num
elif operator == "+":
return first_num+second_num
else:
return first_num-second_num
# separate operants from operators, call helper function on last two items on stack.
def postfix_evaluator(equation):
s = Stack()
# equation = (str(equation)).strip("[]'',")
for i in equation:
if i in "[]'',. ":
continue
elif i.isdigit():
s.push(str_to_num(i))
elif i in "+-*/":
second_num = s.pop()
if not s.isEmpty():
first_num = s.pop()
result = math(i, first_num, second_num)
s.push(result)
else:
return "Not enough arguments"
else:
return "Invalid number"
return s.pop()
if __name__ == "__main__":
# type(argv) = list
raw = sys.argv
# take out argv[0], tokenize
equation = ''.join(raw[1:]).split()
# call function to evaluate input equation
print postfix_evaluator(equation)
sys.exit(0)
|
b3942d4422a17c333e9c1a627e9988df8b578493 | zeyi1/Wallbreakers | /Week 1/Simple String Manipulation/validPalindrome.py | 985 | 4.03125 | 4 | """
Procedure:
Use two pointers (left, right) to point to the beginning and end of the string.
Loop until left >= right, at each iteration keep moving the pointers until they reach
an alphanumeric character and making sure left < right holds true.
If the character at left does not match the character at right, then it is not a palindrome.
Complexity:
n -> length of input string
Time: O(n)
Space: O(1)
"""
class Solution:
def isPalindrome(self, s: str) -> bool:
if not s or len(s) == 1:
return True
left, right = 0, len(s) - 1
while left < right:
while not s[left].isalnum() and left < right:
left += 1
while not s[right].isalnum() and left < right:
right -= 1
if s[left].lower() != s[right].lower():
return False
left, right = left + 1, right - 1
return True |
c5ad949fed9b52e1cf742c49cb8a7c326fae01ea | 15zhazhahe/LeetCode | /Python/111. Minimum Depth of Binary Tree.py | 1,240 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution1:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
ans = [-1]
def dfs(node, depth):
if node is None:
ans[0] = 0
return
if node.left is None and node.right is None:
if ans[0] == -1:
ans[0] = depth + 1
else:
ans[0] = min(ans[0],depth + 1)
if node.left:
dfs(node.left, depth + 1)
if node.right:
dfs(node.right, depth + 1)
dfs(root, 0)
return ans[0]
class Solution2:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
if root.left and root.right:
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
elif root.left is None:
return self.minDepth(root.right) + 1
elif root.right is None:
return self.minDepth(root.left) + 1 |
f80c39565bd2f779f3cb22a8ec398411d93ddd0c | Cronvall/Calculator | /CalculatorGUI.py | 2,573 | 3.890625 | 4 | # package calculator
from tkinter import *
from Calculator import *
# A graphical user interface for the Calculator
#
# **** NOTHING TO DO HERE ****
class CalculatorGUI:
@staticmethod
def calculator_program():
gui = CalculatorGUI()
gui.start()
def __init__(self):
# create a GUI window
self.__gui = Tk()
self.__equation = StringVar()
def start(self):
self.__setup_gui_window()
self.__setup_expression_field()
self.__create_and_attach_buttons()
# start the GUI
self.__gui.mainloop()
# ----- Shhh, here be private methods ----
def __setup_expression_field(self):
expression_field = Entry(self.__gui, textvariable=self.__equation)
expression_field.grid(columnspan=5, ipadx=70)
def __setup_gui_window(self):
self.__gui.configure(background="cyan")
self.__gui.title("Simple Calculator")
self.__gui.geometry("290x130")
def __create_and_attach_buttons(self):
buttons = ["123+C", "456-^", "789*.", "(0)/="]
for row in range(len(buttons)):
for col in range(len(buttons[row])):
self.__create_and_attach_button(buttons[row][col], row, col)
def __create_and_attach_button(self, text, row, col):
button = self.__create_button(text)
button.grid(row=row+2, column=col)
def __create_button(self, text):
return Button(self.__gui, text=text, fg='black', bg='blue',
command=lambda: self.__handle_command(text), height=1, width=7)
# ---- Callback handlers for button presses ----
def __handle_command(self, button_pressed):
switcher = {
"C": self.__clear_equation,
"=": self.__evaluate_equation
}
cmd = switcher.get(button_pressed, lambda: self.__press(button_pressed))
cmd()
# Handle any button press that extends the current equation
def __press(self, txt):
new_txt = self.__equation.get() + txt
self.__equation.set(new_txt)
# Handle reset (C)
def __clear_equation(self):
self.__equation.set("")
# Handle evaluate (=)
def __evaluate_equation(self):
expression = self.__equation.get()
try:
result = eval_expr(expression)
self.__equation.set(str(result))
except ValueError as ve:
self.__equation.set(ve)
if __name__ == "__main__":
CalculatorGUI.calculator_program()
|
2347eff9af41d632c5f8557baba723950abcfd95 | yegeli/month2 | /day03/buffer.py | 365 | 3.65625 | 4 | """
缓冲区示例
"""
# f = open("file",'w') # 普通缓冲 常用
# f = open('file','w',1) # 行缓冲 换行自动刷新
f = open('file','wb',10) # 设置缓冲区为10字节
while True:
data = input(">>")
if not data:
# 直接回车结束循环
break
f.write(data.encode())
# f.flush() # 手动刷新缓冲
f.close() |
1537a8508d017b2b17d039640ab01e7050f2a21d | guyman575/CodeConnectsJacob | /semester1/lesson10/shapestuff.py | 1,470 | 4.125 | 4 | from abc import ABC, abstractmethod
from math import pi
# Shapes
# get the perimeter/circumfrence
# get the area
# print a summary of the shapes dimensions
class AbstractShape(ABC):
def __init__(self):
super().__init__()
@abstractmethod
def getPerimeter(self):
pass
@abstractmethod
def getArea(self):
pass
@abstractmethod
def dimensions(self):
pass
class Rectangle(AbstractShape):
def __init__(self,length,width):
super().__init__()
self.length = length
self.width = width
def getPerimeter(self):
permimeter = (self.length*2) + (self.width*2)
return permimeter
def getArea(self):
area = self.length * self.width
return area
def dimensions(self):
print(f"Rectangle with width {self.width} and length {self.length}")
class Circle(AbstractShape):
def __init__(self,radius):
super().__init__()
self.radius = radius
def getPerimeter(self):
perimeter = 2*pi*self.radius
return perimeter
def getArea(self):
area = pi*(self.radius**2) # or you can do math.pow(self.radius,2)
return area
def dimensions(self):
print (f"Circle with radius{self.radius}")
@property
def diameter(self):
return self.radius * 2
mycircle = Circle(10)
print(mycircle.getArea())
print(mycircle.getPerimeter())
print(mycircle.diameter) |
eaae0e4c728281050e69e82bd957f24e80fea651 | oldcast1e/Python | /Python Lecture/daily task/1.19/t2.py | 545 | 3.578125 | 4 | """ (두 자리 수) × (두 자리 수)는 다음과 같은 과정을 통하여 이루어진다.
8 3 (1)
x 7 4 (2)
--------
3 3 2 (3)
5 8 1 (4)
--------
6 1 4 2 (5)
(1)과 (2)위치에 들어갈 두 자리 자연수가 주어질 때
(3), (4), (5)위치에 들어갈 값을 구하는 프로그램을 작성하세요.
[입력예시]
83
74
[출력예시]
332
581
6142 """
n1 = int(input()) #83
n2 = int(input()) #74
R1 = n2%10 #4
R2 = n2//10 #7
a1 = n1*R1
a2 = n1*R2
a3 = n1*n2
print(a1)
print(a2)
print(a3)
|
79c1bd051741a236a5ee0bcca504fe953e5d4a36 | AndreySperansky/ALGORITHMS | /Lesson_4_examples/fibo_calc/fibo_recur_anoth_memo.py | 402 | 4 | 4 | """Фибо с рекурсией и упрощенной мемоизацией"""
import sys
import timeit
#sys.setrecursionlimit(10000)
#print(sys.getrecursionlimit())
def f(n, memory=[0, 1]):
if n < len(memory):
return memory[n]
else:
r = f(n-1) + f(n-2)
memory.append(r)
return r
n = 8
print(timeit.timeit("f(n)", setup="from __main__ import f, n"))
|
98af31b797f940f1363a87fc228a360252ed753e | justega247/python-scripting-for-system-administrators | /bin/exercises/exercise-3.py | 1,644 | 4.25 | 4 | #!/usr/bin/env python3.7
# Building on top of the conditional exercise, write a script that will loop through a list of users where each item
# is a user dictionary from the previous exercise printing out each user’s status on a separate line. Additionally,
# print the line number at the beginning of each line, starting with line 1. Be sure to include a variety of user
# configurations in the users list.
#
# User Keys:
#
# 'admin' - a boolean representing whether the user is an admin user.
# 'active' - a boolean representing whether the user is currently active.
# 'name' - a string that is the user’s name.
#
# Depending on the values of the user, print one of the following to the screen when you run the script.
#
# Print (ADMIN) followed by the user’s name if the user is an admin.
# Print ACTIVE - followed by the user’s name if the user is active.
# Print ACTIVE - (ADMIN) followed by the user’s name if the user is an admin and active.
# Print the user’s name if neither active nor an admin.
user_list = [
{'admin': True, 'active': True, 'name': 'Kevin'},
{'admin': False, 'active': True, 'name': 'Kingsley'},
{'admin': True, 'active': False, 'name': 'Kelechi'},
{'admin': False, 'active': False, 'name': 'Kess'}
]
def user_status(user):
prefix = ""
if user['admin'] and user['active']:
prefix = "ACTIVE - (ADMIN) "
elif user['admin']:
prefix = "(ADMIN) "
elif user['active']:
prefix = "ACTIVE - "
return prefix + user['name']
for index, person in enumerate(user_list, start=1):
print(f"{index} {user_status(person)}")
|
90b054d869d8ffff6bd0f5c2e45241001ecd8369 | fahad92virgo/deepy | /deepy/layers/chain.py | 1,899 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from layer import NeuralLayer
class Chain(NeuralLayer):
"""
Stack many layers to form a chain.
This is useful to reuse layers in a customized layer.
Usage:
As part of the main pipe line:
chain = Chain(layer1, layer2)
model.stack(chain)
As part of the computational graph:
chain = Chain(layer1, layer2)
y = chain.compute(x)
"""
def __init__(self, *layers):
super(Chain, self).__init__("chain")
self.layers = []
self._layers_to_stack = []
if len(layers) == 1 and type(layers[0]) == int:
# This is a deprecated using of Chain
self.input_dim = layers[0]
else:
self.stack(*layers)
def stack(self, *layers):
if self.input_dim is None or self.input_dim == 0:
# Don't know the input dimension until connect
self._layers_to_stack.extend(layers)
else:
self._register_layers(*layers)
return self
def _register_layers(self, *layers):
for layer in layers:
if not self.layers:
layer.initialize(self.input_dim)
else:
layer.initialize(self.layers[-1].output_dim)
self.layers.append(layer)
self.output_dim = layer.output_dim
self.register_inner_layers(*self.layers)
def prepare(self, *layers):
if self._layers_to_stack:
self._register_layers(*self._layers_to_stack)
self._layers_to_stack = []
def compute_tensor(self, x):
return self._output(x, False)
def compute_test_tesnor(self, x):
return self._output(x, True)
def _output(self, x, test):
y = x
for layer in self.layers:
y = layer.compute_flexible_tensor(y, test=test)
return y
|
3540563de662cf7273f422e38adb7781ae309115 | RyanKeys/Ableton-Voice | /voice_detection.py | 1,599 | 3.5 | 4 | import speech_recognition as sr
import autogui
import pyautogui
start_prompt = 'Ableton Voice V.1.0\nReady for a command:'
commands = ["test", 1, 1]
command_output = 'N/A'
# Creates an instance of Recognizer(), detects voice input
r = sr.Recognizer()
# receives audio from users first mic
mic = sr.Microphone()
with mic as source:
while True:
r.adjust_for_ambient_noise(source)
print(start_prompt)
try:
audio = r.listen(source)
audio_str = r.recognize_google(audio)
print(audio_str)
# Use if " " in audio_str to call code
if "record first track" in audio_str:
autogui.record_track_one()
# asks the user to create a command phrase and choose its x and y coordinates
elif "create a command" in audio_str:
phrase = str(input("Choose a command phrase:"))
mouse_x = int(input("Choose a X coordinate:"))
mouse_y = int(input("Choose a Y coordinate:"))
# create a command using autogui
command_output = autogui.create_command(
phrase, mouse_x, mouse_y)
elif 'show commands' in audio_str:
print(f"{commands}")
# command_phrase[0] == user's previously input str
elif command_output[0] in audio_str:
pyautogui.click(x=mouse_x, y=mouse_y,
clicks=1, duration=0)
else:
pass
except sr.UnknownValueError:
print("Say that again?")
|
8db08369e141d2d50282624394bee58fb7298200 | bartoszmaleta/3rd-Teamwork-week | /splitter_words.py | 214 | 4.1875 | 4 | my_string = 'ala ma kota'
my_string_splitted = my_string.split()
print(my_string_splitted)
for word in my_string_splitted:
print(word)
for word in my_string_splitted:
print(len(word), end=' ')
print() |
ee0d184417eba59c7db50597eb216abdd4e5153d | bnatunga/Algorithm | /summation.py | 245 | 3.796875 | 4 | #sums all the numbers between 1 and N (inclusive).
def sum_num(N):
sum_ = 0
for n in range(N + 1):
sum_ += n
return sum_
print(sum_num(15))
#Gauss summation rule
def sum_gauss(N):
return N*(N+1)//2
print(sum_gauss(15)) |
ae2bea8b5de4ab55beb25abce474015c118e62fc | nguyendaiky/CS114.L21 | /WeCode Assignments/Tuan 3.1/DuyetTheoChieuRong.py | 1,043 | 4.09375 | 4 |
class node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
def insertTree(self,val):
if self.data:
if val < self.data:
if not self.left:
self.left = node(val)
else:
self.left.insertTree(val)
elif self.data < val:
if not self.right:
self.right = node(val)
else:
self.right.insertTree(val)
else:
self.data = val
def printLevelOrder(root):
if root is None:
return
queue = []
queue.append(root)
while len(queue)>0:
print(queue[0].data, end=' ')
Root = queue.pop(0)
if Root.left is not None:
queue.append(Root.left)
if Root.right is not None:
queue.append(Root.right)
n = int(input())
root = node(n)
while True:
n = int(input())
if n == 0:
break
root.insertTree(n)
printLevelOrder(root) |
a7f4eef2b9c391dab85c0dd0433df4f214e07f9a | shuowoshishui/python100texts | /python 100texts/35.py | 390 | 3.71875 | 4 | """有一个已经排好序的数组,现输入一个数,要求按原来的规律将他插入到数组中。"""
if __name__ == '__main__':
a = [1, 2, 5, 6]
num = int(input("输入:"))
if num > a[len(a) - 1]:
a[len(a)] = num
else:
for i in range(len(a) - 1):
if num < a[i]:
a.insert(i, num)
break
print(a)
|
b0db5ed72b0b63835a095a2c297679109b51d2dc | yodigi7/kattis | /JuryJeopardy.py | 3,128 | 3.640625 | 4 | def outputMaze(maze):
for i in maze:
holder = ''
for j in i:
holder += j
print(holder)
holder = ''
def addBot(array):
width, height = getWidthHeight(array)
row = []
answer = []
answer.append(row)
for i in array:
answer.append(i)
for i in range(0, width):
row.append('#')
return answer
def addTop(array):
width, height = getWidthHeight(array)
row = []
answer = []
for i in range(0, width):
row.append('#')
answer.append(row)
for i in array:
answer.append(i)
return answer
def addRight(array):
width, height = getWidthHeight(array)
answer = []
row = []
for i in range(0, height):
for j in array[i]:
row.append(j)
row.append('#')
answer.append(row)
return answer
def addLeft(array):
width, height = getWidthHeight(array)
answer = []
row = []
for i in range(0, height):
row.append('#')
for j in array[i]:
row.append(j)
answer.append(row)
return answer
def getWidthHeight(maze):
height = len(maze)
width = len(maze[0])
return width, height
def getAddXY(direct, facing):
addX = addY = 0
if (facing == "right" and direct == 'F') or (facing == 'up' and direct == 'R') or (facing == 'left' and direct == 'B') or (facing == 'down' and direct == 'L'):
addX = 1
elif (facing == "right" and direct == 'L') or (facing == 'up' and direct == 'F') or (facing == 'left' and direct == 'R') or (facing == 'down' and direct == 'B'):
addY = -1
elif (facing == "right" and direct == 'B') or (facing == 'up' and direct == 'L') or (facing == 'left' and direct == 'F') or (facing == 'down' and direct == 'R'):
addX = -1
elif (facing == "right" and direct == 'R') or (facing == 'up' and direct == 'B') or (facing == 'left' and direct == 'L') or (facing == 'down' and direct == 'F'):
addY = 1
return addX, addY
def goToward(direct, x, y, facing, maze):
addX, addY = getAddXY(direct, facing)
width, height = getWidthHeight(maze)
if addX == 1 and x == width-1:
maze = addRight(maze)
elif addY == 1 and y == height-1:
maze = addBot(maze)
elif (addX == -1 and x == 0) or (addX == -1 and x == 1 and (x != entX or y != entY)):
maze = addLeft(maze)
x += 1
elif addY == -1 and y == 1:
maze = addTop(maze)
y += 1
outputMaze(maze)
maze[x][y] = '.'
return addX+x, addY+y, facing, maze
global entX
global entY
numCases = int(input())
for i in range(0, numCases):
entX = 0
entY = 1
maze = []
hashes = ['#','#','#']
midHashes = ['.','#','#']
maze.append(hashes)
maze.append(midHashes)
maze.append(hashes)
outputMaze(maze)
currX = 0
currY = 1
width = height = 3
facing = 'left'
directions = list(input())
for j in directions:
holder = goToward(j, currX, currY, facing, maze)
maze = holder[3]
currX = holder[0]
currY = holder[1]
facing = holder[2]
|
ed5a5c9cfba9ba40b18a5597d0495db44367ce6f | laxmanlax/My_python_practices | /leetcode/Problems/PalindromicSubstrings.py | 822 | 4.25 | 4 | """
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
"""
def countSubstrings(s):
count = 0
for i in range(len(s)):
count += helper(s, i, i)
count += helper(s, i, i+1)
return count
def helper(string , left, right):
inter_count = 0
while left >=0 and right < len(string) and string[left]==string[right]:
inter_count +=1
left -=1
right +=1
return inter_count
s="abc"
print countSubstrings(s)
|
ca07dc8237dabc45eb5646cb4073d214bb9d7212 | pangyouzhen/data-structure | /tree/199 rightSideView.py | 751 | 3.671875 | 4 | # Definition for a binary tree node.
from typing import List
from base.tree.tree_node import TreeNode
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
def collect(node, depth):
if node:
if depth == len(view):
view.append(node.val)
collect(node.right, depth + 1)
collect(node.left, depth + 1)
view = []
collect(root, 0)
return view
if __name__ == '__main__':
tree = TreeNode(1)
tree.left = TreeNode(2)
tree.left.right = TreeNode(5)
tree.right = TreeNode(3)
tree.right.right = TreeNode(4)
print(tree)
sol = Solution()
print(sol.rightSideView(tree))
|
d899f3f471bb956735551972976b03b976d707db | mcardosog/Hacker-Rank | /Minimum Loss | 1,293 | 3.5 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the minimumLoss function below.
class Tree:
def __init__(self,value):
self.leftChild = None
self.rightChild = None
self.value = value
def AddValue(self, value, minMaximum):
if value<self.value:
if self.leftChild==None:
self.leftChild = Tree(value)
else:
self.leftChild.AddValue(value, minMaximum)
else:
if value> self.value:
tempMinMaximum = value-self.value
if minMaximum[0] > tempMinMaximum:
minMaximum[0] = tempMinMaximum
if self.rightChild == None:
self.rightChild = Tree(value)
else:
self.rightChild.AddValue(value, minMaximum)
def minimumLoss(price):
mainTree = Tree( price[len(price)-1])
minMaximum = [max(price)]
for i in range(len(price)-2,-1,-1):
mainTree.AddValue(price[i],minMaximum)
return minMaximum[0]
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
price = list(map(int, input().rstrip().split()))
result = minimumLoss(price)
fptr.write(str(result) + '\n')
fptr.close()
|
459f7db2cc51233d6e45ab8718fab5a95468022b | Yaro1/Exercism-python | /anagram/anagram.py | 215 | 3.625 | 4 | from collections import Counter
def find_anagrams(word, candidates):
word_counter = Counter(word.lower())
return [i for i in candidates if Counter(i.lower()) == word_counter and word.lower() != i.lower()]
|
74bc3ad8ac73031cc66ea1e03b16359476ac1889 | Nikoolaid/summer2019connect4 | /finalFolder/wip.py | 11,709 | 3.703125 | 4 |
# Color of Playing Tiles
def chooseColor(player):
choose_color1 = str(input( player + ", what color do you want? \n"))
if choose_color1 == "white":
choose_color1 = str(input( player + ", please choose a different color: \n"))
return choose_color1
def mkBoard():
board = turtle.Turtle()
board.color('black')
board.speed(0)
board.penup()
board.goto(-500,-350)
board.pendown()
board.forward(900)
board.right(270)
board.forward(850)
board.right(270)
board.forward(900)
board.right(270)
board.forward(850)
board.penup()
board.goto(-505, -355)
board.pendown()
board.right(270)
board.forward(910)
board.right(270)
board.forward(860)
board.right(270)
board.forward(910)
board.right(270)
board.forward(860)
board.hideturtle()
def mkCirc():
#Circle Slots
#circle radius = 50
#space between circles = 25
#A1 = (-425, -250), B1 = (-300, -250)
sir = turtle.Turtle()
sir.color('black')
sir.speed(0)
sir.penup()
sir.goto(-425, -250)
sir.pendown()
for x in range(6):
for x in range(7):
sir.circle(50)
sir.penup()
sir.forward(125)
sir.pendown()
sir.penup()
sir.left(90)
sir.forward(125)
sir.left(90)
sir.forward(875)
sir.left(180)
sir.pendown()
sir.hideturtle()
label = turtle.Turtle()
label.speed(0)
label.penup()
label.goto(-525, -225)
label.left(90)
lis = [1, 2, 3, 4, 5, 6]
for x in lis:
label.pendown()
style = ('Courier', 15)
label.write(x, font=style, align='center')
label.penup()
label.forward(125)
label.penup()
label.goto(-425, -400)
label.right(90)
lis2 = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
for x in lis2:
label.pendown()
style = ('Courier', 15)
label.write(x, font=style, align='center')
label.penup()
label.forward(125)
label.hideturtle()
coordinates = {'1st column': (-490, -362.5), '2nd column' : (-362.5, -237.5), '3rd column': (-237.5, -112.5), '4th column': (-112.5, 12.5), '5th column': (12.5, 137.5), '6th column': (137.5, 262.5), '7th column': (262.5, 387.5)}
a = coordinates['1st column']
b = coordinates['2nd column']
c = coordinates['3rd column']
d = coordinates['4th column']
e = coordinates['5th column']
f = coordinates['6th column']
g = coordinates['7th column']
if (n > a[0] and n < a[1]):
return 1
elif (n > b[0] and n < b[1]):
return 2
elif (n > c[0] and n < c[1]):
return 3
elif (n > d[0] and n < d[1]):
return 4
elif (n > e[0] and n < e[1]):
return 5
elif (n > f[0] and n < f[1]):
return 6
elif (n > g[0] and n < g[1]):
return 7
def mkTxt():
#Board Text
screen = turtle.Screen()
turtle.penup()
turtle.goto(-50,-300)
turtle.pendown()
screen.register_shape("comic.gif")
image = "comic.gif"
screen.addshape(image)
turtle.shape(image)
#Credits
wright = turtle.Turtle()
wright.hideturtle()
wright.penup()
wright.goto(-50, -450)
wright.pendown()
style = ("Courier", 12)
wright.write("Made by Epic Gamers: ", font=style, align='center')
wright.penup()
wright.goto(-50, -475)
wright.pendown()
style = ("Courier", 12)
wright.write("Rucha B., Grace N., Alayna T., and Katriana T.", font=style, align='center')
wright.penup()
wright.goto(-50, -500)
wright.pendown()
style = ("Courier", 8)
wright.write("~ Getting kicked out of rooms since 2019 ~", font=style, align='center')
wright.penup()
def defPlayerCirc(chooseColor):
#Assigning variables to each circle
#Player 1 color = choose_color1
#Player 2 color = choose_color2
# Capital letter = turtle name
# Lowercase letter = circle variable
playerAcircles = turtle.Turtle()
playerAcircles.color(chooseColor, chooseColor)
playerAcircles.speed(0)
playerAcircles.hideturtle()
return playerAcircles
circles = {"a1": (-425, -250), "a2": (-425, -125), "a3": (-425, 0), "a4": (-425, 125), "a5": (-425, 250), "a6": (-425, 375),"b1": (-300, -250), "b2": (-300, -125), "b3": (-300, 0), "b4": (-300, 125), "b5": (-300, 250), "b6": (-300, 375),"c1": (-175, -250), "c2": (-175, -125), "c3": (-175, 0), "c4": (-175, 125), "c5": (-175, 250), "c6": (-175, 375),"d1": (-50, -250), "d2": (-50, -125), "d3": (-50, 0), "d4": (-50, 125), "d5": (-50, 250), "d6": (-50, 375),"e1": (75, -250), "e2": (75, -125), "e3": (75, 0), "e4": (75, 125), "e5": (75, 250), "e6": (75, 375),"f1": (200, -250), "f2": (200, -125), "f3": (200, 0), "f4": (200, 125), "f5": (200, 250), "f6": (200, 375),"g1": (325, -250), "g2": (325, -125), "g3": (325, 0), "g4": (325, 125), "g5": (325, 250), "g6": (325, 375)}
def defCoords():
#Defines lists and coordinates
count = 0
game_over = False
turn = 0
selection = 'z'
chosenColumn = 0
openSpaceA = ['a1','a2','a3','a4','a5','a6']
openSpaceB = ['b1','b2','b3','b4','b5','b6']
openSpaceC = ['c1','c2','c3','c4','c5','c6']
openSpaceD = ['d1','d2','d3','d4','d5','d6']
openSpaceE = ['e1','e2','e3','e4','e5','e6']
openSpaceF = ['f1','f2','f3','f4','f5','f6']
openSpaceG = ['g1','g2','g3','g4','g5','g6']
opena = [1,2,3,4,5,6]
openb = [1,2,3,4,5,6]
openc = [1,2,3,4,5,6]
opend = [1,2,3,4,5,6]
opene = [1,2,3,4,5,6]
openf = [1,2,3,4,5,6]
openg = [1,2,3,4,5,6]
'''
lista = [0:6]
listb = [6:12]
listc = [12:18]
listd = [18:24]
listee = [24:30]
listf = [30:36]
listg = [36:42]
'''
def drawCirc(playerCirc, goToCirc):
for selection in circles.values():
playerCirc.penup()
playerCirc.goto(circles[goToCirc]) #also has variable for which circle to color in
playerCirc.pendown()
playerCirc.begin_fill()
playerCirc.circle(50)
playerCirc.end_fill()
def returnFirstCircName(selection): # returns first open spot in vertical column. returns a1, a2, etc
if (selection == 1):
first = (opena[0] - 1)
return openSpaceA[first]
elif (selection == 2):
first = (openb[0] - 1)
return openSpaceB[first]
elif (selection == 3):
first = (openc[0] - 1)
return openSpaceC[first]
elif (selection == 4):
first = (opend[0] - 1)
return openSpaceD[first]
elif (selection == 5):
first = (opene[0] - 1)
return openSpaceE[first]
elif (selection == 6):
first = (openf[0] - 1)
return openSpaceF[first]
elif (selection == 7):
first = (openg[0] - 1)
return openSpaceG[first]
#return to me coord of new circle
def magic(selection):
if (selection == 1):
opena.pop(0)
elif (selection == 2):
openb.pop(0)
elif (selection == 3):
openc.pop(0)
elif (selection ==4):
opend.pop(0)
elif (selection == 5):
opene.pop(0)
elif (selection == 6):
openf.pop(0)
elif (selection == 7):
openg.pop(0)
#get mouse pos as list and return column its in
def clickyColumn(n):
if ((n > a[0]) and (n < a[1])):
return 1
elif ((n > b[0]) and (n < b[1])):
return 2
elif ((n > c[0]) and (n < c[1])):
return 3
elif ((n > d[0]) and (n < d[1])):
return 4
elif ((n > e[0]) and (n < e[1])):
return 5
elif ((n > f[0]) and (n < f[1])):
return 6
elif ((n > g[0]) and (n < g[1])):
return 7
def tracker_goto(x):
why = bess.ycor()
bess.goto(x,why)
bess.hideturtle()
bess.penup()
# Find position of mouse click
def findPosition():
wn = turtle.Screen()
wn.listen()
wn.onclick(tracker_goto)
x = bess.pos()
return(x)
def checkAll(listy):
horiz = checkHorizontal(listy)
vert = checkVertical(listy)
dia = checkDiagonal(listy)
if((horiz == True) or (vert == True) or (dia == True)):
return True
else:
return False
def letterConvert(listy, indexx): #replaces all column letters with number
letters = ['a','b','c','d','e','f','g']
for k in range(len(listy)):
for x in range(len(letters)): # for all in list
if letters[x] == listy[k][indexx]:
listy[k][indexx] = x + 1
return listy
def checkHorizontal(listy): #listy is all player checkers
listy = letterConvert(listy, 0) #coverting listy to numbers
for x in listy:
coolList = []
for y in listy:
if (x[1] == y[1]): # if they share the same x coord (if they're in same row)
coolList.append(y[0])# add t
print(coolList)
return checkColumn(coolList)
def checkVertical(listy): #listy is all player checkers
listy = letterConvert(listy, 0) #coverting listy to numbers
for x in listy:
coolList = []
for y in listy:
if (x[0] == y[0]): # if they share the same y coord (if they're in same row)
coolList.append(y[1])# add t
print(coolList)
return checkColumn(coolList)
def checkDiagonal(listy): #listy is all player checkers
listy = letterConvert(listy, 0) #coverting listy to numbers
counter = 1
coolList = []
for x in listy:
for y in listy:
xo = x[0]
yo = y[0]
xi = x[1]
yi = y[1] #if coords x and y are x+1 and y+1
if (((xo == yo + counter) and (xi == yi + counter)) or ((xo == yo - counter) and (xi == yi - counter))):
counter += 1 #add to counter
if(counter >= 4):
return True
else:
return False
def checkColumn(column):
counter = 1
Ncounter = 1
for c in column:
for d in column:
if(c == d + counter):
counter += 1
if(c == d - Ncounter):
Ncounter += 1
print(str(Ncounter) + str(counter))
if((counter >= 4) or (Ncounter >= 4) or (counter + Ncounter >= 4)):
return True
else:
return False
|
553b80d1e5e3d8dcb14e51a675865fb21c856e13 | zhou613/CS-177-Pete-A-Maze-Game | /project2.py | 13,719 | 3.8125 | 4 | from graphics import *
from random import *
#
# project2.py
# Xiaoyu Zhou, 0028388913
# This program includes a game that allows the users to imput
# their names and complete a maze game. The top four users with
# lowest scores would be displayed.
#
# Game Panel
def first_stage():
win = GraphWin('Game Panel', 300, 200)
win.setBackground('grey')
# Initialization
# display the 'Pete-A-Maze' context on the top of the screen
# this list contains the rectangle in need
rec = []
score_board = []
r1 = Rectangle(Point(0,0), Point(300,40))
r1.setFill("white")
m1 = Text(Point(150,20), "Pete-A-Maze")
m1.setSize(24)
r1.draw(win)
m1.draw(win)
# New Player Panel
r2 = Rectangle(Point(100,170), Point(200, 200))
r2.setFill("Green")
m2 = Text(Point(150,185), "NEW PLAYER")
r2.draw(win)
m2.draw(win)
# Exit Panel
r3 = Rectangle(Point(260,170), Point(300, 200))
r3.setFill("Red")
m3 = Text(Point(280,185), "EXIT")
r3.draw(win)
m3.draw(win)
# Score Board
r4 = Rectangle(Point(50,60), Point(250,150))
r4.setFill("white")
r4.draw(win)
# display the Score Board
title = Text(Point(150,70), "TOP SCORES")
dividing_line = Text(Point(150,80), "============")
lowest_four = scoresIn(win)
t1 = Text(Point(150, 95), lowest_four[0])
t2 = Text(Point(150, 110), lowest_four[1])
t3 = Text(Point(150, 125), lowest_four[2])
t4 = Text(Point(150, 140), lowest_four[3])
title.draw(win)
dividing_line.draw(win)
t1.draw(win) , t2.draw(win), t3.draw(win), t4.draw(win)
# store all the rectangle
rec = [r2, r3, r4]
score_board = [title, dividing_line, t1, t2, t3, t4]
return win, rec, score_board
# This function display the input box after clicking start
def next_player(win):
# if the player clicked New_Player box,
# NEW PLAYER control label is changed to START!,
# Player Name: Text label and Entry box
# Start! Panel
r1 = Rectangle(Point(100,170), Point(200, 200))
r1.setFill("Green")
m1 = Text(Point(150,185), "Start!")
m2 = Text(Point(70,70), "Player Name: ")
m2.setSize(18)
# allow the user to input "Player Name"
inputBox = Entry(Point(200,70), 20)
inputBox.draw(win)
r1.draw(win)
m1.draw(win)
m2.draw(win)
return r1, m1, inputBox
# This function pops up the Field after "start!" is clicked
# Display the player's name and live score
def start(win, name):
# create a Field screen
Field = GraphWin("Field", 400, 400)
Field.setBackground("white")
# display the name
# name = input
m0 = Text(Point(180,70),"")
m0.setText(name)
m0.setSize(18)
m0.draw(win)
m1 = Text(Point(95, 110), "Score:")
m1.setSize(18)
m1.draw(win)
# Reset Panel
r1 = Rectangle(Point(0,170), Point(40, 200))
r1.setFill("yellow")
r1.draw(win)
m3 = Text(Point(20,185), "RESET")
m3.draw(win)
# draw grid pattern on the Field
for i in range(0,401,40):
l1 = Line(Point(i, 0), Point(i,400))
l2 = Line(Point(0,i), Point(400, i))
l1.setOutline("light grey")
l2.setOutline("light grey")
l1.draw(Field)
l2.draw(Field)
# draw the start, end, and pete rectangle to the field
r_start = Rectangle(Point(0,0), Point(40,40))
r_start.setOutline("light grey")
r_start.setFill("green")
r_start.draw(Field)
r_end = Rectangle(Point(360, 360), Point(400, 400))
r_end.setOutline("light grey")
r_end.setFill("red")
r_end.draw(Field)
pete = Rectangle(Point(2,2), Point(38,38))
pete.setFill("gold")
pete.draw(Field)
return Field, pete, m1, r1, m0
# This function animate the pete
def animate(Field, win, pete, sensor_loc):
# initialize the score
score = 0
m1 = Text(Point(150,110), score)
m1.setSize(18)
m1.draw(win)
while True:
cp = Field.getMouse()
pete_P1_x = pete.getP1().getX()
pete_P1_y = pete.getP1().getY()
pete_P2_x = pete.getP2().getX()
pete_P2_y = pete.getP2().getY()
old_pete_center_x = pete.getCenter().getX()
old_pete_center_y = pete.getCenter().getY()
# boolean token
add_3 = False
# detect the position of pete
# same row -> Y-axis is within range, move towards the click
if(cp.getY() >= pete_P1_y and cp.getY() <= pete_P2_y):
# if pete.X < click.X, then pete.X increase by 40
# calculate the score, if cross the sensor: +3, if not:+1
if(pete_P2_x < cp.getX()):
pete.undraw()
pete = Rectangle(Point(pete_P1_x+40, pete_P1_y), Point(pete_P2_x+40, pete_P2_y))
pete.setFill("gold")
pete.draw(Field)
# get the new position of the pete
new_pete_center_x = pete.getCenter().getX()
new_pete_center_y = pete.getCenter().getY()
# determine if pete cross the sensor, if True, add 3
for x in sensor_loc:
if(x.getY() == new_pete_center_y and x.getX() <= new_pete_center_x and x.getX() >= old_pete_center_x):
score = score + 3
add_3 = True
# if pete does not cross the sensor, add 1
if(add_3 == False):
score = score + 1
m1.setText(score)
# vice versa
if(pete_P1_x > cp.getX()):
pete.undraw()
pete = Rectangle(Point(pete_P1_x-40, pete_P1_y), Point(pete_P2_x-40, pete_P2_y))
pete.setFill("gold")
pete.draw(Field)
# get the new position of the pete
new_pete_center_x = pete.getCenter().getX()
new_pete_center_y = pete.getCenter().getY()
# determine if pete cross the sensor
for x in sensor_loc:
if(x.getY() == new_pete_center_y and x.getX() >= new_pete_center_x and x.getX() <= old_pete_center_x):
score = score + 3
add_3 = True
if(add_3 == False):
score = score + 1
m1.setText(score)
# same column ->X-axis is within range, move towards the click
if(cp.getX() >= pete_P1_x and cp.getX() <= pete_P2_x):
# if pete.Y < click.Y, then pete.X increase by 40
if(pete_P2_y < cp.getY()):
pete.undraw()
pete = Rectangle(Point(pete_P1_x, pete_P1_y+40), Point(pete_P2_x, pete_P2_y+40))
pete.setFill("gold")
pete.draw(Field)
# get the new position of the pete
new_pete_center_x = pete.getCenter().getX()
new_pete_center_y = pete.getCenter().getY()
# determine if pete cross the sensor
for x in sensor_loc:
if(x.getX() == new_pete_center_x and x.getY() <= new_pete_center_y and x.getY() >= old_pete_center_y):
score = score + 3
add_3 = True
if(add_3 == False):
score = score + 1
m1.setText(score)
# vice versa
if(pete_P1_y > cp.getY()):
pete.undraw()
pete = Rectangle(Point(pete_P1_x, pete_P1_y-40), Point(pete_P2_x, pete_P2_y-40))
pete.setFill("gold")
pete.draw(Field)
# get the new position of the pete
new_pete_center_x = pete.getCenter().getX()
new_pete_center_y = pete.getCenter().getY()
# determine if pete cross the sensor
for x in sensor_loc:
if(x.getX() == new_pete_center_x and x.getY() >= new_pete_center_y and x.getY() <= old_pete_center_y):
score = score + 3
add_3 = True
if(add_3 == False):
score = score + 1
m1.setText(score)
# get the current location of pete after moving
pete_center_x_cur = pete.getCenter().getX()
pete_center_y_cur = pete.getCenter().getY()
# if pete reaches the end, display "Finished! Click to Close",
# wait for click, and close Field
if(pete_center_x_cur > 360 and pete_center_x_cur < 400 and pete_center_y_cur > 360 and pete_center_y_cur < 400):
finish = Text(Point(200,200), "Finished! Click to Close")
finish.draw(Field)
click = Field.getMouse()
break
Field.close()
return score, m1
def sensor(Field):
# create 3 list which contains all the center location of the sensors
l1 = []
# loop through the column and generate the sensor by 40%
for i in range(37, 364, 40):
for j in range(2, 399,40):
# if 40%, generate a sensor 36*5 rectangle
if(random() == True):
rec1 = Rectangle(Point(i, j), Point(i+5, j+36))
rec1.setFill("orange")
rec1.draw(Field)
center1 = Point(rec1.getCenter().getX(), rec1.getCenter().getY())
l1.append(center1)
# loop through the row and generate the sensor by 40%
for i in range(2, 399, 40):
for j in range(37, 364,40):
# if 40%, generate a sensor 5*36 rectangle
if(random() == True):
rec2 = Rectangle(Point(i, j), Point(i+36, j+5))
rec2.setFill("orange")
rec2.draw(Field)
center2 = Point(rec2.getCenter().getX(), rec2.getCenter().getY())
l1.append(center2)
return l1
def scoresOut(player_name, score):
player = player_name + "," + str(score)
file = open("top_scores.txt", "a")
file.write(player)
file.write("\n")
def scoresIn(win):
file = open("top_scores.txt", "r")
num = []
res = []
lowest_four = []
for line in file:
res.append(line.strip())
num.append(line[-3:].strip())
after_sort = selSort(num, res)
return after_sort
def selSort(nums, player):
# sort nums into ascending order
n = len(nums)
# For each position in the list (except the very last)
for bottom in range(n-1):
# find the smallest item in nums[bottom]..nums[n-1]
mp = bottom # bottom is smallest initially
for i in range(bottom+1, n): # look at each position
if nums[i] < nums[mp]: # this one is smaller
mp = i # remember its index
nums[bottom], nums[mp] = nums[mp], nums[bottom]
player[bottom], player[mp] = player[mp], player[bottom]
return player
# This function generate random number from 1-10 and determine if the number is [1,4]
# return true if number is within [1,4], false otherwise
def random():
random_num = randint(1, 10)
if(random_num >= 1 and random_num <= 4):
return True
else: return False
# This function detects if the point clicked by the mouse is inside the rectangle
def click(r, point):
# compare the coordinates of the points with the rectangle's
if(point.getX() >= r.getP1().getX() and point.getX() <= r.getP2().getX()
and point.getY() >= r.getP1().getY() and point.getY() <= r.getP2().getY()):
return True
return False
def main():
loop = 1
while loop == 1:
# receive the "Screen", "Boxs", and "Score_Board" from gp()
win, rec, score_board = first_stage()
Field = None
while loop == 1:
cp = win.getMouse()
# if "Exit" is clicked, end the program
if(click(rec[1], cp) == True):
loop = 0
break
# if "New Player" is clicked, then undraw all Score_Board and display then Entry
if(click(rec[0], cp) == True):
for i in range(0,6):
score_board[i].undraw()
rec[2].undraw()
# receive the "Player Name" and "Start!" box from start()
start_box, message1, inputBox = next_player(win)
# if name is not null and start is clicked,
# load the game and display the name and score
cp1 = win.getMouse()
if(click(start_box, cp1) == True):
name = inputBox.getText()
inputBox.undraw()
message1.setText("NEW PLAYER")
Field, pete, score_box, reset_box, name_box = start(win, name)
sensor_loc = sensor(Field)
score, message2 = animate(Field, win, pete, sensor_loc)
scoresOut(name, score)
#click(rec[0], cp) = False
cp2 = win.getMouse()
# At the end of the game, reset the score
if(click(rec[0], cp2) == True):
message2.undraw()
score_box.undraw()
name_box.undraw()
# If reset box is clicked, then reset everything
if(click(reset_box, cp2) == True):
break
win.close()
if(Field is not None):
Field.close()
main()
|
1ccfad4e7b2afb33f71bb4fef6f31730d629a471 | Zulkarnine1/Data-Structure-Algorithm-Python-Collection | /DS Implementations/BinarySearchTree.py | 4,160 | 3.796875 | 4 | class Node:
def __init__(self, x):
self.left = None
self.right = None
self.val = x
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self,x):
new_node = Node(x)
if not self.root:
self.root = new_node
else:
currentNode = self.root
while (True):
if(x<currentNode.val):
# left
if(not currentNode.left):
currentNode.left = new_node
return self
else:
currentNode = currentNode.left
else:
# Right
if (not currentNode.right):
currentNode.right = new_node
return self
else:
currentNode = currentNode.right
def lookup(self,x):
if not self.root:
return None
else:
currentNode = self.root
while (True):
if x == currentNode.val:
return True
else:
if (x < currentNode.val):
# left
if (not currentNode.left):
return False
else:
currentNode = currentNode.left
else:
# Right
if (not currentNode.right):
return False
else:
currentNode = currentNode.right
# def remove(self,x):
# tar_node, parentNode = self.__remove_lookup__(self,x)
# if not tar_node:
# return False
# else:
# chosenParent = None
# # no right child
# if not tar_node.right:
# if not parentNode:
# self.root = tar_node.left
# else:
# if tar_node.val<parentNode.val:
# parentNode.left = tar_node.left
# elif tar_node.val>parentNode.val:
# parentNode.right = tar_node.left
#
# chosenOne = tar_node.right
# while True:
# if chosenOne.left:
# chosenOne = chosenOne.left
# else:
# break
# elif tar_node.left:
# chosenOne = tar_node.left
# while True:
# if chosenOne.right:
# chosenOne = chosenOne.right
# else:
# break
# tar_node.val = chosenOne.val
#
#
#
# def __remove_lookup__(self, x):
# if not self.root:
# return None, None
# else:
# currentNode = self.root
# parentNode = None
# while (True):
# if x == currentNode.val:
# return currentNode, parentNode
# else:
# if (x < currentNode.val):
# # left
# if (not currentNode.left):
# return None, None
# else:
# parentNode = currentNode
# currentNode = currentNode.left
# else:
# # Right
# if (not currentNode.right):
# return None, None
# else:
# parentNode = currentNode
# currentNode = currentNode.right
tree = BinarySearchTree()
res = tree.insert(9)
print(res)
res = tree.insert(4)
print(res)
res = tree.insert(6)
print(res)
res = tree.insert(20)
print(res)
res = tree.insert(170)
print(res)
res = tree.insert(1)
print(res)
node = tree.lookup(9)
print(node)
node = tree.lookup(1)
print(node)
node = tree.lookup(21)
print(node) |
96baab89a41576027d83a991191ed78afe3f238b | lucasfreire017/Desafios_Python | /Exercício Python #115 - Cadastro de pessoas - B/lib/interface/__init__.py | 812 | 3.734375 | 4 | def leiaInt(msg):
"""
Função para a leitura de valores tipo int
:param msg: valor a ser processado
:return: valor convertido para int
"""
try:
number = int(input(msg))
except (ValueError, TypeError, UnboundLocalError):
print('\033[31mERRO! O valor digitado é inválido, digite um valor inteiro\033[m')
except (KeyboardInterrupt):
print('\033[31mO usúario preferiu não digitar o valor\033[m')
number = 0
else:
return number
def linha():
print('\033[1m-\033[m'*42)
def titulo(msg):
linha()
print(msg.center(42))
linha()
def menu(*opcoes):
titulo('MENU')
n = 0
for item in opcoes:
n+=1
print(f'{n} ➡ {item}')
linha()
num = leiaInt('Digite sua opção: ')
return num
|
3e750585aa9927965eb0d390de93f784e684a20e | ramyasutraye/python--programming | /beginner level 1/primeornot.py | 142 | 3.609375 | 4 | n=raw_input()
n=int(n)
a=0
if n>1:
for i in range(2,n):
if(n%i)==0:
a=1
break
else:
a=2
if a==1:
print "no"
else:
print "yes"
|
3d32f2b9953f4ea36270e874ff35f51bfc44d756 | yindan01/yindan | /animal.py | 454 | 3.53125 | 4 | ##定义类
class Dog:
#毛色,黑色,四条腿
#会吃,会叫,会水
##属性
color="black"
leg=4
##方法,在类的方法中,是使用def关键字定义
##def定义的在类外叫做函数function,在类内,叫做method
def eat(self):
print("狗在吃")
def voice(self):
print ("狗在叫")
#类的实例化
print(Dog.color)
print(Dog.leg)
Dog().eat()
Dog().voice()
|
2e0e5ef285496cbe54c3d4168d707962ffbb90cb | jackrapp/python_challenge | /PyBank/main.py | 1,717 | 3.625 | 4 | #import modules
import csv
import os
budget_data = os.path.join("budget_data.csv")
profit = 0
months = 0
value = 0
increase = 0
decrease = 0
#pull data from csv file in git hub folder
with open(budget_data, newline="") as csvfile:
records = csv.reader(csvfile, delimiter = ",")
next(records)
#calculate
#total number of months in data
for row in records:
#monthly profit/loss
value = int(row[1])
#find number of months
months = months + 1
#total net profit/loss
profit = profit + value
#greatest increase in profits
increase = max(increase, value)
if increase == value:
inc_month = row[0]
#greatest decrease in losses
decrease = min(decrease, value)
if decrease == value:
dec_month = row[0]
#total net profit/loss
avg_monthly = int(profit)/int(months)
print("Financial Analysis")
print("------------------")
print(f"Total Months: {months}")
print(f"Total: {profit}")
print(f"Average Change: {avg_monthly}")
print(f"Greatest Profit: {inc_month} ({increase})")
print(f"Greatest Loss: {dec_month} ({decrease})")
#print out results and send as text file
with open("pybank_analysis.txt", "w") as pybank_analysis:
print("Financial Analysis", file = pybank_analysis)
print("------------------", file = pybank_analysis)
print(f"Total Months: {months}", file = pybank_analysis)
print(f"Total: {profit}", file = pybank_analysis)
print(f"Average Change: {avg_monthly}", file = pybank_analysis)
print(f"Greatest Profit: {inc_month} ({increase})", file = pybank_analysis)
print(f"Greatest Loss: {dec_month} ({decrease})",file = pybank_analysis)
|
8b17cb5eea460045ab563e859007f86c8e476688 | Hasil-Sharma/Spoj | /m_seq.py | 491 | 3.796875 | 4 | from math import sqrt
g_dict = {}
f_dict = {1:8,2:8}
def F(n):
if n in f_dict:
return f_dict[n]
else:
f_dict[n] = 8 + pow((n-2)/(1.0*n),2)*F(n-2)
return f_dict[n]
def G(n):
if n in g_dict:
return g_dict[n]
else:
g_dict[n] = sqrt(8*(pow(n,2)-pow((n-1),2))+pow((n-2),2)*F(n-2) - pow((n-3),2)*F(n-3) + 1.0)/(1.0*n)
return g_dict[n]
def main():
t = input()
i =0
while i < t:
i += 1
n = input()
g = G(n)
print "%.8f" % (round(g,8))
if __name__ == '__main__':
main() |
8574c99aa44e92d5a8e69fac0691db8d057c5662 | v1nnyb0y/Coursera.BasePython | /Coursera/Week.2/Task.41.py | 366 | 3.84375 | 4 | '''
Номер числа Фибоначчи
'''
digit = int(input())
number = 2
first = 0
second = 1
if (digit == 0):
print(0)
elif (digit == 1):
print(1)
else:
while (second < digit):
temp = second
second += first
first = temp
number += 1
if (second == digit):
print(number - 1)
else:
print(-1)
|
4978d37f17bb9c95fd0078fb327785224f93706a | baby5/HackerRank | /Algorithms/Sorting/QuickSort2.py | 468 | 3.53125 | 4 | #coding:utf-8
n = int(raw_input())
ar = map(int, raw_input().split())
def quick_sort(ar):
if len(ar) <= 1:
return ar
p = ar[0]
equal = [p]
left = []
right = []
for x in ar[1:]:
if x < p:
left.append(x)
else:
right.append(x)
left1 = quick_sort(left)
right1 = quick_sort(right)
print ' '.join(map(str, left1+equal+right1))
return left1 + equal + right1
quick_sort(ar)
|
18a377e9832db62a4f0be9fe5ed11929eed940dd | wyifan/pythonlearning | /compute/bisection.py | 465 | 3.765625 | 4 | x = 25
epsilon =0.01
numGuess = 0
low = min(0.00,x)
high = max(1.0, x)
ans = (high+low)/2
while abs(ans**3 -x)>=epsilon:
print 'low:',low,"high:",high,"ans:",ans
numGuess+=1
if ans**3< x:
low = ans
else:
high= ans
ans = (high+low)/2.0
print "Numguess:", numGuess
print ans, "is close to square root of", x
def isIn(a,b):
if(str(a) in str(b)):
return True
else:
return False
print isIn("wsf","wwsfe")
|
02f341a5b4bd7ee57ff9f0aaa366520cbd028ecb | pTricKg/python | /python_files/untitled/list_comprehension.py | 1,365 | 4.09375 | 4 | ## List Comprehension
## makes list of even squares of 1 to 10
even_squares = [x**2 for x in range(1,11) if x % 2 == 0]
print even_squares
## makes list of cubed number divised evenly by 4
cubes_by_four = [x**3 for x in range(1,11) if (x**3) % 4 == 0]
print cubes_by_four
## list slicing
## [start:end:stride] stride is increments of list items selected
l = [i ** 2 for i in range(1, 11)]
# Should be [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print l[2:9:2]
# prints [9, 25, 49, 81]
## print out list elements via slicing
## following will print odd elements
my_list = range(1, 11) # List of numbers 1 - 10
print my_list[::2]
''' preceding has null value for start, so python assumes beginning of list
end has null value, so python assumes end of list,
stride equals 2 so pulls 2 item from list and on and on,
in this case it is odd numbers'''
## positve strides go through list from start to finish or left to right
## negative strides go through list backwards
my_list = range(1, 11)
backwards = my_list[::-1]
print backwards
## another going backwards through list by tens
to_one_hundred = range(101)
backwards_by_tens = to_one_hundred[::-10]
print backwards_by_tens
##
to_21 = range(1,22)
odds = to_21[::2]
middle_third = to_21[7:14:1]
print odds + middle_third
## prints [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 8, 9, 10, 11, 12, 13, 14]
|
2bdbe8794b38b7fccc52fb60fc9ea013ffe7fa5e | RyanIsBored/unit4 | /rectangle.py | 146 | 3.671875 | 4 | #Ryan Jones
#3/9/18
def rectangle(length,width):
print('The area is',length*width)
print('The perimeter is',length*2+width*2)
rectangle(3,4) |
06009d3d34daa3e4c7db77bb5bd0e39adcfce3d8 | Ram-95/python_notes | /Inheritance_and_subclasses.py | 1,862 | 4.28125 | 4 | # Inheritance and Subclasses
class Car:
# class variables
car_type: str = 'Hatchback'
price_inc: int = 1.05
no_of_cars: int = 0
def __init__(self, brand: str, model: str, price: int):
# Instance variables
self.brand = brand
self.model = model
self.price = price
# This should be Class name and not the instance
Car.no_of_cars += 1
def __str__(self):
return f'{self.brand} - {self.model}\'s object'
def increase_price(self):
# Using a class variable - one way
self.price *= self.price_inc
# Other way
#self.price *= self.price_inc
# Subclass - 1
class FuelCars(Car):
"""FuelCars is a sub-class of Car."""
# Changing the price_inc for FuelCars
price_inc:int = 1.02
# Adding some extra instance variables to FuelCars
def __init__(self, brand: str, model: str, price: int, fuel: str):
# Calls the parent class' __init__() method
# Usually sufficient when Single inheritance
super().__init__(brand, model, price)
# Another way - Used when there is Multiple inheritance
#Car.__init__(brand, model, price)
self.fuel = fuel
# Subclass - 2
class ElectricCars(Car):
price_inc = 1.06
def __init__(self, brand: str, model: str, price: int, isSelfDriving: bool):
super().__init__(brand, model, price)
self.isSelfDriving = isSelfDriving
# Driver Code
obj1 = FuelCars('BMW', 'X3', 25000, 'Petrol')
print(obj1)
obj2 = ElectricCars('Tesla', 'S20', 12000, True)
print(obj2)
# To know Method Resolution Order and other details inherited from parent class
#help(FuelCars)
obj1.increase_price()
print(obj1.price)
obj2.increase_price()
print(obj2.price)
print(obj1.fuel)
|
d12e330df1eeffb9f7a09064bcc58c384ad9f94d | MagiRui/machine-learning | /visualization/pandasvisual/pandas_visual.py | 288 | 3.515625 | 4 | # coding=utf-8
# author:MagiRui
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10,4),index=pd.date_range('2018/12/18',
periods=10), columns=list('ABCD')) # 数据 索引 列
print(df)
ds = df.plot() # 折线图
plt.show() |
551d8d0c2f5e0fa3483084f26c4af2e47a4c5250 | richistron/PythonCabal-richistron | /Clase_1/if.py | 289 | 3.90625 | 4 | x = 'hfhfh'
if int(x) = x:
if x < 0:
x = str(x)
print ('Negative changed to zero', x)
elif x == 0:
print ('Zero')
elif x > 0:
print ('Single')
else:
print ('Not a found option')
else:
print ( x, '... Is not an intiger' )
|
57632c2a34616c41a683122cee51ed8dfac513e4 | jakesjacob/FDM-Training-3 | /Exercises/8_user_info.py | 787 | 4.1875 | 4 | # get full name
# get dob
# return users age
# say users age on next birthday
from datetime import datetime
def getName():
firstName = input("Please type your first name: ")
secondName = input("Please type your second name: ")
firstNameCap = firstName.capitalize()
secondNameCap = secondName.capitalize()
fullName = (firstNameCap + " " + secondNameCap)
print("Hello", fullName)
def getDOB():
dob = input("\n\nPlease enter your DOB (dd-mm-yyyy)")
datetimeDate = datetime.strptime(dob, "%d-%m-%Y")
today = datetime.today()
difference = today - datetimeDate
age = int(difference.days/365)
age1 = age + 1
print("Your age is: ", age)
txt = ("You will be {} on your next birthday")
print(txt.format(age1))
getDOB()
getName()
|
3442c5e70926f125fd6a5831b2c3ca1aac64b475 | Sakib18110/Digital-Diary | /DigitalDiary.py | 3,026 | 3.8125 | 4 | import pymysql as db
import os
conn=db.connect("localhost","root","","digital_diary")
cur=conn.cursor()
def insertrecord():
name=input("Enter the name of your frined: ")
address=input("Enter the address of your friend: ")
contact=input("Enter the contact no. of your friend: ")
email=input("Enter the email of your friend: ")
birthday=input("Enter the dob of your friend: ")
qry=f"""insert into friends(name,address,contact,email,birthday)
values ('{name}','{address}',{contact},'{email}','{birthday}')"""
cur.execute(qry)
conn.commit()
print("Record Inserted Successfully")
def updaterecord():
s_no=int(input("Enter the s.no: "))
name=input("Enter the name of your friend: ")
qry="update friends set "
for i in ["address","contact","email","birthday"]:
ch=input(f"Do you want to update {i} y/n: ")
if ch=='y':
val=input(f"enter {i} ")
qry+=f"{i}='{val}' "
qry+=f"where s_no={s_no} and name='{name}'"
cur.execute(qry)
conn.commit()
print("Record Updated Successfully")
def showfriends():
print("All data in diary are following: ")
qry=f"select * from friends"
cur.execute(qry)
for val in cur:
print([val])
conn.commit()
def deletefriend():
s_no=int(input("Enter the s.no: "))
name=input("Enter the name of your friend: ")
ch=input(f"Do you want to delete your friend from list y/n: ")
if ch=='y':
qry=f"delete from friends where s_no={s_no} and name='{name}'"
cur.execute(qry)
conn.commit()
else:
print(f"Don't do this '{name}' is your friend")
print("Deleted Successfully")
def searchfriend():
ch=input("""what you know about your friend name and birthday
1)For name:
2)For birthday:
Enter Here: """)
if ch=='1':
name=input("Enter the name of your friend: ")
qry=f"select * from friends where name='{name}'"
cur.execute(qry)
res=cur.fetchall()
for i in res:
print([i])
conn.commit()
elif ch=='2':
birthday=input("Enter the birthday of your friend: ")
qry=f"select * from friends where birthday={birthday}"
cur.execute(qry)
res=cur.fetchall()
for val in res:
print([val])
conn.commit()
print("Your Friend Data are above")
while True:
os.system('cls')
choice=input("""What you want to be done in diary:
1)Insertion
2)Deletion
3)Updation
4)Show all Diary
5)Searching Friend
6)Exit
""")
if choice=='1':
insertrecord()
elif choice=='2':
deletefriend()
elif choice=='3':
updaterecord()
elif choice=='4':
showfriends()
elif choice=='5':
searchfriend()
elif choice=='6':
break
else:
print("Invalid Input")
os.system('pause')
cur.close()
conn.close()
os.system('cls') |
34a62c5d46dd16c777341800d6b2753d817fca05 | tetrabiodistributed/project-tetra-display | /filter_rms_error.py | 4,707 | 3.859375 | 4 | import numpy as np
import matplotlib.pyplot as plt
def filter_rms_error(filter_object,
to_filter_data_lambda,
desired_filter_data_lambda,
dt=0.01,
start_time=0.0,
end_time=10.0,
skip_initial=0,
use_pressure_error=False,
abs_tol=2.0,
rel_tol=0.02,
generate_plot=False):
"""Calculates root-mean-square (RMS) error between data calculated
by a filter and a reference function that nominally should yield
equal data.
Parameters
----------
filter_object : object
An object representing the filter being tested. It must have
the following functions defined.
filter_object(dt: float)
filter_object.append(datum: float)
filter_object.get_datum() -> float
to_filter_data_lambda : lambda
A function representing the data being fed to the filter. It
should be of the form
to_filter_lambda(time: np.array) -> np.array
desired_filter_data_lambda : lambda
A function representing output that the filter_object output
should be nominally equal to. It should be of the form
desired_filter_data_lambda(time: np.array) -> np.array
start_time=0.0 : float
end_time=10.0 : float
dt=0.01 : float
Represents a time interval in seconds of [start_time, end_time)
with steps of dt between. Calculated as
np.arange(start_time, end_time, dt).
skip_initial=0 : int
Ignores the first skip_inital data points when calculating
error. This is useful when a filter has an initial transient
before it starts returning useful data.
use_pressure_error=False : bool
Instead of calculating direct RMS error, this function will
calculate a normalized error based on given tolerances. This is
useful for ventilators trying to calculate pressure meeting
ISO 80601-2-80:2018 201.12.4.101.1. Default values for the
tolerances are based on this standard.
abs_tol=2.0 : float
The design absolute tolerance when calculating pressure error,
i.e. +/- abs_tol. Only used if use_pressure_error == True.
rel_tol=0.02 : float
The design relative tolerance when calculating pressure error,
i.e. +/- rel_tol * desired_filter_data(t).
generate_plot=False : bool
If True, then a plot of the filter data and
desired_filter_data_lambda with respect to time will be
generated. Note that this should be false in non-interactive
contexts.
Returns
-------
error : float
If use_pressure_error is False,
This returns the RMS error between the filter output and
the output of desired_filter_data_lambda.
If use_pressure_error is True,
This returns a normalized error between the filter output
and the output of desired_filter_data_lambda. If error < 1,
then the typical error is within the design tolerance. When
testing, you can add a safety factor to the error by
asserting that the error must be less than 1/safety_factor.
"""
t = np.arange(start_time, end_time, dt)
test_filter = filter_object(dt)
to_filter_data = to_filter_data_lambda(t)
filtered_data = np.array([])
desired_filtered_data = desired_filter_data_lambda(t)
for i in range(len(to_filter_data)):
test_filter.append(to_filter_data[i])
filtered_data = np.append(filtered_data,
test_filter.get_datum())
if generate_plot:
figure, axis = plt.subplots()
axis.plot(t, to_filter_data, label="To Filter Data")
axis.plot(t, filtered_data, label="Filtered Data")
axis.plot(t, desired_filtered_data, label="Desired Filtered Data")
axis.legend()
plt.show()
if not use_pressure_error:
return _root_mean_square(
(filtered_data - desired_filtered_data)[skip_initial:])
else:
return _pressure_error(filtered_data[skip_initial:],
desired_filtered_data[skip_initial:])
def _root_mean_square(np_array):
return np.sqrt(np.mean(np.square(np_array)))
def _pressure_error(calculated_pressure,
actual_pressure,
abs_tol=2.0,
rel_tol=0.02):
return _root_mean_square(
(calculated_pressure - actual_pressure)
/ (np.full_like(actual_pressure, abs_tol) + rel_tol * actual_pressure)
)
|
f8a762e69a8ba68687aa075adc84b28812b5e6b8 | paul-schwendenman/advent-of-code | /2018/day01/day01.py | 594 | 3.78125 | 4 | from itertools import accumulate, cycle
def part1(frequencies):
return sum(int(frequency) for frequency in frequencies)
def part2(raw_frequencies):
frequencies = accumulate(cycle(int(f) for f in raw_frequencies))
history = set()
for frequency in frequencies:
if frequency in history:
break
else:
history.add(frequency)
return frequency
def main():
with open('input') as input_file:
data = input_file.read().splitlines()
print(part1(data))
print(part2(data))
if __name__ == "__main__":
main()
|
eece6515529bc683a42922201a1418d0d46e50b8 | SongJialiJiali/test | /leetcode_844.py | 592 | 3.578125 | 4 | #leetcode 844. 比较含退格的字符串
class Solution(object):
def backspaceCompare(self, S, T):
"""
:type S: str
:type T: str
:rtype: bool
"""
return self.backspaceString(S) == self.backspaceString(T)
def backspaceString(self,Str):
'''
求退格后的字符串函数
'''
List = []
for i in range(len(Str)):
if Str[i] != '#':
List.append(Str[i])
elif Str[i] == '#' and len(List) != 0:
List.pop()
return List
|
c76137546716f769c3f2b78b4ee5083bab380c34 | adammachaj/python-vending-machine | /collector.py | 1,052 | 3.609375 | 4 | import item
class Collector(item.Item):
"""Soda collector"""
def __init__(self, code, price = 2.0):
self.code = code
self.price = price
self.quantity = 5
self.items = []
def __str__(self):
if not self.items:
rep = "<empty>" + "\tCena: " + str(self.price)
else:
rep = str(self.items[0]) + " Cena: " + str(self.price)
return rep
def add_item(self, i):
if len(self.items) < self.quantity:
self.items.append(i)
else:
print("Not enough slots in collector")
def remove_items(self):
self.items.clear()
def get_item(self):
if self.items[0] == None:
return "No sodas here"
else:
return self.items[0].name
def get_price(self):
return self.price
def buy_item(self):
if not self.items:
return "No sodas here"
else:
#print(self.items[0])
#self.items.pop(0)
return self.items.pop(0)
|
051bca102944c6047be7d477a46d78974c66fe53 | pokerSeven/leetcode | /71.py | 680 | 3.625 | 4 | # _*_ coding: utf-8 _*_
__author__ = 'lhj'
__date__ = '2017/10/18 22:11'
class Solution(object):
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
left = 0
for i in range(len(path)):
if path[i] == "/":
left = i + 1
else:
break
path = path[left:][::-1]
left = 0
for i in range(len(path)):
if path[i] == "/":
left = i + 1
else:
break
path = path[left:][::-1]
ans = []
ps = path.split("/")
for n in ps:
if n == "" or n == ".":
pass
elif n == "..":
ans = ans[:-1]
else:
ans.append(n)
if not ans:
return "/"
else:
re = ""
for n in ans:
re = re + "/" + n
return re
|
d19b1fdca8efc92c59b9620817ba256cbe051539 | fitrepoz/SSW-567 | /HW01/hw01.py | 1,074 | 4 | 4 |
import unittest
def classify_triangle(a, b, c):
if a == b == c:
return 'equilateral'
elif a == b or a == c or b == c:
return 'isosceles'
elif a*a + b*b == c*c:
return 'right'
else:
return 'scalene'
def main():
print('')
print('Now lets check our sample input:')
print('---------------------------------------')
print(classify_triangle(10, 1, 2))
print(classify_triangle(1, 1, 1))
print(classify_triangle(3, 45, 5))
print(classify_triangle(2, 2, 2))
print(classify_triangle(1, 3, 4))
class RunTests(unittest.TestCase):
def test_classify_triangle(self):
self.assertEqual(classify_triangle(1, 1, 1), "equilateral")
self.assertEqual(classify_triangle(2, 3, 4), "scalene")
self.assertEqual(classify_triangle(2, 2, 3), "isosceles")
self.assertEqual(classify_triangle(6, 8, 10), "right")
self.assertEqual(classify_triangle(2, 8, 10), "right")
print('')
if __name__ == "__main__":
unittest.main(exit = False, verbosity = 2)
main() |
a55aa82e219b0b660c2a15fe43b7a3d3261614c5 | meenapandey500/Python_program | /Revision/emp_constructor.py | 672 | 4.03125 | 4 | class Employee:
def __init__(self): #__init__() constructor function : it is call automatic in main
#or anywhere when create the object of class in main program or anywhere
self.__Emp_no=101 #private variable
self.__Emp_name="Meena Pandey" #private variable
self.__Salary=67000 #private variable
def display(self):
print("Emp no :",self.__Emp_no)
print("Emp Name : ",self.__Emp_name)
print("Salary : ",self.__Salary)
def __del__(self): #destructor function
print("Clear memory of object")
#main program
Sales=Employee()
Sales.display() #call
del(Sales) #call destructor function
|
9e553fd8bd78e84c2bc056193104072f23c51cb8 | BrantLauro/python-course | /module01/ex/ex025.py | 131 | 4.1875 | 4 | name = str(input('Type your complete name: ')).strip().upper().split()
print(f'Does your name have "POTTER"? {"POTTER" in name}')
|
ced8bf5c9b3fb0fcecd90bb87bb9c5ab59a0462a | suruisunstat/leetcode_practice | /1038. Binary Search Tree to Greater Sum Tree.py | 988 | 3.8125 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def bstToGst(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
def inorder(root,s=[0]):
if root:
inorder(root.right)
s[0] += root.val
root.val = s[0]
inorder(root.left)
inorder(root)
return root
root = TreeNode(4)
root.left = TreeNode(1)
root.left.left = TreeNode(0)
root.left.right = TreeNode(2)
root.left.right.right = TreeNode(3)
root.right = TreeNode(6)
root.right.left = TreeNode(5)
root.right.right = TreeNode(7)
root.right.right.right = TreeNode(8)
sol = Solution()
res = sol.bstToGst(root)
def dfs(root):
if root:
print(root.val)
dfs(root.left)
dfs(root.right)
dfs(root)
# 30
# 36
# 36
# 35
# 33
# 21
# 26
# 15
# 8
|
9abc642667805de5af01cbd3078d6b52a62f90b3 | psycomarcos/cursointensivodepython | /2.3.py | 587 | 4.34375 | 4 | # Armazene o nome de uma pessoa em uma variável e apresente uma mensagem a essa pessoa.
nome = "Marcos"
print("Alô, " + nome + ", você gostaria de aprender um pouco de Python hoje?")
# // outras formas de fazer que não está no livro //
# separando strings e variaveis com uma virgula
print("Alô,", nome, "você gostaria de aprender um pouco de Python hoje?")
# usando a função f"string"
print(f"Alô, {nome}, você gostaria de aprender um pouco de Python hoje?")
# usando .format(variavel)
print("Alô, {}, você gostaria de aprender um pouco de Python hoje?".format{nome})
|
c46a62b74f133d49c50f0f15118a498822d79bbc | KasturiPatil/Mini-Python-Projects | /ATMMachine.py | 2,010 | 4.09375 | 4 | while True:
pin = int(input("Enter account pin:"))
if pin > 1000 and pin < 9999:
print("1-View Balance 2-Withdraw 3-Deposit 4-Exit")
break
else:
print("Invalid Pin Entered.")
class Account:
def __init__(self,balance = 0):
self.balance = balance
def ViewBalance(self):
return self.balance
def Withdraw(self):
withdraw_amt = float(input("Enter amount to withdraw:"))
if withdraw_amt < self.balance:
check= input("Is this the correct amount, Y/N?")
if check == "Y" or check =="y":
self.balance -= withdraw_amt
print("Remaining Balance:",obj.ViewBalance())
else:
print("You're balance is less than withdrawl amount.")
print("Please make a deposit.")
def Deposit(self):
deposit_amt = float(input("Enter amount to deposit:"))
check = input("Is this the correct amount, Y/N?")
if check == "Y" or check =="y":
self.balance += deposit_amt
print("Updated Balance:", obj.ViewBalance())
else:
pass
obj=Account()
while True:
select = int(input("\nEnter your selection:"))
if select==1:
print("Your current Balance is:",obj.ViewBalance())
elif select==2:
obj.Withdraw()
elif select == 3:
obj.Deposit()
elif select == 4:
print("\nTransaction Successfull.")
print("Balance:", obj.ViewBalance())
break
else:
print("\nInvalid selection. Please select again")
|
00f45fe6ae16e41bab5b53902fccc99ebf206420 | bit-bots/bitbots_vision | /bitbots_vision/scripts/extract_from_rosbag.py | 5,940 | 3.625 | 4 | #!/usr/bin/env python3
import os
import cv2
import rosbag
import argparse
import numpy as np
from cv_bridge import CvBridge
from sensor_msgs.msg import Image
def yes_or_no_input(question, default=None):
# type: (str) -> bool
"""
Prints a yes or no question and returns the answer.
:param str question: Yes or no question
:param bool default: Default answer, if empty answer
:return bool: Input answer
"""
answer = None
reply = None
extension = None
if default is None:
extension = " [y|n]"
elif default == True:
extension = " [Y|n]"
elif default == False:
extension = " [y|N]"
while answer is None:
reply = str(input(question + extension + ": ")).lower().strip()
if default is not None and reply == "":
answer = default
elif reply[:1] == 'y':
answer = True
elif reply[:1] == 'n':
answer = False
return answer
def int_input(question, min_int=None, max_int=None):
# type: (str, int, int) -> int
"""
Prints a question about a int value and returns the answer.
:param str question: Int question
:param int min_int: Minimum input value to be accepted
:param int max_int: Maximum input value to be accepted
:return int: Input answer
"""
answer = None
reply = None
extension = None
# Construct full question with min and max
if min_int is not None and max_int is None:
extension = f" [MIN: {min_int}]"
elif min_int is None and max_int is not None:
extension = f" [MAX: {max_int}]"
elif min_int is not None and max_int is not None:
if not min_int <= max_int:
raise ValueError("min_int must be smaller or equal to max_int.")
else:
extension = f" [{min_int} - {max_int}] "
while answer is None:
try:
reply = int(input(question + extension + ": ").strip())
except ValueError:
pass
# Check for min and max conditions
if reply is not None:
if min_int is None and max_int is None or \
min_int is not None and max_int is None and min_int <= reply or \
min_int is None and max_int is not None and reply >= max_int or \
min_int is not None and max_int is not None and min_int <= reply <= max_int:
answer = reply
return answer
parser = argparse.ArgumentParser("Extract images from a rosbag")
parser.add_argument("-o", "--out-dir", required=True, help="Output directory for the images", dest="outputdir")
parser.add_argument("-i", "--input-bag", required=True, help="Input rosbag", dest="inputfile")
parser.add_argument("-n", "--nth-image", help="Every n-th image will be saved, prompted if not specified", dest="n",
type=int)
parser.add_argument("-t", "--topic", help="Image topic, prompted if not asked", dest="topic")
args = parser.parse_args()
try:
bag = rosbag.Bag(args.inputfile, "r")
except IOError:
print("Error while opening bag")
exit(1)
topics_and_type = bag.get_type_and_topic_info()
image_topics_and_info = []
for topic, info in topics_and_type.topics.items():
if info.msg_type == "sensor_msgs/Image":
image_topics_and_info.append([topic, info])
if len(image_topics_and_info) == 0: # no topics found
print("No messages of type sensor_msgs/Image found in the provided rosbag")
exit()
elif len(image_topics_and_info) == 1: # 1 topic found
print(f"Found exactly one topic ({image_topics_and_info[0][0],}) of type sensor_msgs/Image with {image_topics_and_info[0][1].message_count} messages.")
if image_topics_and_info[0][0] == args.topic:
chosen_set_num = 0
else:
selection = yes_or_no_input("Do you want to extract images from this topic?", default=True)
if not selection:
exit()
chosen_set_num = 0
else: # Multiple topics found
if args.topic in image_topics_and_info: # Topic already specified in argument
for i, topic_tuple in enumerate(image_topics_and_info):
if topic_tuple[0] == args.topic:
chosen_set = image_topics_and_info[i]
else: # Multiple topics, but not specified yet
print("Multiple topics with type sensor_msgs/Image:")
for i, topic_tuple in enumerate(image_topics_and_info):
print("[" + str(i) + "] topic: " + str(topic_tuple[0]) + " \t message_count: " + str(
topic_tuple[1].message_count))
chosen_set_num = int_input("Make a selection", min_int=0, max_int=len(image_topics_and_info) - 1)
chosen_set = image_topics_and_info[chosen_set_num]
print(f"The dataset you have selected has a frequency of {chosen_set[1].frequency}")
if args.n is None:
n = int_input("Every n-th image will be saved. Please specify n", min_int=1)
else:
n = args.n
print(f"Extracting every {n}-th image.")
try:
os.mkdir(args.outputdir)
except OSError:
if not yes_or_no_input("Directory already exists, continue?" ,default=True):
exit()
i = 0
frame_number = 0
bridge = CvBridge()
for bag_msg in bag.read_messages(chosen_set[0]):
i = (i + 1) % n
if i != 0:
continue
msg_from_bag = bag_msg.message
img = Image()
img.header = msg_from_bag.header
img.data = msg_from_bag.data
img.height = msg_from_bag.height
img.width = msg_from_bag.width
img.encoding = msg_from_bag.encoding
img.is_bigendian = msg_from_bag.is_bigendian
img.step = msg_from_bag.step
cv_image = bridge.imgmsg_to_cv2(img, desired_encoding="passthrough")
cv2.imwrite(f"{args.outputdir}/img{frame_number:05d}.png", cv_image)
frame_number += 1
if frame_number % 10 == 0:
print(f"\r{frame_number}/{chosen_set[1].message_count // n}", end="")
print(f"\r{frame_number}/{chosen_set[1].message_count // n}")
print("Image extraction complete.")
|
10586c683f02a3df1e84da33480f0527306f741a | pratyushmb/Prat_Python_Repo | /Venkat_training/class_constructor.py | 744 | 3.8125 | 4 | class TscEmp:
"""This is a template creating tsc emp"""
empCount = 0
# Constructor assigning values to instance variables.
def __init__(self, name, salary, role):
self.name = name
self.salary = salary
self.role = role
TscEmp.empCount += 1
def displayCount(self):
print("total emp till now %d", TscEmp.empCount)
def displayEmployee(self):
print("Employee name:", self.name)
print("Employee role:", self.role)
# Creating objects for TscEmp class
emp1 = TscEmp("John", 100, "Manager")
emp2 = TscEmp("prat", 200, "developer")
# Accessing the methods of the class via object
emp1.displayEmployee()
emp2.displayEmployee()
print(TscEmp.__doc__)
print(TscEmp.__dict__)
|
4b1f90521c2c33e2b13d9764bd752aec7d799866 | madamiak/advent-of-code | /2016/days7-25/test_puzzle10.py | 3,808 | 3.515625 | 4 | from unittest import TestCase
from puzzle10 import Puzzle10
class TestPuzzle10(TestCase):
pass
def setUp(self):
self.test_object = Puzzle10()
def test_distribute_value(self):
self.test_object.solve("value 5 goes to bot 2")
self.assertEqual(self.test_object.get_bot_with_values([5]), ['bot 2'])
def test_skip_instruction_when_no_values(self):
self.test_object.solve("bot 2 gives low to bot 1 and high to bot 0")
self.assertEqual(self.test_object.get_bot_values(2), None)
def test_skip_instruction_when_one_value(self):
self.test_object.solve("value 5 goes to bot 2\n"
"bot 2 gives low to bot 1 and high to bot 0")
self.assertEqual(self.test_object.get_bot_values('bot 2'), [5])
def test_distribute_two_values(self):
self.test_object.solve("value 5 goes to bot 1\n"
"value 5 goes to bot 2\n"
"value 4 goes to bot 2\n")
self.assertEqual(self.test_object.get_bot_with_values([5, 4]), ['bot 2'])
self.assertEqual(self.test_object.get_bot_with_values([5]), ['bot 1'])
def test_bot_gives_value_when_two_available(self):
self.test_object.solve("value 5 goes to bot 2\n"
"value 4 goes to bot 2\n"
"bot 2 gives low to bot 1 and high to bot 0")
self.assertEqual(self.test_object.get_bot_values('bot 1'), [4])
self.assertEqual(self.test_object.get_bot_values('bot 0'), [5])
self.assertEqual(self.test_object.get_bot_values('bot 2'), [])
def test_putting_to_output(self):
self.test_object.solve("value 5 goes to bot 2\n"
"value 4 goes to bot 2\n"
"bot 2 gives low to output 1 and high to output 0")
self.assertEqual(self.test_object.get_bot_values('output 1'), [4])
self.assertEqual(self.test_object.get_bot_values('output 0'), [5])
self.assertEqual(self.test_object.get_bot_values('bot 2'), [])
def test_complex(self):
self.test_object.solve("value 5 goes to bot 2\n"
"bot 2 gives low to bot 1 and high to bot 0\n"
"value 3 goes to bot 1\n"
"bot 1 gives low to output 1 and high to bot 0\n"
"bot 0 gives low to output 2 and high to output 0\n"
"value 2 goes to bot 2")
self.assertEqual(self.test_object.get_bot_values('output 0'), [5])
self.assertEqual(self.test_object.get_bot_values('output 1'), [2])
self.assertEqual(self.test_object.get_bot_values('output 2'), [3])
def test_search_pair(self):
bot = self.test_object.solve("value 5 goes to bot 2\n"
"bot 2 gives low to bot 1 and high to bot 0\n"
"value 3 goes to bot 1\n"
"bot 1 gives low to output 1 and high to bot 0\n"
"bot 0 gives low to output 2 and high to output 0\n"
"value 2 goes to bot 2", [3, 5])
self.assertEqual(bot, 'bot 0')
def test_solution_1(self):
with open('Puzzle10.txt', 'r') as puzzle:
print self.test_object.solve(puzzle.read(), [17, 61])
def test_solution_2(self):
with open('Puzzle10.txt', 'r') as puzzle:
self.test_object.solve(puzzle.read())
out_0 = self.test_object.get_bot_values('output 0')[0]
out_1 = self.test_object.get_bot_values('output 1')[0]
out_2 = self.test_object.get_bot_values('output 2')[0]
print int(out_0 * out_1 * out_2)
|
2c84c68b31667d90b1d29b53af13b8757f527355 | darkraven92/DD1310 | /Lab1/Uppgift4.py | 679 | 3.9375 | 4 | import math
def find_cubes(n):
solutions = []
for a in range(1, math.floor(n**(1/3))+1):
for b in range(a, math.floor(n**(1/3))+1):
if a**3 + b**3 == n:
solutions.append((a,b))
if len(solutions) == 2:
return solutions
return solutions
n = int(input("Ange ett positivt heltal: "))
solutions = find_cubes(n)
if len(solutions) == 0:
print(f"Det finns inga lösningar till a³ + b³ = {n}")
elif len(solutions) == 1:
print(f"Det finns en lösning till a³ + b³ = {n}: {solutions[0]}")
else:
print(f"Det finns två lösningar till a³ + b³ = {n}: {solutions[0]} och {solutions[1]}")
|
2b42cd4ae6925ea39b94393e46f139b964de639f | ahmad0711/PracticeOfPython | /01_basic.py | 851 | 4.21875 | 4 | '''# This is single Line Comment
"Again This is a Comment"
print("Ahmad Chaudhry")
'''This is a MultiLine comment'''
print('''Hello How are you and
what are you doing right now''')
# Arithmetic Operators
a = 30
b = 30
print ("This is the sum of 30 + 30 is ", a+b)
#compersion operaotre
c = (14>7)
d = (15<6)
print (c,d)
# logical Operatores
bool1 = True
bool2 = False
print("The Value of Bool1 and Bool2 is ", (not bool2))
print("The Value of Bool1 or Bool2 is ", (bool1 and bool2))
print("The Value of Bool1 not Bool2 is ", (bool1 or bool2))
# Type Casting
e = "4735"
e = int(e)
print(type(e)) '''
# Input function
f = input("Please Eneter your Name ")
print("Your Name Is ",f)
g = input(int("Please Enter a Number "))
h = input(int("Please Enter Second Number "))
print("The Sum of first and second number is ",h+g)
|
c87b37e57107090990169352855e0384d5e00359 | SethMiller1000/Portfolio | /Foundations of Computer Science/Lab 13- More While Loops.py | 2,388 | 4.125 | 4 | ## More repetition with while loops- Lab 13: CIS 1033
## Author: Seth Miller
## Loop 1- finds sum of all integers from 10 to 20 including 10 and 20
integer = 10
sum = 0
while ( integer <= 20 ):
sum = sum + integer
integer = integer + 1
print( "Sum of integers 10 to 20:", sum )
print()
## Loop 2- concatenates 4 seperate strings entered by user
userString = ""
concatenatedString = ""
stringCount = 0
while ( stringCount < 4 ):
userString = input("Please enter a string > ")
if userString == "":
print("Error: you must enter at least one character!")
else:
concatenatedString = concatenatedString + userString
stringCount = stringCount + 1
print( "Your strings concatenated together: " + concatenatedString )
print()
## Loop 3- Simulates a cashier at a retail store
itemsPurchased = int( input( "Please enter the number of items purchased: " ) )
itemCount = 0
totalPrice = 0
if ( itemsPurchased == 0 ):
print( "No items purchased." )
else:
while( itemCount < itemsPurchased ):
itemPrice = float( input( "Please print the price of an item in dollars and pennies: $" ) )
totalPrice = totalPrice + itemPrice
itemCount = itemCount + 1
formattedTotalPrice = "%.2f" %totalPrice
print( "Your total price is $" + str( formattedTotalPrice ) )
print()
## Loop 4- Asks user for secret word until user enters actual secret word ( BEARCAT )
secretWord = "BEARCAT"
secretWordInput = input( "Please enter the secret word: " )
while ( secretWordInput != secretWord ):
secretWordInput = input( "Incorrect! Please enter the secret word: " )
print( "Correct! Access granted." )
print()
## Loop 5- Asks user to enter a string and displays each character on a new line
userMessage = input( "Please enter a single string > " )
i = 0
while ( i< len( userMessage ) ):
print( userMessage[i] )
i = i + 1
print()
## Loop 6- Determines whether a series of numbers input by the user are even or odd
enteredNumber = int( input( "Please enter an integer or 0 to stop: " ) )
while ( enteredNumber != 0 ):
if enteredNumber % 2 == 0:
numberStatus = "even"
else:
numberStatus = "odd"
print( "This number is " + numberStatus + "." )
print()
enteredNumber = int( input( "Please enter an integer or 0 to stop: " ) )
|
d97b4aff2646515f2a4399fa7c75b2ae2102e6fd | satyajit98/python_test | /add.py | 95 | 3.84375 | 4 | a=int(input("Enter first number"))
b=int(input("Enter second number"))
sum=a+b
print("sum",sum) |
d6b26a832f952e9183ce9ab13fb9fa0f081ec226 | hghimanshu/CodeForces-problems | /bose/python/arrays/TimeMap.py | 831 | 3.640625 | 4 | class TimeMap:
def __init__(self):
self.time_map = {}
def set(self, key,value,timestamp):
if self.time_map.get(key):
self.time_map[key].update({timestamp:value})
else:
self.time_map.update({key:{timestamp:value}})
def get(self, key,timestamp):
try:
while timestamp>=0:
if self.time_map[key].get(timestamp):
return self.time_map[key][timestamp]
timestamp-=1
return ""
except KeyError:
return ""
if __name__ == "__main__":
obj = TimeMap()
obj.set("love", "high", 10)
obj.set("love", "low", 20)
print(obj.get("love",5))
print(obj.get("love",10))
print(obj.get("love",15))
print(obj.get("love",20))
print(obj.get("love",25)) |
674a55163057ebd490db005751673994f553c6a2 | panpanshen1/vip5 | /异常处理.py | 1,244 | 3.84375 | 4 | # def calc(a,b):
# try:
# print(a/b)
# except ZeroDivisionError:
# #如果被除数是0的话,抛出异常
# print('被除数不能是0')
# a=int(input('输入一个除数'))
# b=int(input('输入被除数'))
#
# calc(a,b)
# try:
# print(name)
# #只打印print
# except NameError:
# print('未定义')
# def calc(a,b):
# try:
# print(a/b)
# except ZeroDivisionError as result:
# print(result)
# a,b=input('plealse input two value').split(',')
# calc(int(a),int(b))
# def calc(a,b):
# #print(a+b)
# try:
# print(a/b)
# except ZeroDivisionError as result:
# print(result)
# except KeyboardInterrupt as result1:
# print(result1)
# except ValueError as result2:
# print(result2)
# else:
# print('c程序执行完毕。')
# a,b= input('please ').split(',')
# calc(int(a),int(b))
# def calc(a,b):
# try:
# print(a/b)
# except NameError as a:
# print(a)
# raise
# #当是nameeerror的时候,就是捕获然后又抛出来
# except TypeError as msg:
# print(msg)
# else:
# print('chengxuwanbi')
# a,b= input('please ').split('+')
# calc(int(a),int(b)) |
1d5588f0628f4a8e4143b0669a56962079ca1232 | Vagacoder/Python_for_everyone | /P4EO_source/ch05/worked_example_5/growth.py | 1,677 | 4.21875 | 4 | ##
# This program creates bar charts to illustrate exponential growth or
# decay over long periods of time.
#
from matplotlib import pyplot
def main() :
showGrowthChart(1000.0, 1.0, 500, 50, "Bank balance")
showGrowthChart(100.0, -0.0121, 6000, 500, "Carbon decay")
## Constructs a bar chart that shows the cumulative increase or
# decrease in a quantity over many years.
# @param initial (float) the initial value of the quantity
# @param rate (float) the percentage rate of change per year
# @param years (int) the number of years to show in the chart
# @param bardistance (int) the number of years between successive bars
# @param title (string) The title of the graph
#
def showGrowthChart(initial, rate, years, bardistance, title) :
amount = initial
bar = 0
# Add the bar for the initial amount.
pyplot.bar(bar, amount, align = "center")
bar = bar + 1
year = 1
while year <= years :
# Update the amount
change = amount * rate / 100
amount = amount + change
# If a bar should be drawn for this year, draw it
if year % bardistance == 0 :
pyplot.bar(bar, amount, align = "center")
bar = bar + 1
year = year + 1
# Set the title of the chart
if rate >= 0 :
subtitle = "Growth rate %.4f percent" % rate
else :
subtitle = "Decay rate %.4f percent" % -rate
pyplot.title(title + "\n" + subtitle)
# Configure the axes
pyplot.xlabel("Year")
pyplot.ylabel("Amount")
pyplot.xticks(range(0, bar), range(0, year, bardistance))
# Fit the plot area tightly around the bar chart.
pyplot.xlim(-0.5, bar - 0.5)
pyplot.show()
main()
|
c966cde609243af443c51b66bafcf7ec29557e16 | prologuek/python | /text.py | 209 | 3.59375 | 4 | import numpy
data = [[1, 2], [3, 4], [5, 6]]
x = numpy.array(data)
print (x)
print (x.dtype)
print (x.ndim) # 打印数组的维度
print (x.shape) # 打印数组各个维度的长度。shape是一个元组
|
2615db66781d31f318108638447528f147cb21e0 | pyq111/Rikao | /Zhoukao1/demo2.py | 269 | 3.8125 | 4 | import random
list1=[]
list2=[]
list3=[]
for i in range(50):
a=int(random.randrange(-10,10))
list1.append(a)
print(list1)
if list1[a]>0:
list2=list1
list2.append(a)
print(list2)
elif list1[a]<0:
list3=list1
list3.append(a)
print(list3) |
88f84d3134f89dc0d06d37dc9b94f178aab083b1 | Nadeemk07/Python-Examples | /Arrays/rotation_count.py | 248 | 3.65625 | 4 | def rotate(arr, n):
min = arr[0]
for i in range(0, n):
if (min > arr[i]):
min = arr[i]
min_index = i
return(min_index)
arr = [15, 18, 2, 3, 6, 12]
n = len(arr)
print(rotate(arr, n))
|
d4748e77aad02a17b3e75ec4965331e6dcd39ad6 | katerinasarlamanova/Katerina | /zadatak 1/z5.py | 253 | 3.796875 | 4 | # -*- coding: utf-8 -*-
a = int(raw_input("Unesite prvi broj: "))
b = int(raw_input("Unesite drugi broj: "))
c = int(raw_input("Unesite treci broj: "))
s = (a + b + c) / 3.0
print ("Sredina unetih brojeva je %.3f" %s)
# %.3f zaokruzava na 3 decimale
|
177362dad92d340b904cfe6c612f00bb8666ca38 | day1127/ICSstuff | /listFunc.py | 2,024 | 4.46875 | 4 |
"""
create a python program called listFunc.py that contains the following functions
1. shuffleList(list) done
2. bubbleSort(list) done
3. selectSort(list)done
4. insertSort(list)done
5. quickSort(list)done
"""
# listFunc.py
# Day Burke
# March 9, 2021 finshed march 10, 2021
# stored on my github at link
import random as r
def shuffleList(list):
r.shuffle(list)
print(list,"\n")
def bubbleSort(list):
indexLength = len(list) - 1
sorted = False
while not sorted:
sorted = True
for i in range(0, indexLength):
if list[i]> list[i+1]:
sorted = False
list[i], list[i+1] = list[i+1], list[i]
return list
def selectSort(list):
indexLength = range(0, len(list) - 1)
for i in indexLength:
maxValue = i
for j in range(i+1, len(list)):
if list[j] < list[maxValue]:
maxValue = j
if maxValue != i:
list[i], list[maxValue] = list[maxValue], list[i]
return list
def insertSort(list):
indexLength = range(1,len(list))
for i in indexLength:
valToSort = list[i]
while list[i-1] > valToSort and i > 0:
list[i-1], list[i] = list[i], list[i-1]
i = i-1
return list
def quickSort(list):
Len = len(list)
if Len <=1:
return list
else:
pivot = list.pop()
iGreater = []
iSmaller = []
for i in list:
if i > pivot:
iGreater.append(i)
if i < pivot:
iSmaller.append(i)
return quickSort(iSmaller) + [pivot] + quickSort(iGreater)
if __name__ == "__main__":
shuffleList([1,2,3,4,5,6,7])
print(bubbleSort([8,6,9,2,1,0,5,3]),"\n")
print(selectSort([1,4,5,3,6,7,8,9,10]),"\n")
print(insertSort([3,4,5,6,3,2,3,5,7,8,7,8,9,8,10,11,15,50,49]),"\n")
print(quickSort([1,4,5,6,4,14,17,7,8,9,4,15,20]))
|
9b5db7119c9043ea44ba5d183c8d8f7fcd94cecb | egarcia410/digitalCraft | /Week1/9-turtleExercises/exercise1/pentagon.py | 222 | 3.921875 | 4 | import turtle
def pentagon():
turtle.Screen()
turtle.color('pink')
turtle.shape('turtle')
for num in range(0, 5):
turtle.forward(100)
turtle.left(72)
turtle.exitonclick()
pentagon()
|
691f4dbd3cf5a6d0381856293f163b9475bc709c | JamesSmith1202/softdev-work05 | /utils/work03.py | 1,497 | 3.609375 | 4 | #Work03
#James Smith and Ish Mahdi
import random
global d
d = {}
#CORE FUNCTIONS =============================================================================
#returns a list of the csv file lines.
def open_read(csvFile):
csv_file = open(csvFile, 'r')
return csv_file.readlines()[1:len(csv_file.readlines())-1]
def lineToDictEntry(line):
#This block deals with commas and splicing
if line.find('''",''') == -1:
job = line.split(",")[0]
percentage = line.split(",")[1]
link = line.split(",")[2]
else:
job = line.split('''",''')[0][1:]
percentage = line.split('''",''')[1].split(",")[0]
link = line.split('''",''')[1].split(",")[1]
numLinkTuple = (float(percentage),link)
d[job] = numLinkTuple
return d
#Turns the csv line list into a dictionary with Profession:Percentage
def listToDict(lineList):
#iterate through the list and fill dictionary
for line in lineList:
lineToDictEntry(line)
#Picks weighted random key value from dictionary
def getRandom():
threshold = random.random() * 99.8#total percentage
counter = 0
for entry in d:
counter += d[entry][0]
if(counter > threshold):
return entry
#CORE FUNCTIONS ===========================================================================
#testing program
def run(csvFile):
lineList = open_read(csvFile)
listToDict(lineList)
return(d, (getRandom()))
|
3c7d79253766f598236c308892b85ff04bac5cde | martinbaros/competitive | /HashCode/solution.py | 517 | 3.546875 | 4 | roads = {}
positions = {}
cars = {}
D,I,S,V,F = [int(s) for s in input().split()]
for line in range(S):
start,end,name,time = [str(s) for s in input().split()]
start,end,time = int(start), int(end), int(time)
roads[name] = [start,end,time]
for car in range(V):
inp = [str(s) for s in input().split()]
cars[car] = inp[1:]
if inp[2] in positions:
positions[inp[2]] = positions[inp[2]].append(car)
else:
positions[inp[2]] = [car]
print(roads)
print(cars)
print(positions)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.