blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
3543f6f7791c4308f5d4404b123a1277ba6a3624
|
devinupreti/coding-problems
|
/staircase.py
| 2,109 | 4.1875 | 4 |
# PROBLEM : There exists a staircase with N steps, and you can climb up
# either 1 or 2 steps at a time.
# Given N, write a function that returns
# the number of unique ways you can climb the staircase.
# The order of the steps matters.
# For example, if N is 4, then there are 5 unique ways:
# 1, 1, 1, 1
# 2, 1, 1
# 1, 2, 1
# 1, 1, 2
# 2, 2
# Time : O(2^n) | Space : O(n) - recursion stack
def climbStairs(stairs):
if stairs < 2:
return 1
elif stairs == 2:
return 2
else:
return climbStairs(stairs-1) + climbStairs(stairs-2)
# Time : O(n) | Space : O(n)
def climbStairsDP(stairs):
if stairs < 2:
return 1
ways = [0 for _ in range(stairs)]
ways[0] = 1 # base case
ways[1] = 2 # base case
for index in range(2,stairs):
ways[index] = ways[index-1] + ways[index-2]
return ways[stairs-1]
assert climbStairs(4) == 5
assert climbStairsDP(4) == 5
# What if, instead of being able to climb 1 or 2 steps at a time,
# you could climb any number from a set of positive integers X?
# For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.
# Note : This is similar to the coin change problem but order matters
# Recursion
# l - possible number of steps | n - stairs
# Time : O(l^n) | Space : O(n) - recursion stack
def climbStairsAny(stairs ,steps_list):
n = stairs
X = steps_list
if n < 0:
return 0
elif n == 0:
return 1
elif n in X:
return 1 + sum(staircase(n - x, X) for x in X if x < n)
else:
return sum(staircase(n - x, X) for x in X if x < n)
# Dynamic Programming
# Time : O(mn) | Space : O(n)
def staircase(stairs, step_list):
cache = [0 for _ in range(stairs + 1)]
cache[0] = 1
for i in range(stairs + 1):
for x in step_list:
if i - x > 0:
cache[i] += cache[i - x]
cache[i] += 1 if i in step_list else 0
return cache[stairs]
print(climbStairsAny(4,[1,2]))
assert climbStairsAny(4,[1,2]) == 5
print(climbStairsAny(4,[3,2]))
print(staircase(4,[3,2]))
|
3422b9b245725603f8ae1800215010fbf69ae7e9
|
SergioJune/leetcode_for_python
|
/listNode/445.py
| 1,522 | 4.0625 | 4 |
"""
给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
示例:
输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# 这道题还可以使用栈来做,但是做法不够我这样好,我这个时间复杂度O(max(m+n)),空间复杂度O(max(m+n))
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
num1 = self.get_sum(l1)
num2 = self.get_sum(l2)
sum_num = num1 + num2
prev = None
while sum_num != 0:
node = ListNode(sum_num%10)
node.next = prev
prev = node
sum_num //= 10
if prev:
return prev
return ListNode(sum_num)
def get_sum(self, head):
num = 0
while head:
num = num * 10 + head.val
head = head.next
return num
|
10de9fb88df1c122de85351a2994cb36910db59c
|
jackmoody11/project-euler-solutions
|
/python/p003.py
| 606 | 3.703125 | 4 |
# Compute the max prime factor of 600,851,475,143
# It is easily verified that 71 is the
# smallest prime divisor, and thus we only need to check
# to sqrt of the number (it is not prime itself)
from math import sqrt
from utils import primes
def compute():
TARGET = 600_851_475_143
PRIMES = primes(int(sqrt(TARGET)) + 1)
max_div = 0
for p in PRIMES:
if TARGET % p == 0:
max_div = p
while TARGET % p == 0:
TARGET //= p
if TARGET > max_div:
return TARGET
else:
return max_div
if __name__ == '__main__':
print(compute())
|
0b0dd8d87a8bfc54baec6e62eb85e2f35c7ec034
|
ptkuo0322/SI507_Win2021
|
/Project/Final/TestingFIle/testing1.py
| 5,705 | 3.75 | 4 |
import time
def search_condition():
instruction = '''What kind of filtering condition would you like?
1. filtered by Rating first and ordered by ReviewCount.
2. filtered by Rating first and ordered by Price.
3. filtered by ReviewCount first and ordered by Rating.
4. filtered by ReviewCount first and ordered by Price.
5. filtered by Price first and ordered by Rating.
6. filtered by Price first and ordered by ReviewCount.
'''
option_list = ['1','2','3','4','5','6']
rating_list = ["0", '0.5','1.0','1.5','2.0','2.5','3.0','3.5','4.0','4.5','5.0']
price_list = ["0", '1','2','3','4','5']
while True:
print(instruction)
usr_input = input("what's your choice? from 1 to 6 ")
if usr_input in option_list:
if usr_input == "1":
query_list = ["R.Rating", "R.ReviewCount"]
print("Rating range:", rating_list)
usr_input2 =input("Enter the number, please! ")
if usr_input2 in rating_list:
query_list.append(usr_input2)
break
else:
print("invalid input!, please try again!")
elif usr_input == "2":
query_list = ["R.Rating", "R.Price"]
print("Rating range:", rating_list)
usr_input2 =input("Enter the number, please! ")
if usr_input2 in rating_list:
query_list.append(usr_input2)
break
else:
print("invalid input!, please try again!")
elif usr_input == "3":
query_list = ["R.ReviewCount", "R.Rating"]
print("ReviewCount range: at least 1")
usr_input2 =input("Enter the number, please! ")
if bool(int(usr_input2))==True and int(usr_input2) > 0:
query_list.append(usr_input2)
break
else:
print("invalid input!, please try again!")
elif usr_input == "4":
query_list = ["R.ReviewCount", "R.Price"]
print("ReviewCount range: at least 1")
usr_input2 =input("Enter the number, please! ")
if bool(int(usr_input2))==True and int(usr_input2) > 0:
query_list.append(usr_input2)
break
else:
print("invalid input!, please try again!")
elif usr_input == "5":
query_list = ["R.Price", "R.Rating"]
print("Price range:", price_list)
usr_input2 =input("Enter the number, please! ")
if usr_input2 in price_list:
query_list.append(usr_input2)
break
else:
print("invalid input!, please try again!")
elif usr_input == "6":
query_list = ["R.Price", "R.ReviewCount"]
print("Price range:", price_list)
usr_input2 =input("Enter the number, please! ")
if usr_input2 in price_list:
query_list.append(usr_input2)
break
else:
print("invalid input!, please try again!")
else:
print("invalid input!, please try again!")
return query_list
def search_order():
instruction = '''which order would you like?
1, in ascending order.
2, in descending order.
'''
option_list = ['1','2']
print(instruction)
while True:
usr_input = input("what's your choice? from 1 to 2 ")
if usr_input in option_list:
if usr_input == "1":
query_word = "ASC"
break
elif usr_input == "2":
query_word = "DESC"
break
else:
print("invalid input!, please try again!")
return query_word
def search_number():
instruction = '''How many data do you want to search?
ranging for 1 to 20
'''
print(instruction)
option_list = ["1",'2','3','4','5','6','7','8','9','10','11',"12",'13','14','15','16','17','18','19','20']
while True:
usr_input = input("what's your choice? from 1 to 20 ")
if usr_input in option_list:
query_word = usr_input
break
else:
print("invalid input!, please try again!")
return query_word
def sql_query():
query_string1 = '''SELECT F.RestaurantName, F.PhoneNumber, F.Rating, F.ReviewCount, F.Price FROM FOOD_RESULT
AS F JOIN RESTAURANT_RESULT AS R ON F.RefId = R.RefId
'''
init_list = search_condition()
b_word = search_order()
c_word = search_number()
init_list.append(b_word)
init_list.append(c_word)
query_string2 = f'WHERE {init_list[0]} > {init_list[2]} ORDER BY {init_list[1]} {init_list[3]} LIMIT {init_list[4]}'
return query_string1 + query_string2
search_cond = ["Rating", "ReviewCount", "Price"]
while True:
usr_answer1 = input("w")
def decide_sql_query():
rating_scale = ["0", '0.5','1.0','1.5','2.0','2.5','3.0','3.5','4.0','4.5','5.0']
price_scale = ["0", '1','2','3','4','5']
order_scale = ["ASC", "DESC"]
num_scale = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20']
default_list = ['A','B','C','DESC','10']
SELECT F.RestaurantName, F.PhoneNumber, F.Rating, F.ReviewCount, F.Price FROM FOOD_RESULT AS F JOIN RESTAURANT_RESULT AS R ON F.RefId = R.RefId
WHERE R.Rating > 4.0 ORDER BY R. ReviewCount DESC LIMIT 15
print(decide_sql_query())
|
9b993631cb0fdbbed6e708e5237d173e3d589c07
|
HalfMoonFatty/Interview-Questions
|
/313. Super Ugly Number.py
| 1,033 | 4.0625 | 4 |
'''
Problem:
Write a program to find the nth super ugly number.
Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k.
For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is the sequence of the first 12 super ugly numbers given primes = [2, 7, 13, 19] of size 4.
Note:
(1) 1 is a super ugly number for any given primes.
(2) The given numbers in primes are in ascending order.
(3) 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000.
'''
import sys
class Solution(object):
def nthSuperUglyNumber(self, n, primes):
res = [1]*n
ind = [0]*len(primes) # to store the base-index(in result) of prime numbers
for i in range(1,n):
res[i] = sys.maxint # note here
for j in range(len(primes)):
res[i] = min(res[i],primes[j]*res[ind[j]])
for j in range(len(primes)):
if res[i] == primes[j]*res[ind[j]]:
ind[j] += 1
return res[-1]
|
c674c17f45773718f2f0990bad1a39954d1890a5
|
misizeji/python_study_notes
|
/class-obj/ClassInherit3More.py
| 1,139 | 4.25 | 4 |
#!/usr/bin/python3
class People():
name = ''
age = 0
__weight = 0
def __init__(self, n, a, w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s says that I am %d years old"%(self.name, self.age))
class Student(People):
grade = 0
def __init__(self, n, a, w, g):
People.__init__(self, n, a, w)
self.grade = g
def speak(self):
print("%s says that I am %d years old, I am in grade %d"%(self.name, self.age, self.grade))
class Speaker():
topic = ''
name = ''
def __init__(self, n, t):
self.name = n
self.topic = t
def speak(self):
print("I am %s, a speech speaker, my topic is %s"%(self.name, self.topic))
class Sample(Speaker, Student):
a = ''
def __init__(self, n, a, w, g, t):
Student.__init__(self, n, a, w, g)
Speaker.__init__(self, n, t)
test = Sample("Tim", 25, 80, 9, "python")
# 方法同名,方法调用括号内,父类排列从左至右依次查找speak()方法,所以此处的speak()方法为speaker类里面的speak方法
test.speak()
|
d9e8c37c9c2095754700d55bde617b74b0e18bc6
|
Psami-wondah/Documents
|
/Escape Velocity and volume of a planet.py
| 462 | 3.875 | 4 |
import math
def escapevelocity(r,m):
g=(6.67430 * (10 ** (-11)))
Ve=(((2.0 * g * float(m)) / r) ** (1 / 2))
return Ve
def volume(r):
V=(float((4/3)*math.pi*(r**3)))
return V
r=input('Enter radius of planet in meters:\n')
r=int(r)
m=input('Enter mass of planet in kg:\n')
m=int(m)
print('The escape velocity of the planet is:',(escapevelocity(r, m)), 'm/s')
print('The volume of the planet is:', (volume(r)),('m^3'))
|
670fd7e0a8729ee7e1efece7354c9177ad680ea6
|
sandy-reddy/first_repo
|
/Python Practice Problems/practice_15_debig.py
| 155 | 3.578125 | 4 |
sent = "hi my name is sandeep"
sep_sent = sent.split()
print(sep_sent)
print (sep_sent[(len(sep_sent)) - 1])
print (sep_sent.index("sandeep")
)
|
c91d40cc2ed02542fdc750a499177d312d68b919
|
VictorTestov/Test1
|
/CALCULATOR.py
| 1,021 | 4 | 4 |
# -*- coding: utf-8 -*-
# програма Калькулятор
print "Вітаємо!"
loop = 1
choice = 0
while loop == 1:
print "Vuberit diy:"
print "1) Dodavannya"
print "2) Vidnimannya"
print "3) Mnojennya"
print "4) Dilennya"
print "5) Zakrutu kalkulyator"
choice = input("Oberit vashy diy: ")
if choice == 1:
num1 = input("Dodatu ce chuslo: ")
num2 = input("Do cyogo: ")
print num1, " + ", num2, " = ", num1 + num2
elif choice == 2:
num1 = input("Vidnimaemo chuslo: ")
num2 = input("vid: ")
print num2, " - ", num1, " = ", num2 - num1
elif choice == 3:
num1 = input("Mnojumo: ")
num2 = input("na: ")
print num1, " * ", num2, " = ", num1 * num2
elif choice == 4:
num1 = input("Dilumo chuslo: ")
num2 = input("na: ")
print num1, " / ", num2, " %= ", num1 / num2
elif choice == 5:
loop = 0
print "The end"
|
f676e5c9c8c58f968a9471b4ed92f12aba380c47
|
bagriffith/AMATH582
|
/HW4/code/evaluation.py
| 5,304 | 4.125 | 4 |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from itertools import combinations
import loadmnist
class NaiveClassifier:
"""A model classifier that randomly guesses a digit.
This was created as a simple test article to make sure the number_confusion
code worked indpendent of any model used.
"""
def fit(self, X, y):
self.choices = np.int8(list(set(y)))
def predict(self, X):
index = np.random.randint(0, len(self.choices), X.shape[0])
return self.choices[index]
def number_confusion(model, train_n, V):
"""Plots a how the model preforms at distinguising pairs of digits.
Args:
model: The model class. Should have functions fit(X, y) that trains the
model to identify labels y using data X and predict(X) that will
label data in the matrix X.
train_n (int): The number of example digits to train on.
V (array-like): A matrix to transform the data into the basis for
predictions.
"""
error_rate = np.full((10, 10), np.nan)
fig, ax = plt.subplots(figsize=(6, 4))
for digits in combinations(range(10), 2):
X, labels = loadmnist.load_data(numbers=digits,
size=train_n+(train_n//5))
Y = np.dot(V, X.T).T
model.fit(Y[:train_n], labels[:train_n])
model_lables = model.predict(Y[train_n:])
errors = np.sum(model_lables != labels[train_n:])
e = 100*errors / len(model_lables)
error_rate[digits[1], digits[0]] = e
ax.text(digits[0], digits[1], f'{e:0.1f}', c='k',
va='center', ha='center')
ax.set_xlim(-.5, 8.5)
ax.set_ylim(.5, 9.5)
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
X, Y = np.meshgrid(np.arange(11)-.5, np.arange(11)-.5)
m = np.nanmean(error_rate)
r = np.nanmax(np.abs(error_rate - m))
mesh = ax.pcolormesh(X, Y, error_rate, cmap='coolwarm', vmin=m-r, vmax=m+r)
l = np.floor(10*np.nanmin(error_rate))/10
r = np.ceil(10*np.nanmax(error_rate))/10
bounds = np.linspace(l, r, 512)
cbar = fig.colorbar(mesh, boundaries=bounds, label='Error Rate %')
cbar.set_ticks(MaxNLocator(8))
fig.savefig('HW4/figures/{}-digits_conf.pdf'.format(type(model).__name__),
bbox_inches='tight')
def full_classification(model, train_n, V):
"""Plots a how the model preforms at identifying digits.
Args:
model: The model class. Should have functions fit(X, y) that trains the
model to identify labels y using data X and predict(X) that will
label data in the matrix X.
train_n (int): The number of example digits to train on.
V (array-like): A matrix to transform the data into the basis for
predictions.
"""
frac_rate = np.full((10, 10), np.nan)
fig, ax = plt.subplots(figsize=(6, 4))
X, labels = loadmnist.load_data(size=train_n+(train_n//5))
Y = np.dot(V, X.T).T
model.fit(Y[:train_n], labels[:train_n])
model_lables = model.predict(Y[train_n:])
ax.set_xlabel('Real #')
ax.set_ylabel('Predicted #')
total = np.bincount(labels[train_n:])
for real in range(10):
for predict in range(10):
n = np.sum((model_lables == predict) & (labels[train_n:] == real))
frac = 100*n / total[real]
frac_rate[real, predict] = frac
c = 'w' if real == predict else 'k'
ax.text(real, predict, f'{frac:0.1f}', c=c,
va='center', ha='center')
ax.set_xlim(-.5, 9.5)
ax.set_ylim(-.5, 9.5)
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
X, Y = np.meshgrid(np.arange(11)-.5, np.arange(11)-.5)
off_diag = frac_rate.copy()
np.fill_diagonal(off_diag, np.nan)
ax.pcolormesh(X, Y, off_diag, cmap='YlOrRd', alpha=.4, vmin=0, vmax=11.2)
on_diag = np.full_like(off_diag, np.nan)
np.fill_diagonal(on_diag, 1)
on_diag *= frac_rate
m = np.nanmin(on_diag) - (np.nanmax(on_diag)-np.nanmin(on_diag))*.5
ax.pcolormesh(X, Y, on_diag, cmap='Greens', vmin=50, vmax=100)
fig.savefig('HW4/figures/{}-classification.pdf'.format(type(model).__name__),
bbox_inches='tight')
def digit_performance(model, train_n, V, digits):
"""Plots a how the model preforms at identifying digits.
Args:
model: The model class. Should have functions fit(X, y) that trains the
model to identify labels y using data X and predict(X) that will
label data in the matrix X.
train_n (int): The number of example digits to train on.
V (array-like): A matrix to transform the data into the basis for
predictions.
digits (list): List of digits to test on
"""
X, labels = loadmnist.load_data(numbers=digits,
size=train_n+(train_n//5))
Y = np.dot(V, X.T).T
model.fit(Y[:train_n], labels[:train_n])
model_lables = model.predict(Y[train_n:])
errors = np.sum(model_lables != labels[train_n:])
error_rate = 100*errors / len(model_lables)
return error_rate
|
90461670616c6142ab31feb81b6cb1e1f202f12a
|
xuanxuan-good/MyCode
|
/之前做过的/680.验证回文字符串-ⅱ.py
| 1,897 | 3.609375 | 4 |
#
# @lc app=leetcode.cn id=680 lang=python3
#
# [680] 验证回文字符串 Ⅱ
#
# @lc code=start
class Solution:
def validPalindrome(self, s: str) -> bool:
# 最多删除一个字符的情况,是否可以构成回文串
# 1.暴力,逐个删除字符,再遍历判断是否回文O(N^2)
'''
# 2.双指针,当碰到有不相等的时候,删除左边或者右边,再判断剩下的是否是回文
isPalindrome = lambda x : x == x[::-1]
strPart = lambda s, x : s[:x] + s[x+1:]
left, right = 0, len(s)-1
while left < right:
if s[left] != s[right]:
return isPalindrome(strPart(s,left)) or isPalindrome(strPart(s, right))
left += 1
right -= 1
return True
'''
'''
# 3.改进版双指针,被删除字符的两边不需要再判断,只要判断中间是否是回文即可 即(left, right] or [left, right)
isPalindrome = lambda x : x == x[::-1]
left, right = 0, len(s)-1
while left < right:
if s[left] != s[right]:
return isPalindrome(s[left:right]) or isPalindrome(s[left+1:right+1])
left += 1
right -= 1
return True
'''
# 4.贪心+双指针 [和3相同,只是x[::-1]换一种原地写法,使得空间复杂度降为O(1)] !!!索引位置
def isPalindrome(left, right):
l, r = left, right
while l < r:
if s[l] != s[r]:
return False
l += 1
r -= 1
return True
left, right = 0, len(s)-1
while left < right:
if s[left] != s[right]:
return isPalindrome(left, right-1) or isPalindrome(left+1, right)
left += 1
right -= 1
return True
# @lc code=end
|
8fce955147527ddf889c22b62864de271d9c605a
|
WWPOL/CV-Pong
|
/game/app/util/log.py
| 835 | 3.6875 | 4 |
class Enum(set):
def __getattr__(self, name):
if name in self:
return name
raise AttributeError
def log(message, log_class, log_level):
"""Log information to the console.
If you are angry about having to use Enums instead of typing the classes and levels in, look up how any logging facility works.
Arguments:
message -- the relevant information to be logged
log_class -- the category of information to be logged. Must be within util.log.LogClass
log_level -- the severity of the information being logged. Must be within util.log.LogLevel
"""
assert log_class in LogClass
assert log_level in LogLevel
print("%s/%s: %s" % (log_level, log_class, message))
LogClass = Enum(["CV", "GRAPHICS", "GENERAL"])
LogLevel = Enum(["VERBOSE", "INFO", "WARNING", "ERROR"])
|
128b09ac61e695997c340171f066c21245b18309
|
pimvermeij/huiswerk1
|
/NS functies.py
| 1,112 | 3.71875 | 4 |
def standaardPrijs(afstandKM):
'berkent de prijs door middel van de afstand als float'
if afstandKM < 50:
prijs = afstandKM * 0.8
elif afstandKM <= 0:
prijs = 0
elif afstandKM >= 50:
prijs = 15 + (afstandKM * 0.6)
return prijs
def ritprijs(leeftijd, weekendrit, afstandKM):
'berekent de ritprijs incl. korting met leeftijd als int, weekendrit als ja of nee en afstandKM als int'
if (leeftijd < 12 or leeftijd >= 65) and weekendrit == True:
korting = standaardPrijs(afstandKM) * 0.65
elif leeftijd < 12 or leeftijd >= 65:
korting = standaardPrijs(afstandKM) * 0.7
elif (leeftijd >= 12 and leeftijd < 65) and weekendrit == True:
korting = standaardPrijs(afstandKM) * 0.6
else:
korting = standaardPrijs(afstandKM)
return korting
leeftijd = float(input("hoe oud ben je?"))
weekendrit = input ("is het weekend?")
afstandKM = float(input("wat is de afstand in kilometers?"))
if weekendrit == "ja":
weekendrit = True
elif weekendrit == "nee":
weekendrit = False
print(ritprijs(leeftijd, weekendrit, afstandKM))
|
4e9e58784f137883eed784e09668e046e7194be3
|
Loaye/Math-Series
|
/test_series.py
| 1,953 | 3.609375 | 4 |
"""Test for math series."""
def test_fib_zero():
'''Test fib function to check value 0 of fibonacci'''
from series import fib
assert fib(0) == 0
def test_fib_one():
'''Test fib function to check value 1 of fibonacci'''
from series import fib
assert fib(1) == 0
def test_fib_two():
'''Test fib function to check value 2 of fibonacci'''
from series import fib
assert fib(2) == 1
def test_fib_five():
'''Test fib function to check value 5 of fibonacci'''
from series import fib
assert fib(5) == 3
def test_fib_seven():
'''Test fib function to check value 7 of fibonacci'''
from series import fib
assert fib(7) == 8
def test_lucas_zero():
'''Test lucas function to check value of 0'''
from series import lucas
assert lucas(0) == 0
def test_lucas_one():
'''Test lucas function to check value of 1'''
from series import lucas
assert lucas(1) == 2
def test_lucas_two():
'''Test lucas function to check value of 2'''
from series import lucas
assert lucas(2) == 1
def test_lucas_four():
'''Test lucas function to check value of 4'''
from series import lucas
assert lucas(4) == 4
def test_lucas_eight():
'''Test lucas function to check value of 8'''
from series import lucas
assert lucas(8) == 29
def test_sum_series_zero():
"""Test sum_series to check value of 0"""
from series import sum_series
assert sum_series(0) == 0
def test_sum_series_fib():
"""Test sum_series to check value of 1 for x and y defaults"""
from series import sum_series
assert sum_series(1) == 0
def test_sum_series_lucas():
"""Test sum_series to check value of eight for x=2 y=1"""
from series import sum_series
assert sum_series(8, 2, 1) == 29
def test_sum_series_five_three_one():
"""Test sequence is... 3, 1, 4, 5, 9, 14, 23"""
from series import sum_series
assert sum_series(5, 3, 1) == 9
|
f9950ff7f3a34f1db57cd8af72f675738725e78a
|
yred/euler
|
/python/problem_072.py
| 1,750 | 4 | 4 |
# -*- coding: utf-8 -*-
"""
Problem 72 - Counting fractions
Consider the fraction, n/d, where n and d are positive integers. If n<d and
HCF(n,d)=1, it is called a reduced proper fraction.
If we list the set of reduced proper fractions for d ≤ 8 in ascending order of
size, we get:
1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8,
2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8
It can be seen that there are 21 elements in this set.
How many elements would be contained in the set of reduced proper fractions for
d ≤ 1,000,000?
"""
from itertools import takewhile
from math import log
from common import primes_up_to
def factors(n, primes):
"""Yields the prime factors of n, along with their orders"""
for p in takewhile(lambda p: p*p < n, primes):
exponent = 0
while n % p == 0:
exponent += 1
n /= p
if exponent > 0:
yield p, exponent
if n > 1:
yield n, 1
def solution():
limit = 10**6
plist = list(primes_up_to(limit))
# Initialize a dict to hold the totient values of all integers up to
# `limit`, starting with those of primes and their powers
phi = {p**k: (p**(k-1)) * (p - 1)
for p in plist for k in range(1, int(log(limit, p)) + 1)}
for n in range(2, limit+1):
if n not in phi:
# Uses the fact that φ(a*b) = φ(a)*φ(b) when gcd(a, b) = 1
phi[n] = reduce(lambda a, b: a*b,
(phi[p**k] for p, k in factors(n, plist)), 1)
# The number of reduced proper fractions is simply the sum of phi values
# for numbers up to and including `limit`
return sum(phi.values())
if __name__ == '__main__':
print(solution())
|
4d501c25eaf3b639f131e094be63aaa0c157115b
|
amajung/SI507-Project2
|
/movies_tools.py
| 332 | 3.53125 | 4 |
# Define a class Movie that accepts as constructor input one row of the movies_clean.csv file
class Movie():
def __init__(self, row):
cells = row.strip().split(',')
self.title = cells[0]
self.IMDBrating = cells[14]
def __str__(self):
return "{} | {}<br>".format(self.title, self.IMDBrating)
|
737d8fe463b9086c63e4f06b0a36f734f61d954f
|
denisnmurphy/workingwithdata
|
/tkinter1.py
| 178 | 3.828125 | 4 |
import tkinter as tk
from tkinter import *
btn=Button()
btn.pack()
btn["text"]="Hello everyone!"
def click():
print("You just clicked me!")
btn["command"]=click
tk.mainloop()
|
e39f3d166a168a3f8bdf1a5243aaedd62bb95dff
|
pflun/advancedAlgorithms
|
/generatePossibleNextMoves.py
| 822 | 3.8125 | 4 |
# -*- coding: utf-8 -*-
# You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend
# take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other
# person will be the winner.
# Write a function to compute all possible states of the string after one valid move.
class Solution:
def generatePossibleNextMoves(self, s):
if len(s) < 2:
return []
res = []
for i in range(len(s) - 1):
if s[i] == '+' and s[i + 1] == '+':
tmp = list(s)
tmp[i], tmp[i + 1] = '-', '-'
res.append(''.join(tmp))
return res
test = Solution()
print test.generatePossibleNextMoves("++++")
|
d7df128a101b8149cd77e747034606b2bdac94af
|
AishwaryalakshmiSureshKumar/DS-Algo
|
/linkedlist_sorted_merge.py
| 1,532 | 3.96875 | 4 |
def sortedMerge(head1, head2):
temp = Node(None)
result = temp
if head1 is None:
return head2
if head2 is None:
return head1
while(head1 is not None and head2 is not None):
if head1.data<=head2.data:
result.next = head1
head1 = head1.next
else:
result.next = head2
head2 = head2.next
result = result.next
if head1 is None:
result.next = head2
elif head2 is None:
result.next = head1
return temp.next
def printList(n):
while n is not None:
print(n.data, end=' ')
n = n.next
print()
class Node:
def __init__(self, val):
self.data = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, val):
new_node = Node(val)
if self.head==None:
self.head = new_node
return
last = self.head
while(last.next):
last = last.next
last.next = new_node
test_case = int(input())
for i in range(test_case):
n,m=list(map(int, input().strip().split()))
a= LinkedList()
b= LinkedList()
value1 = list(map(int, input().strip().split()))
value2 = list(map(int, input().strip().split()))
for x in value1:
a.push(x)
for x in value2:
b.push(x)
printList(sortedMerge(a.head,b.head))
|
f1701505a1adee8763ff6fbeec19d03d94f53ae6
|
begarn/python-training
|
/day3/Deck.py
| 1,312 | 3.78125 | 4 |
#! /usr/bin/env python3
# -*- coding : UTF-8 -*
from Card import Card
import random
class Deck:
def __init__(self, empty = False):
# self.deck = []
# for color in Card.colors:
# for value in Card.values:
# self.deck.append(Card(color, value))
if not empty:
self.__deck = list(Card(color, value) for color in Card.colors for value in Card.values)
else:
self.__deck = []
def getDeck(self):
return self.__deck
def setDeck(self, card):
self.__deck.append(card)
deck = property(getDeck, setDeck)
def __str__(self):
# return ', '.join(str(card) for card in self.__deck)
return ', '.join(str(card) for card in self.deck)
def mix(self):
# return random.shuffle(self.__deck)
return random.shuffle(self.deck)
def take(self):
try:
# return self.__deck.pop(0)
return self.deck.pop(0)
except:
raise Exception('The deck is empty')
if __name__ == '__main__':
cg = Deck()
c = cg.take()
print(c)
#print(len(cg.deck))
# print(cg)
# cg.mix()
# print('\n' + str(cg))
# try:
# while True:
# print(cg.take())
# except Exception as e:
# print(str(e))
|
f75a6b9ea125c411d35774a5c5e8c61640991d0f
|
tbilsbor/Euler-Python
|
/Euler#29/Euler#29.py
| 300 | 3.953125 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 26 12:56:53 2018
@author: toddbilsborough
"""
#How many distinct terms are in the sequence
# generated by a ** b for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?
terms = len(set([a ** b for a in range(2, 101) for b in range(2, 101)]))
|
8964012113d6b9a9681cb0f26e4fbb27de65c57c
|
shivngishrma23/FSDP19
|
/day1/mini.py
| 216 | 3.6875 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Tue May 7 18:56:15 2019
@author: Shivangi Sharma
"""
import random
guess=0
name=input("enter you rname")
while(g<6):
print("try again")
g=g+1
print("no more guesses left")
|
35fc4873c00db36fc8c958f5227d8590dc78e7f6
|
jarbhav/CCBD
|
/Approach 2/new_latest.py
| 6,981 | 3.671875 | 4 |
from __future__ import division
import math
import turtle
import random
import time
pointer=turtle.Turtle()
screen=turtle.Screen()
screen.bgcolor('white')
pointer.shape("arrow")
pointer.color("white")
pointer.width(1.1)
#pointer.goto(0,0)
pointer.speed(100)
#equation=[]
color=["green","red","blue","orange","black","yellow"]
#random
start = time.time()
#intersection
def line(p1, p2):
A = (p1[1] - p2[1])
B = (p2[0] - p1[0])
C = (p1[0]*p2[1] - p2[0]*p1[1])
return A, B, -C
def intersection(L1, L2):
D = L1[0] * L2[1] - L1[1] * L2[0]
Dx = L1[2] * L2[1] - L1[1] * L2[2]
Dy = L1[0] * L2[2] - L1[2] * L2[0]
if D != 0:
x = Dx / D
y = Dy / D
return [x,y]
else:
return False
def inter(equation,i,k):
p=0
#print(len(equation))
if(len(equation)>=2):
for j in range(0,len(equation)-1):
L1=line(equation[j][0],equation[j][1])
L2=line(i,k)
R = intersection(L1, L2)
if(R):
distance_1=math.sqrt((i[0]-k[0])**2+(i[1]-k[1])**2)
distance_2=math.sqrt((i[0]-R[0])**2+(i[1]-R[1])**2)
if(R==i):
# print(0)
return 0
if(distance_1>distance_2):
# print(distance_1,distance_2)
# print(R)
# print([equation[j][0],equation[j][1]],[i,k],j)
#print(1)
# print(1)
return 1
#print(0)
return 0
def checkquadrant(a,b):
if (a[0]>b[0] and a[1]>b[1]):
return 1
elif (a[0]<b[0] and a[1]>b[1]):
return 2
elif (a[0]<b[0] and a[1]<b[1]):
return 3
elif (a[0]>b[0] and a[1]<b[1]):
return 4
elif (a[1]==b[1]):
if (a[0]>b[0]):
return 5 #0
else:
return 6 #180
elif (a[0]==b[0]):
if (a[1]>b[1]):
return 7 #90
else:
return 8 #270
sum=0
new=[]
x0=0
y0=0
plot=[]
for k in range(0,6):
ran=[]
for i in range(0,(10-k)*10):
x=random.randint(-100,100)
y=random.randint(-100,100)
while((x0-x)**2 < 1000 ):
x0=x
x=random.randint(-(10-k)*10,(10-k)*10)
while((y0-y)**2 < 1000 ):
y0=y
y=random.randint(-(10-k)*10,(10-k)*10)
ran.append([x,y])
x0=x
y0=y
plot.append(ran)
def find_area_perim(new):
a = 0
p = 0
ox,oy = new[0]
for x,y in new[1:]:
a += (x*oy-y*ox)
p += abs((x-ox)+(y-oy)*1j)
ox,oy = x,y
return a/2,p
dimensions=[]
cen=[]
def centroid(array):
xaxis=0
yaxis=0
for i in range(0,len(array)):
xaxis=array[i][0]+xaxis
yaxis=array[i][1]+yaxis
xaxis=xaxis/len(array)
yaxis=yaxis/len(array)
return xaxis,yaxis
ends=[]
def endpoints(mid,array):
x1,y1=mid[0],mid[1]
x2,y2=mid[0],mid[1]
x3,y3=mid[0],mid[1]
x4,y4=mid[0],mid[1]
for i in array:
if (i[0] > mid[0] and i[1] >mid[1]):
x1=i[0]
y1=i[1]
elif(i[0] < mid [0] and i[1] > mid[1]):
x2=i[0]
y2=i[1]
elif(i[0] < mid [0] and i[1] < mid[1]):
x3=i[0]
y3=i[1]
else:
x4=i[0]
y4=i[1]
ends.append([[x1,y1],[x2,y2],[x3,y3],[x4,y4]])
points_new=[[[1.81,11.23],[ 18.41 ,69.81999999999999],[ 22.42, 92.19], [24.18 ,30.65],[ 47.47 ,90.33],[ 48.98, 84.06999999999999],[ 69.18000000000001, 43.04], [99.92 ,34.4], [51.1 ,1.53], [40.72 ,14.39], [1.81, 11.23]],[[10.3 ,29.74], [27.22, 56.87], [46.11, 66.89],[ 49.61, 72.75], [68.48, 74.36], [75.20999999999999 ,87.81999999999999],[ 82.87 ,85.56999999999999], [84.81999999999999, 73.45], [86.79000000000001 ,58.28], [99.03 ,24.49], [19.56 ,5.74], [10.3 ,29.74]],[[7.41 ,66.93000000000001], [11.12 ,99.22], [18.73, 72.48999999999999], [95, 88.53], [98.05, 77.06], [89.59 ,53.08], [85.19 ,61.03], [82.01000000000001 ,53.15], [81.51000000000001, 14.68], [43.68, 47.78], [33.96 ,22.93], [18.28 ,42.79], [7.41 ,66.93000000000001]],[[0.24, 57.37], [9.08, 91.29000000000001], [24.93 ,67.41], [30.05, 58.46], [42.54, 54.66], [46.9 ,54.56], [78.77 ,48.43], [68.45 ,46.67], [65.8 ,8.550000000000001], [31.04 ,53.75], [26.02, 18.25], [21.69 ,6.19], [12.28 ,21.54], [0.24 ,57.37]]]
"""for f in range(0,3):
ran=plot[f]
new=[]
k=[ran[0][0],ran[0][1]]
pointer.color(color[f])
pointer.goto(ran[0][0],ran[0][1])
equation=[]"""
for f in range(0,len(points_new)):
ran=points_new[f]
new=[]
k=[ran[0][0],ran[0][1]]
pointer.color("white")
pointer.goto(ran[0][0],ran[0][1])
pointer.color(color[f])
equation=[]
for i in range(1,len(ran)):
sum=sum+1
# print(1)
distance=math.sqrt(((ran[i][0]-k[0])**2)+((ran[i][1]-k[1])**2))
top=k[1]-ran[i][1]
bottom=k[0]-ran[i][0]
q=checkquadrant(ran[i],k)
if q==1 or q==4:
angle=math.atan(top/bottom)*180/math.pi
#pointer.left(angle)
elif q==2:
angle=math.atan(top/bottom)*180/math.pi
angle=angle+180
#pointer.left(angle)
elif q==3:
angle=math.atan(top/bottom)*180/math.pi
angle=180+angle
#pointer.left(angle)
elif q==5:
angle=0
#pointer.left(angle)
elif q==6:
angle=180
#pointer.left(angle)
elif q==7:
angle=90
#pointer.left(angle)
else:
angle=270
#pointer.left(angle)
#equation.append([i,k])
l=0
#print(equation)
a=inter(equation,ran[i],k)
if(a==0):
pointer.left(angle)
pointer.forward(distance)
pointer.left(-angle)
kp=[[ran[i][0],ran[i][1]],[k[0],k[1]]]
equation.append(kp)
k[0]=ran[i][0]
k[1]=ran[i][1]
new.append(ran[i])
pointer.goto(ran[0][0],ran[0][1])
area=find_area_perim(new)
qw=centroid(new)
cen.append(qw)
endpoints(qw,new)
dimensions.append(area)
#print(angle)
#pointer.goto(new[0][0],new[0][1])
#pointer.goto(0,0)
for i in range(0,2):
print(dimensions[i],cen[i],ends[i])
#print(i,k)
"""o=[ran[0][0],ran[0][1]]
x=True
j=len(new)-1
while(x and j!=1):
q=inter(equation,new[j],o)
if(q==0):
pointer.goto(new[0][0],new[0][1])
x=True
else:
pointer.color("black")
pointer.goto(new[j-1][0],new[j-1][1])
pointer.color("red")
j=j-1
if(j==1):
print("not found")"""
end = time.time()
print(end-start)
|
0c7fe52667fa2f8bad06b5a2e4d9d40cb854e25f
|
jpaulo-kumulus/KumulusAcademy
|
/Exercícios José/Create your first Python program/challenge1.py
| 392 | 3.78125 | 4 |
print("Today's day?")
day = input()
print("Breakfast calories?")
breakCalories = int(input())
print("Lunch calories")
lunchCalories = int(input())
print("Dinner calories")
dinnerCalories = int(input())
print("Sack calories")
snackCalories = int(input())
sum = breakCalories + lunchCalories + dinnerCalories + snackCalories
print("Calories content for " + day + " is : " + str(sum))
print(sum)
|
eb71eb333fc921ef98c64956822a033897d494a3
|
yi-fan-wang/bilby
|
/examples/core_examples/linear_regression_unknown_noise.py
| 2,168 | 3.5625 | 4 |
#!/usr/bin/env python
"""
An example of how to use bilby to perform parameter estimation for
non-gravitational wave data. In this case, fitting a linear function to
data with background Gaussian noise with unknown variance.
"""
from __future__ import division
import bilby
import numpy as np
import matplotlib.pyplot as plt
# A few simple setup steps
label = 'linear_regression_unknown_noise'
outdir = 'outdir'
bilby.utils.check_directory_exists_and_if_not_mkdir(outdir)
# First, we define our "signal model", in this case a simple linear function
def model(time, m, c):
return time * m + c
# Now we define the injection parameters which we make simulated data with
injection_parameters = dict(m=0.5, c=0.2)
# For this example, we'll inject standard Gaussian noise
sigma = 1
# These lines of code generate the fake data. Note the ** just unpacks the
# contents of the injection_parameters when calling the model function.
sampling_frequency = 10
time_duration = 10
time = np.arange(0, time_duration, 1 / sampling_frequency)
N = len(time)
data = model(time, **injection_parameters) + np.random.normal(0, sigma, N)
# We quickly plot the data to check it looks sensible
fig, ax = plt.subplots()
ax.plot(time, data, 'o', label='data')
ax.plot(time, model(time, **injection_parameters), '--r', label='signal')
ax.set_xlabel('time')
ax.set_ylabel('y')
ax.legend()
fig.savefig('{}/{}_data.png'.format(outdir, label))
injection_parameters.update(dict(sigma=1))
# Now lets instantiate the built-in GaussianLikelihood, giving it
# the time, data and signal model. Note that, because we do not give it the
# parameter, sigma is unknown and marginalised over during the sampling
likelihood = bilby.core.likelihood.GaussianLikelihood(time, data, model)
priors = dict()
priors['m'] = bilby.core.prior.Uniform(0, 5, 'm')
priors['c'] = bilby.core.prior.Uniform(-2, 2, 'c')
priors['sigma'] = bilby.core.prior.Uniform(0, 10, 'sigma')
# And run sampler
result = bilby.run_sampler(
likelihood=likelihood, priors=priors, sampler='dynesty', npoints=500,
sample='unif', injection_parameters=injection_parameters, outdir=outdir,
label=label)
result.plot_corner()
|
7ddbab0c7f4942cfa4997d6742dd2a3c5702fd53
|
siri-palreddy/CS550-FallTerm
|
/CS-HW/HW10-15-17:MineSweeperProject.py
| 2,341 | 3.984375 | 4 |
import sys
import random
import math
def getRow(cellNumber):
rowNumber = math.ceil(cellNumber/totalColumns)
return rowNumber
def getColumn(cellNumber):
columnNumber = cellNumber%totalColumns
if columnNumber == 0:
columnNumber = totalColumns
return columnNumber
try:
totalRows = int(input('How many rows would you like?'))
totalColumns = int(input('How many columns would you like?'))
mines = int(input('How many mines would you like?'))
except ValueError:
print('Please enter valid numbers. Don\'t trick me!')
exit()
totalCells = totalRows * totalColumns
# print(totalRows, totalColumns, mines)
if mines > (totalCells/10):
print('You cannot have more than 10 percent of your cells as mines.')
exit()
mineBoard = [[0 for x in range(totalColumns)] for x in range(totalRows)]
randMines = list()
for i in range(mines):
mineLocation = random.randint(1, (totalCells + 1))
# To avoid duplicate mines
while (mineLocation in randMines):
mineLocation = random.randint(1, (totalCells + 1))
randMines.append(mineLocation)
for i in range(totalRows):
print(mineBoard[i])
print (randMines)
for i in randMines: # As index starts with zero we need to adjust the index
mineRow = getRow(i) - 1
mineColumn = getColumn(i) - 1
print(mineRow)
print(mineColumn)
mineBoard[mineRow][mineColumn] = 100
if (mineRow > 0):
mineBoard[mineRow - 1][mineColumn] += 1
if (mineColumn > 0):
mineBoard[mineRow - 1][mineColumn - 1] += 1
if (mineColumn < (totalColumns - 1)):
mineBoard[mineRow - 1][mineColumn + 1] += 1
if (mineRow < (totalRows - 1)):
mineBoard[mineRow + 1][mineColumn] += 1
if (mineColumn > 0):
mineBoard[mineRow + 1][mineColumn - 1] += 1
if (mineColumn < (totalColumns - 1)):
mineBoard[mineRow + 1][mineColumn + 1] += 1
if (mineColumn > 0):
mineBoard[mineRow][mineColumn - 1] += 1
if (mineColumn < (totalColumns - 1)):
mineBoard[mineRow][mineColumn + 1] += 1
for i in range(totalRows):
mineBoard[i] = ['*' if x>99 else x for x in mineBoard[i]]
for i in range(totalRows):
#Using the map function to call str for each element of mineBoard[i]
#Creating a new list of strings and join into one string with str.join.
#Then string formatting is used
# print ('[%s]' % ', '.join(map(str, mineBoard[i])))
print(' '.join(map(str, mineBoard[i])))
|
4d6a21ebffb7a92a3479ee001c9279516f41487d
|
ihzarizkyk/LearnPython3byIhza
|
/fungsi-kuadrat-kali.py
| 1,207 | 3.625 | 4 |
'''
Author : Mochammad Ihza Rizky Karim
'''
#buat fungsi kuadrat yang didalamnya memuat parameter angka
def kuadrat(angka):
#lalu kembalikan nilai angka dan kuadratkan
return angka*angka
#buat variabel nol sampe sembilan yang menyimpan fungsi kuadrat
#beserta angka 0 - 9
nol = kuadrat(0)
satu = kuadrat(1)
dua = kuadrat(2)
tiga = kuadrat(3)
empat = kuadrat(4)
lima = kuadrat(5)
enam = kuadrat(6)
tujuh = kuadrat(7)
delapan = kuadrat(8)
sembilan = kuadrat(9)
#ini untuk mencetak output fungsi diatas
print("kuadrat dari 0 adalah ",nol)
print("kuadrat dari 1 adalah ",satu)
print("kuadrat dari 2 adalah ",dua)
print("kuadrat dari 3 adalah ",tiga)
print("kuadrat dari 4 adalah ",empat)
print("kuadrat dari 5 adalah ",lima)
print("kuadrat dari 6 adalah ",enam)
print("kuadrat dari 7 adalah ",tujuh)
print("kuadrat dari 8 adalah ",delapan)
print("kuadrat dari 9 adalah ",sembilan)
#ini menggunakan fungsi
#buat fungsi kali yang memuat 2 parameter argumen
def kali(bil1,bil2):
#buat perulangan dari bilangan 1 dan bilangan 2 dengan range 3 - 11 dengan
#jeda 2
for bil1 in range(3,13,2):
print("\t")
for bil2 in range(3,13,2):
#print dengan format berikut
print('{}*{} = {}\t'.format(bil1,bil2,bil1*bil2))
|
dc7f30a9a94f5d89c9cf12d96991624252abfb1e
|
koziscool/embankment_5
|
/e17.py
| 1,058 | 3.5 | 4 |
import time
num_letters = { 0:0, 1:3, 2:3, 3:5, 4:4, 5:4, 6:3, 7:5, 8:5, 9:4, 10:3,
11:6, 12:6, 13:8, 14:8, 15:7, 16:7, 17:9, 18:8, 19:8, 20:6,
30:6, 40:5, 50:5, 60:5, 70:7, 80:6, 90:6, 100:10,
200:10, 300:12, 400:11, 500:11, 600:10, 700:12, 800:12, 900:11, 1000:11 }
def e17():
def num_word_length( num ):
if num in num_letters:
return num_letters[num]
if num >= 100:
huns = num / 100
hunRem = num % 100
return num_word_length( huns * 100 ) + 3 + num_word_length( hunRem )
ones = num % 10
tens = num / 10 % 10
return num_word_length( tens * 10 ) + num_word_length( ones )
end_range = 1000
return sum( num_word_length(i) for i in xrange(1, end_range + 1) )
if __name__ == '__main__':
start = time.time()
print
print "Euler 17 solution is:", e17()
end = time.time()
print "elapsed time is: %.4f milliseconds" % (1000 * (end - start))
|
34223771c4676e81555b049b9a80601745ce30a6
|
Pixaurora/Desmos-Calculator-Generator
|
/components/gates.py
| 3,987 | 3.59375 | 4 |
from .component import Component
class LogicGate(Component):
"""An arbitrary Logic Gate.
By default, no conversion or computation is implemented, but is instead
implemented by the other children classes.
Attributes
----------
inputs: List[Component]
A list of all the inputs to the Logic Gate. By default, any type is
allowed however.
kind: str
The kind of gate. This is usually handled by the internal classes
only.
"""
__slots__ = ('inputs', 'kind')
def __init__(self, kind: str, required_inputs: int, *inputs):
"""Creates the Logic Gate.
Arguments
---------
kind: str
required_inputs: int
The amount of inputs allowed to be inputted.
*inputs: List[Union[LogicGate, Bit]]
"""
self.kind = kind
if len(inputs) == required_inputs:
self.inputs = inputs
else:
raise KeyError("Too few or too many inputs entered.")
def __getitem__(self, index: int):
"""Used to replicate list-like syntax with LogicGate[index]
Arguments
---------
index: int
"""
return self.inputs[index]
def compute(self):
"""Computes the gate's value."""
raise NotImplementedError("This internal class isn't meant to be used.")
def __str__(self):
"""Convert the Logic Gate to a string in the syntax of Python.
IE LogicGate(*inputs) and also convert those inputs to a string and so
on...
"""
return f'{self.kind}({", ".join([str(i) for i in self.inputs])})'
def convert_latex(self, as_list=False):
"""Convert the Logic Gate to a string in the syntax of LaTeX.
This one is much more complicated as the math that it gets converted to
may vary.
"""
raise NotImplementedError("This internal class isn't meant to be used.")
class And(LogicGate):
"""An AND Logic Gate."""
def __init__(self, *inputs):
super().__init__("And", 2, *inputs)
def compute(self):
return self[0].compute() & self[1].compute()
def convert_latex(self, as_list=False):
I = self[0].convert_latex(as_list=True)
J = self[1].convert_latex(as_list=True)
return_list = []
for i in I:
for j in J:
return_list.append(f'{i}{j}')
return return_list if as_list else '+'.join(return_list)
class Or(LogicGate):
"""An OR Logic Gate."""
def __init__(self, *inputs):
super().__init__("Or", 2, *inputs)
def compute(self):
return self[0].compute() | self[1].compute()
def convert_latex(self, as_list=False):
"""Converts the gate to LaTeX code, for use in Desmos."""
left = '{'
right = '}'
return_statement = f'\\operatorname{left}sign{right}\\left({self[0].convert_latex()}+{self[1].convert_latex()}\\right)'
return [return_statement] if as_list else return_statement
class Xor(LogicGate):
"""An XOR Logic Gate."""
def __init__(self, *inputs):
super().__init__("Xor", 2, *inputs)
def compute(self):
return self[0].compute() ^ self[1].compute()
def convert_latex(self, as_list=False):
"""Converts the gate to LaTeX code, for use in Desmos."""
return_statement = f'\\left|{self[0].convert_latex()}-{"-".join(self[1].convert_latex(as_list=True))}\\right|'
return [return_statement] if as_list else return_statement
class Not(LogicGate):
"""An NOT Logic Gate."""
def __init__(self, input):
super().__init__("Not", 1, input)
def compute(self):
return not self[0].compute()
def convert_latex(self, as_list=False):
"""Converts the gate to LaTeX code, for use in Desmos."""
return_statement = f'1-{self[0].convert_latex()}'
return [return_statement] if as_list else return_statement
|
f50044c8f432e4512d6fe6b97e0f51d7e8bd3a75
|
XiwangLi/LeetcodeArchive
|
/String/Leetcode_String.py
| 8,856 | 3.71875 | 4 |
# coding: utf-8
## 1: Implement strStr() Leetcode 28
# The first question is StrStr. It is the first problem in almost all the books of pactice material
# The brute force way of solve this problem is very easy and the time-complexity is O(m*n).
# Everybody will say, the brute force O(m*n) method is not good. We want better one. People recommended KMP.
# I also tried KMP,but it is so hard to follow. So here I will try another algorithem called Robin-Karp.
# The whole idea is to scan over the string and adding the new one/deleting the first one at the same time
def strstrBF(haystack, needle):
m, n = len(haystack), len(needle)
for i in range(m -n + 1):
if haystack[i: i + n] == needle:
return i
return -1
def RobinKarp(haystack, needle):
base = 26
# calculate the hash for haystack (the first n-lenght substring) and needle
hash_h = reduce(lambda h, c: h * base + ord(c), haystack[: len(needle)], 0)
hash_n = reduce(lambda h, c: h * base + ord(c), needle, 0)
power = max(base ** (len(needle) - 1), 0) # in case len(needle) is 0, how many time that ord(c) mutiplied by base
for i in range(len(needle), len(haystack)): #then scan the whole string ahead
if hash_h == hash_n:
return i - len(needle)
hash_h -= power * ord(haystack[i - len(needle)]) # substract the first chara
hash_h = hash_h * base + ord(haystack[i])
if hash_h == hash_n:
return len(haystack) - len(needle) # check the last substring
return -1
print strstrBF('haystack', 'yst')
print RobinKarp('haystack', 'yst')
## 2: Reverse Words in a String II
# The key idea of solving this problem is to "reverse the string TWICE"
# Given s = "the sky is blue",
# reverse onceL eht yks si eulb ---> find the space and reverse the word
# reverse twice: blue is sky the --> reverse the whole string
def reverseWords(s):
s.split()
idx = 0
for i in range (len(s)):
if s[i] == ' ':
s[idx : i] = reversed(s[idx : i])
idx = i + 1
s[idx :] = reversed(s[idx : ])
s.reverse()
# # 3: Decode Ways
#
# For example,
# Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
# The number of ways decoding "12" is 2.
# This is a string + Dynamic problem question. As we need to count the decode ways from the frist str to ith str
def numDecodings(s):
if not s or len(s) == 0 or s[0] == '0': return 0
DP = [0] * (len(s) + 1)
DP[0] = 1
for i in range(1, len(s) + 1):
if s[i - 1] != '0':
DP[i] += DP[i - 1] #one char
if i > 1 and s[i - 2 : i] >= '10' and s[i - 2 : i] <= '26':
DP[i] += DP[i - 2] #two char
return DP[-1]
print numDecodings('12')
# # 4: String to Integer (atoi)
# this problem is not hard, but there are some corner cases.
# 1: with sign or not
# 2: number larger/smaller the sysMAX, sysMIN
# 3 non digital str
def myAtoi(st):
ls = list(st.strip())
if len(st) == 0: return 0
sign = -1 if ls[0] == '-' else 1
if ls[0] == '-' or ls[0] == '+':
ls = ls[1 :]
ans, i = 0, 0
while i < len(ls) and ls[i].isdigit():
ans = ans * 10 + int(ls[i])
i += 1
return min(2147483647, ans*sign) if ans*sign > 0 else max(-2147483648, ans*sign)
# # 5: Wildcard Matching
# isMatch("aa","a") → false
# isMatch("aa","aa") → true
# isMatch("aaa","aa") → false
# isMatch("aa", "*") → true
# isMatch("aa", "a*") → true
# isMatch("ab", "?*") → true
# isMatch("aab", "c*a*b") → false
#
# '?' Matches any single character.
# '*' Matches any sequence of characters (including the empty sequence).
# In[110]:
# this is a string with 2D DP problem
# if * then do not need to match S and P, just need to check previous match dp[i-1][j] or dp[i][j-1]
# if ? need s[i-1] == p[j-1]
# The DP is (m +1 X n + 1). The base case DP[0][i]: the first i char of P isMatch the 0 char of S: So only if p[i-1] == '*'
# The base case DP[j][0]: The 0 char of P isMatch the first j of S. So it is FALSE
def isMatch( s, p):
m, n = len(s), len(p)
dp = [[False]*(n+1) for _ in range (m+1)]
dp[0][0] = True
for i in range (1, n+1):
if p[i-1] == '*':
dp[0][i] = dp[0][i-1]
for i in range (1, m+1):
for j in range (1, n+1):
if p[j-1] == '*':
dp[i][j] = dp[i-1][j] or dp[i][j-1] #'*' can matches any sequence of characters (including the empty sequence
else:
dp[i][j] = dp[i-1][j-1] and (p[j-1] == '?' or s[i-1] == p[j-1])
return dp[-1][-1]
isMatch('aa', '*')
# # 6: Remove Invalid Parentheses
# "()())()" -> ["()()()", "(())()"]
#
# "(a)())()" -> ["(a)()()", "(a())()"]
#
# ")(" -> [""]
# This problem is a follow up question of "valid parentheses"
# The idea is to romove each parentheses and then check ""valid" or not, if valid, save it to result list.
# One thing to pay attention: cannot save duplicate combination in the result list
def removeInvalidParentheses(s):
visited, res, queue = set([]), [], [s]
valid = False
while queue:
string = queue.pop(0)
if validParentheses(string):
res.append(string)
valid = True
elif not valid:
#cannot use else. we only want to remove one char, So once it is valid, do not remove par
for i in range(len(string)):
if string[i] == '(' or string[i] == ')':
temp = string[:i] + string[i + 1 :]
if temp not in visited:
visited.add(temp)
queue.append(temp)
return res
def validParentheses(s):
count = 0
for c in s:
if c == '(': count += 1
elif c == ')':
if count == 0:
return False
count -= 1
return count == 0
removeInvalidParentheses("()())()")
## 7: Longest Substring Without Repeating Characters
# Given "abcabcbb", the answer is "abc", which the length is 3.
# This type of long substring, sublist, sub... can use two-pointer methods
# use a fast pointer to count each char as save it to a hashtable
# While Val[fast].count > 1, use slow point to remove the val[fast]
def lengthOfLongestSubstring(s):
slow, fast = 0, 0
hashmap = {}
maxlen = 0
while fast < len(s):
if s[fast] in hashmap:
hashmap[s[fast]] = hashmap.get(s[fast], 0) + 1
else:
hashmap[s[fast]] = 1
while hashmap.get(s[fast], 0) > 1:
hashmap[s[slow]]= hashmap.get(s[slow], 0)- 1
slow += 1
maxlen = max(maxlen, fast - slow + 1)
fast +=1
return maxlen
lengthOfLongestSubstring('abcabcbb')
## 8: Longest Substring with At Most Two Distinct Characters
# For example, Given s = “eceba”,
# T is "ece" which its length is 3.
# Different to P7, this problem requires the lenth of the hashmap <= 2
# When the count of one char <= 0, we need remove this char from hashmap
def lengthOfLongestSubstringTwoDistinct(s):
slow, fast = 0, 0
hashmap = {}
maxlen = 0
while fast < len(s):
if s[fast] in hashmap:
hashmap[s[fast]] = hashmap.get(s[fast], 0) + 1
else:
hashmap[s[fast]] = 1
while len(hashmap) > 2:
hashmap[s[slow]]= hashmap.get(s[slow], 0) - 1
if hashmap.get(s[slow], 0) <= 0:
del hashmap[s[slow]]
slow += 1
maxlen = max(maxlen, fast - slow + 1)
fast += 1
return maxlen
lengthOfLongestSubstringTwoDistinct('eceba')
## 9: Letter Combinations of a Phone Number
#
# Input:Digit string "23"
#
# Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
#This is a string + DFS problem
# This types of combination or permutation can be solved using DFS
def letterCombinations(digits):
if not digits:
return []
res = []
dic = {"2":"abc", "3":"def", "4":"ghi", "5":"jkl", "6":"mno", "7":"pqrs", "8":"tuv", "9":"wxyz"}
dfs(dic, digits,0, '', res)
return res
def dfs(dic, digits, digidx, path, res):
if len(path) == len(digits):
res.append(path)
for i in range(digidx, len(digits)):
for c in dic[digits[i]]:
dfs(dic, digits, i+1, path+c, res)
letterCombinations('23')
## 10: Generate Parentheses
# This is also a DFS problem
# binary tree adding ( or adding )
def generateParenthesis(n):
res=[]
ParenDFS(n, 0, 0, '', res)
return res
def ParenDFS(n, idxL, idxR, sol, res):
if idxL == n and idxR == n:
res.append(sol)
if idxL < n:
ParenDFS(n, idxL + 1, idxR, sol + '(', res)
if idxR < idxL:
ParenDFS(n, idxL, idxR + 1, sol + ')', res)
generateParenthesis(4)
|
bdfde5dfd25a5439d7a0ce5392bb63e96ed6ef69
|
koukijohn/holbertonschool-higher_level_programming
|
/0x07-python-test_driven_development/2-matrix_divided.py
| 589 | 3.625 | 4 |
#!/usr/bin/python3
"""
This module divides the matrix by div.
"""
def matrix_divided(matrix, div):
""" This function divides all elments of a matrix.
Args:
matrix: This is the matrix.
div: This is to divide.
Returns:
a new matrix.
"""
new_matrix = []
for row in range(len(matrix)):
new_matrix.append([])
for elements in matrix[row]:
new_matrix[row].append(round((elements / div), 2))
return new_matrix
if __name__ == "__main__":
import doctest
doctest.testfile("./tests/2-matrix_divided.txt")
|
834afa56934730be698d2d48cf16bc1085f44d0e
|
AmalfiAnalyticsOrg/Meta-Model
|
/adaptative-app/adaptative/data_structures/sklearn_data_structure.py
| 1,668 | 3.5625 | 4 |
'''
DataStructure to serialize a Keras Model
It puts the network architecture as metadata and pickles the weights.
'''
import pickle
from soil.data_structures.data_structure import DataStructure
class Model(DataStructure):
# @staticmethod
@classmethod
def unserialize(serialized, metadata):
''' Function to deserialize '''
return Model(pickle.loads(serialized), metadata)
def serialize(self):
''' Function to serialize '''
return pickle.dumps(self.data)
class SKLearnDataStructure(Model):
''' Data Structure for a Sklearn Model '''
def get_data(self, **_args):
# pylint: disable=no-self-use
''' Placeholder function for the API call '''
return {"this is a model": True} # self.data
class Model_DT(SKLearnDataStructure):
# @classmethod
def unserialize(serialized, metadata):
''' Function to deserialize '''
return Model_DT(pickle.loads(serialized), metadata)
def get_data(self, **_args):
return {"what i am?": "dt"}
class Model_RF(SKLearnDataStructure):
# @classmethod
def unserialize(serialized, metadata):
''' Function to deserialize '''
return Model_RF(pickle.loads(serialized), metadata)
def get_data(self, **_args):
return {"what i am?": "RF"}
class MetaModel(Model):
# @classmethod
def unserialize(serialized, metadata):
''' Function to deserialize '''
return MetaModel(pickle.loads(serialized), metadata)
def get_data(self, **_args):
# pylint: disable=no-self-use
''' Placeholder function for the API call '''
return {} # self.data
|
9a742e8bcd32f2bc03636482444ae37936566ebc
|
kouyalong/StudyCode
|
/python_data_structure/leetcode/338.counting-bits.py
| 562 | 3.53125 | 4 |
# -*- coding: utf-8 -*-
from typing import List
class Solution:
def countBits(self, num: int) -> List[int]:
ret = [0, 1]
if num <= 1:
return ret[:num+1]
flag = 1
for i in range(2, num+1):
if (flag << 1) == i:
flag = flag << 1
ret.append(1)
else:
ret.append(ret[flag] + ret[i-flag])
return ret
"""
0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
"""
number = 5
s = Solution()
print(s.countBits(number))
|
78d95db0411c661fa5c68509b322c4f74e86244d
|
itskeithstudent/Programming-and-Scripting-Labs
|
/Topic04-Flow/Lab04.03-average copy.py
| 661 | 4.25 | 4 |
#Program to keep reading numbers until user enters a 0
#take number from user
user_num = int(input("Enter a number please (0 to quit): "))
entered_numbers = [] #list of entered numbers
if user_num == 0: #if user has entered a 0 we proceed no further
print("You entered 0 immediately")
else: #else user must not have entered 0
while user_num !=0: #while user hasn't entered 0
entered_numbers.append(user_num)#we don't need to add 0 to the end of the list when a user enter 0
user_num = int(input("Enter a number again please (0 to quit): "))
#print the average
print(f"The average is {sum(entered_numbers)/len(entered_numbers)}")
|
0e4322487eb2f318db228f0f774cc5e3bbc17d21
|
MaxGubin/mywifes_homework
|
/homework1205.py
| 946 | 3.8125 | 4 |
from __future__ import print_function
CSV_NUM_FILEDS = 5
CSV_SID = 0
CSV_GPA = 4
def load_file():
"""Loads the file, return a list of tuples with SID, GPA"""
result = []
for line in open('cats.txt'):
elements = line.strip().split(',')
if len(elements) != CSV_NUM_FILEDS:
continue # invalid number of fields
result.append((int(elements[CSV_SID]), float(elements[CSV_GPA])))
return result
def print_data(data):
"""Prints SID, GPA, and summaries"""
print("SID\t\tGPA")
print("___\t\t___")
for v in data:
print(v[0], "\t\t", v[1])
gpas = [v[1] for v in data]
if gpas:
print() # add an empty line
print("Average GPA:\t%.2f" % (sum(gpas)/float(len(gpas))))
print("High GPA:\t%.2f" % max(gpas))
print("Low GPA:\t%.2f" % min(gpas))
def main():
data = load_file()
print_data(data)
if __name__ == "__main__":
main()
|
1d84d696d3db120a8779881bfefaa54d2a4c3ef5
|
Yobretaw/AlgorithmProblems
|
/Py_leetcode/045_jumpGame2.py
| 926 | 4.0625 | 4 |
import sys
import math
from collections import defaultdict
"""
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
"""
def jump_game2(A):
if not A:
return True
n = len(A)
curr_right = 0
max_right = 0
steps = 0
for i in range(0, n):
if i > max_right:
# not possible
return -1
if i > curr_right:
steps += 1
curr_right = max_right
max_right = max(max_right, i + A[i])
return steps
#a = [2, 3, 1, 1, 4]
#print jump_game2(a)
|
3a38dc90c9c00f0e0394bbac4edade20b357e90a
|
Pumala/python_rpg_logic
|
/rpg-5.py
| 9,910 | 3.90625 | 4 |
"""
Added a store. The hero can now buy a tonic or a sword. A tonic will add 2 to the hero's health wherease a sword will add 2 power.
"""
import random
import time
class Character(object):
def __init__(self):
self.name = '<undefined>'
self.health = 10
self.power = 5
self.coins = 20
def alive(self):
return self.health > 0
def attack(self, enemy):
if not self.alive():
return
print "%s attacks %s" % (self.name, enemy.name)
enemy.receive_damage(self.power)
time.sleep(1.5)
def receive_damage(self, points):
self.health -= points
print "%s received %d damage." % (self.name, points)
if self.health <= 0:
print "%s is dead." % self.name
def print_status(self):
print "%s has %d health and %d power." % (self.name, self.health, self.power)
class Hero(Character):
def __init__(self):
self.name = 'hero'
self.health = 10
self.power = 5
self.coins = 20
self.armour = 0
self.armour_usage = 0
self.evade = 0
self.tonic_pts = 0
self.swap_power_count = 0
self.resources = []
def swap_power(self, enemy):
# if self.swap_power:
# print "Would you like to swap powers? (Y or N)"
# answer = raw_input("> ").upper()
# if answer == "Y":
temp_power = enemy.power
enemy.power = hero.power
hero.power = temp_power
def use_tonic(self):
if self.tonic_pts:
print "Do you want to use your tonic now?"
print "It will increase your health by %d." % self.tonic_pts
answer = raw_input("(Y or N): ").upper()
if answer == "Y":
health_before = self.health
self.health += self.tonic_pts
self.tonic_pts = 0
print "The %s's health increased from %d to %d." % (self.name, health_before, self.health)
else:
pass
def tonic(self):
health_before = self.health
self.health += self.tonic_pts
self.tonic_pts = 0
print "The %s's health increased from %d to %d." % (self.name, health_before, self.health)
def use_resources(self):
if len(self.resources) >= 1:
answer = raw_input("Do you want to use any of your resources now (Y or N)? ").upper()
if answer == "Y":
for i in range(0, len(self.resources)):
print "%d. %s" % (i + 1, self.resources[i])
answer = int(raw_input("> "))
item = self.resources[answer - 1]
if item == "tonic":
# self.use_tonic()
self.tonic()
elif item == "swap power":
self.swap_power()
del self.resources[answer - 1]
else:
print "Maybe next time"
def attack(self, enemy):
super(Hero, self).attack(enemy)
if not enemy.alive():
self.coins += enemy.bounty
print "The %s collected %d bounty." % (self.name, enemy.bounty)
def receive_damage(self, points):
if self.evade > 0:
evade_prob = float((5 + (5 * (self.evade / 2.0))) / 100)
if random.random() < evade_prob:
print "The %s evaded the attack." % self.name
return
# if len(self.resources) >= 1:
# print "Do you want to use any of your resources now?"
self.use_resources()
# self.use_tonic()
if self.armour:
self.armour_usage -= 1
armour_pts = self.armour
print "The armour protects the %s." % self.name
print "The attack power is reduced by %d points." % self.armour
if random.random() > 0.2:
super(Hero, self).receive_damage(points - self.armour)
else:
super(Hero, self).receive_damage((points * 2) - self.armour )
print "The %s was delivered 2 blows." % (self.name)
if self.armour_usage == 0:
self.armour = 0
def restore(self):
self.health = 10
print "Hero's heath is restored to %d!" % self.health
time.sleep(1)
def buy(self, item):
self.coins -= item.cost
item.apply(hero)
class Medic(Character):
def __init__(self):
self.name = "medic"
self.health = 9
self.power = 4
self.bounty = 5
def receive_damage(self, points):
super(Medic, self).receive_damage(points)
if self.alive():
if random.random() > 0.2:
self.health += 2
print "The %s regained 2 health points." % (self.name)
else:
pass
class Shadow(Character):
def __init__(self):
self.name = "shadow"
self.health = 1
self.power = 2
self.bounty = 7
def receive_damage(self, points):
if random.random() > 0.10:
print "The %s evaded the attack." % (self.name)
return
else:
super(Shadow, self).receive_damage(points)
class Goblin(Character):
def __init__(self):
self.name = 'goblin'
self.health = 6
self.power = 2
self.bounty = 5
class Wizard(Character):
def __init__(self):
self.name = 'wizard'
self.health = 8
self.power = 1
self.bounty = 6
def attack(self, enemy):
swap_power = random.random() > 0.5
if swap_power:
print "%s swaps power with %s during attack" % (self.name, enemy.name)
self.power, enemy.power = enemy.power, self.power
super(Wizard, self).attack(enemy)
if swap_power:
self.power, enemy.power = enemy.power, self.power
class Battle(object):
def do_battle(self, hero, enemy):
print "====================="
print "Hero faces the %s" % enemy.name
print "====================="
while hero.alive() and enemy.alive():
hero.print_status()
enemy.print_status()
time.sleep(1.5)
print "-----------------------"
print "What do you want to do?"
print "1. fight %s" % enemy.name
print "2. do nothing"
print "3. flee"
print "> ",
input = int(raw_input())
if input == 1:
hero.attack(enemy)
elif input == 2:
pass
elif input == 3:
print "Goodbye."
exit(0)
else:
print "Invalid input %r" % input
continue
enemy.attack(hero)
if hero.alive():
print "You defeated the %s" % enemy.name
return True
else:
print "YOU LOSE!"
return False
class Tonic(object):
cost = 5
name = 'tonic'
def apply(self, character):
while True:
print "Do you want to use it now or save for later?"
print "1. Use tonic now"
print "2. Save tonic for later"
answer = int(raw_input("> "))
if answer == 1:
character.health += 2
print "%s's health increased to %d." % (character.name, character.health)
break
elif answer == 2:
character.tonic_pts += 2
character.resources.append("tonic")
print "%s's tonic has been stored in the weaponry." % (character.name)
break
else:
print "Invalid answer."
class SuperTonic(object):
cost = 8
name = 'supertonic'
def apply(self, character):
character.health += 10
print "%s's health increased to %d." % (character.name, character.health)
class Sword(object):
cost = 10
name = 'sword'
def apply(self, hero):
hero.power += 2
print "%s's power increased to %d." % (hero.name, hero.power)
class Armour(object):
cost = 10
name = 'armour'
def apply(self, hero):
hero.armour = 2
hero.armour_usage = 3
print "%s's armour increased to %d." % (hero.name, hero.armour)
class Evade(object):
cost = 8
name = 'evade'
def apply(self, hero):
hero.evade += 2
print "%s's evade increased to %d." % (hero.name, hero.evade)
class SwapPower(object):
cost = 5
name = 'swap power'
def apply(self, hero):
hero.swap_power_count += 1
print "%s's swap power count has increased to %d." % (hero.name, hero.swap_power_count)
class Store(object):
# If you define a variable in the scope of a class:
# This is a class variable and you can access it like
# Store.items => [Tonic, Sword]
items = [Tonic, SuperTonic, Sword, Armour, Evade, SwapPower]
def do_shopping(self, hero):
while True:
print "====================="
print "Welcome to the store!"
print "====================="
print "You have %d coins." % hero.coins
print "What do you want to do?"
for i in xrange(len(Store.items)):
item = Store.items[i]
print "%d. buy %s (%d)" % (i + 1, item.name, item.cost)
print "10. leave"
input = int(raw_input("> "))
if input == 10:
break
else:
ItemToBuy = Store.items[input - 1]
item = ItemToBuy()
hero.buy(item)
hero = Hero()
enemies = [Goblin(), Shadow(), Medic(), Wizard()]
battle_engine = Battle()
shopping_engine = Store()
for enemy in enemies:
hero_won = battle_engine.do_battle(hero, enemy)
if not hero_won:
print "YOU LOSE!"
exit(0)
shopping_engine.do_shopping(hero)
print "YOU WIN!"
|
a76e74ec036b349222cc48d444ad9541778b0405
|
domenicoven/python-katas
|
/string-calculators-kata/string_calculator.py
| 845 | 3.609375 | 4 |
import re
class StringCalculator:
def add(self, numbers):
delimiters = self.__retrieveDelimiters(numbers)
numList = re.split(delimiters, numbers)
total = 0
for val in numList:
total = total + self.__str_to_int(val)
return int(total)
def __str_to_int(self, str):
value=0
try:
value= int(str)
except ValueError:
value=0
if value<0:
raise NegativeNotAllowedException('negatives not allowed: {0}'.format(value))
return value if value<=1000 else 0
def __retrieveDelimiters(self, str):
if (str.startswith("//")) and (str.index("\n") >2):
return re.compile(str[2:str.index('\n')] )
else:
return r"[,\n]"
class NegativeNotAllowedException(Exception):
pass
|
e4c11fa168529e50e8e542131f03a15b21918574
|
psbarros/Variaveis3
|
/2019-1/231/users/4219/codes/1719_2505.py
| 211 | 3.6875 | 4 |
from math import*
x = eval(input("angulo :"))
k = int(input("insira: "))
i = 0
soma = 0
while i<k :
conta = x**((2*i) + 1)/factorial (2*i+1)
x = -1 *x
soma = soma + conta
i = i + 1
print (round(soma, 10))
|
55481b8fef77a13f67eed56f641949f034f96bb8
|
hoanhan101/gumroad
|
/pivot.py
| 864 | 3.90625 | 4 |
def find_pivot(numbers: list):
if len(numbers) <= 2:
return -1
left = numbers[0]
right = sum(numbers)
for i in range(1, len(numbers) - 1):
left += numbers[i - 1]
right -= numbers[i]
if left == right:
return i
return -1
def test_find_pivot():
assert find_pivot([]) == -1
assert find_pivot([0]) == -1
assert find_pivot([0, 1]) == -1
assert find_pivot([0, 1]) == -1
assert find_pivot([1, 0, 1]) == 1
assert find_pivot([1, 0, 2]) == -1
assert find_pivot([2, 0, 1]) == -1
assert find_pivot([1, 1, 0, 1]) == 1
assert find_pivot([1, 0, 0, 1]) == 1
assert find_pivot([1, 0, 1, 1]) == 2
assert find_pivot([1, 1, 1, 1]) == -1
assert find_pivot([1, 4, 6, 3, 2]) == 2
assert find_pivot([1, 4, 6, 3, 11]) == 3
assert find_pivot([1, 4, 6, 3, 5, 6]) == 3
|
0848a6c6d26b0eede22ebca5f82c87145b313750
|
kesia-barros/exercicios-python
|
/ex001 a ex114/ex016.py
| 381 | 4.0625 | 4 |
from math import trunc, floor
n = float(input("Digite um número: "))
print("O número",n)
print("tem a parte inteira",floor(n))
# Outra forma de fazer é:
n = float(input("Digite um número: "))
print("O número",n)
print("tem a parte inteira",trunc(n))
# Outra forma de fazer é:
n = float(input("Digite um número: "))
print("O número",n)
print("tem a parte inteira",int(n))
|
03a42e155dadadcc261d974dcde4a252cd8fcf4d
|
Linkin-1995/test_code1
|
/day05/exercise02.py
| 521 | 3.65625 | 4 |
# 练习:
# 字符串: content = "我是京师监狱狱长金海。"
# 打印第一个字符、打印最后一个字符、打印中间字符
# 打印第三个字符、打印倒数第五个字符
# 命题:金海在字符串content中
# 命题:京师监狱不在字符串content中
content = "我是京师监狱狱长金海。"
print(content[0])
print(content[-1])
print(content[len(content) // 2])
print(content[2])
print(content[-5])
print("金海" in content) # True
print("京师监狱" not in content) # False
|
69de80b7c5b079a654876c66dea0f0cab4c82cd1
|
gabopotestades/python_mini_projects
|
/Hackerrank/Built-ins/ginortS.py
| 518 | 3.9375 | 4 |
#Declare list for storage
lcase = []
ucase = []
odd = []
even = []
#Determine each character which list they will be inserted
for s in input():
if s.isdigit():
if int(s) % 2 == 0:
even.append(int(s))
else:
odd.append(int(s))
elif s.islower():
lcase.append(s)
else:
ucase.append(s)
#Print in format: lowercase, uppercase, odd, even using sorted for each list
print(*[i for i in sorted(lcase) + sorted(ucase) + sorted(odd) + sorted(even)], sep = '')
|
362b604f4e219e8da4cda1663733c70cd715eacb
|
LSaldyt/q-knap
|
/scripts/dynamic.py
| 2,061 | 3.84375 | 4 |
import functools
def memoize(obj):
'''
Decorator that caches function calls, allowing dynamic programming.
If a function is called twice with the same arguments, the cached result is used.
obj: function to be cached
'''
cache = obj.cache = {}
@functools.wraps(obj)
def memoizer(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = obj(*args, **kwargs)
return cache[key]
return memoizer
def dynamic_knapsack(items, outerConstraints):
'''
Solve the knapsack problem
`items`: a sequence of pairs `(value, weight, volume)`, where `value` is
a number and `weight` is a non-negative integer.
`outerConstraints`: a list of numbers representing the maximum values
for each respective constraint
`return`: a pair whose first element is the sum of values in the most
valuable subsequence, and whose second element is the subsequence.
'''
@memoize
def bestvalue(i, constraints):
'''
Return the value of the most valuable subsequence of the first i
elements in items whose constraints are satisfied
'''
if i == 0: return 0
value, *limiters = items[i - 1]
tests = [l > v for l, v in zip(limiters, constraints)]
if any(tests): # constraint checking
return bestvalue(i - 1, constraints)
else: # maximizing
modifications = [v - l for l, v in zip(limiters, constraints)]
return max(bestvalue(i - 1, constraints),
bestvalue(i - 1, modifications) + value)
k = outerConstraints
result = []
for i in range(len(items), 0, -1):
if bestvalue(i, k) != bestvalue(i - 1, k):
result.append(items[i - 1])
k = [
c - items[i - 1][n + 1] for n, c in enumerate(k)
]
result.reverse()
choices = [items.index(choice) for choice in result]
return bestvalue(len(items), outerConstraints), result, choices
|
0f65c20e850f35911d9dbfba1967076391328163
|
MarijaLaz/Awele_Othello
|
/Awele/awele.py
| 4,672 | 3.859375 | 4 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.append("..")
import game
def initialiseJeu():
""" void -> jeu
Initialise le jeu (nouveau plateau, liste des coups joues vide, liste des coups valides None, scores a 0 et joueur = 1)
"""
#plateau = [[4 for i in range(6)] for i in range(2)]
plateau = [[4,4,4,4,4,4],[4,4,4,4,4,4]]
return [plateau , 1, None, [], [0,0]]
def advaffame(jeu):
""" jeu -> bool
checks if the opponent starves (his row is 0)
"""
j = game.getJoueur(jeu)
adv = j%2+1
return sum(jeu[0][adv-1]) == 0
def nourrit(jeu, coup):
""" jeu, coup -> bool
checks if a coup reaches opponents row
"""
j = game.getJoueur(jeu)
if (j==1):
return coup[1]<game.getCaseVal(jeu, coup[0], coup[1])
return game.getCaseVal(jeu, coup[0], coup[1]) + coup[1] > 5
def getCoupsValides(jeu):
if(jeu[2]==None):
j = game.getJoueur(jeu)
a = advaffame(jeu)
jeu[2] = [(j-1,i) for i in range(6) if game.getCaseVal(jeu,j-1,i) > 0 and ((not a) or nourrit(jeu,(j-1,i)))]
return jeu[2]
def nextCase(l, c, horaire = False):
if horaire:
if c == 5 and l == 0:
return (1,c)
if c == 0 and l == 1 :
return (0,c)
if l == 0:
return (l, c+1)
return (l,c-1)
else:
if c == 5 and l == 1:
return (0,c)
if c == 0 and l == 0 :
return (1,c)
if l == 0:
return (l, c-1)
return (l,c+1)
def distribue(jeu,case):
v = game.getCaseVal(jeu, case[0], case[1])
nc = case
jeu[0][case[0]][case[1]] = 0
while v > 0:
nc = nextCase(nc[0], nc[1])
if not nc == case:
jeu[0][nc[0]][nc[1]] += 1
v -= 1
return nc
def joueCoup(jeu, coup):
l,c = distribue(jeu, coup)
save = game.getCopieJeu(jeu)
j = game.getJoueur(jeu)
v = game.getCaseVal(jeu,l, c)
while(l == (j%2) and ((v == 2) or (v == 3))):
#print("in")
jeu[0][l][c] = 0
#print(jeu[0][l][c])
jeu[-1][j-1] += v
#print(jeu[-1][j-1])
l,c = nextCase(l,c,True)
v = game.getCaseVal(jeu, l, c)
if advaffame(jeu):
jeu[0] = save[0]
jeu[-1] = save[-1]
game.changeJoueur(jeu)
jeu[2] = None
jeu[3].append(coup)
def finJeu(jeu):
""" jeu -> bool
When one player has captured 25 or more seeds.
When one player has no move to avoid the opponent to starve
When a given position occurs for the second time with the same player's turn.
"""
if(jeu[4][0] >= 25 or jeu[4][1] >= 25):
return True
if(game.getCoupsValides(jeu) == []):
return True
if(len(game.getCoupsJoues(jeu))>=100):
return True
return False
def affiche(jeu):
""" jeu->void
Affiche l'etat du jeu de la maniere suivante :
Coup joue = <dernier coup>
Scores = <score 1>, <score 2>
Plateau :
| 0 | 1 | 2 | ...
------------------------------------------------
0 | <Case 0,0> | <Case 0,1> | <Case 0,2> | ...
------------------------------------------------
1 | <Case 1,0> | <Case 1,1> | <Case 1,2> | ...
------------------------------------------------
... ... ... ...
Joueur <joueur>, a vous de jouer
Hypothese : le contenu de chaque case ne depasse pas 5 caracteres
"""
if(jeu[3]== []):
print("Coup joue = None")
else:
print("Coup joue = ", jeu[3][-1])
print("Joueur: ", jeu[1])
print("Scores = ", jeu[4][0]," , ", jeu[4][1])
print("Plateau :")
plateau = jeu[0]
for x in range (len(plateau[0])):
if(x == 0):
print("%5s|" %(""), end=" ")
print("%5s|" %(x), end=" ")
print()
print("--------------------------------------------------------------")
for i in range(len(plateau)):
print(" ",i," |", end=" ")
for j in range(len(plateau[i])):
if(plateau[i][j] == 0):
print("%5s|" %(" "), end=" ")
else:
if(plateau[i][j] == 1):
print("%5s|" %(plateau[i][j]), end=" ")
else:
print("%5s|" %(plateau[i][j]), end=" ")
print()
print("--------------------------------------------------------------")
|
4510c4cf5d314d787b11142440aed2178be1f137
|
SS4G/AlgorithmTraining
|
/exercise/leetcode/python_src/by2017_Sep/Leet173.py
| 1,213 | 4.03125 | 4 |
# Definition for a binary tree node
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from AlgorithmTraining.G55Utils.Py.Utils import *
class BSTIterator(object):
"""
O(1) times
O(n) memory
"""
def __init__(self, root):
"""
:type root: TreeNode
"""
self.storage = []
self.ptr = 0
self.midTraverse(root)
def midTraverse(self, root):
if root is None:
return
else:
self.midTraverse(root.left)
self.storage.append(root.val)
self.midTraverse(root.right)
def hasNext(self):
"""
:rtype: bool
"""
return self.ptr < len(self.storage)
def next(self):
"""
:rtype: int
"""
res = self.storage[self.ptr]
self.ptr += 1
return res
# Your BSTIterator will be called like this:
# i, v = BSTIterator(root), []
# while i.hasNext(): v.append(i.next())
if __name__ == "__main__":
root = TreeUtil.deserialize([1, 2, 3])
s = BSTIterator(root)
while s.hasNext():
print(s.next())
|
9bd995b601321c0ab60d7a180586605051d851d1
|
alphadome/python
|
/Programs/toppings.py
| 278 | 3.71875 | 4 |
requested_toppings=['mushrooms', 'cheese', 'ham', 'pepperoni']
for requested_topping in requested_toppings:
if requested_topping == 'mushrooms':
print("Sorry out of mushrooms.")
else:
print("Adding " + requested_topping +".")
print("\nFinished making your pizza!")
|
9516ec9bab68674f78cd3e5b44568f9e4b2ba164
|
Iceberry-qdd/python_exercise
|
/day3/5.py
| 266 | 3.796875 | 4 |
score=float(input('请输入成绩:'))
if score>=90:
print('A')
elif score<90 and score>=80:
print('B')
elif score<80 and score>=70:
print('C')
elif score<70 and score>=60:
print('D')
elif score<60:
print('E')
else:
print('输入错误!')
|
17a1135c177ceaf3e0679788902801ed4c01dbf5
|
Rkutta/Sedgewick_Algorithms_2nd_ED_in_Python
|
/Fundamentals/Elementary Data Structures/linked_list.py
| 1,309 | 3.984375 | 4 |
'''
Algorithms 2nd. Ed by Robert Sedgewick
Chapter 3: Elementary Data Structures pg 20
Program: linked_list
Implemented in Python by Edward Heronzy
'''
# Single Linked List
class node:
def __init__(self, key=None, next=None):
self.key = key
self.next = next
def listinitialize():
global head
global z
head = node()
z = node()
head.next = z
z.next = z
def deletenext(t):
t.next = t.next.next
def insertafter(v,t):
x = node()
x.key = v
x.next = t.next
t.next = x
'''
Author's Note:
To eleborate on a bit of confusion that may
arise when comparing the Pascal code to the
Python implementation, Python does not implement
pointers. You cannot initialize a pointer type in
Python (as it goes against the philosophy of Python
that simple is better than complex). But if you look
at how objects are created in Python, you can see
that each variable we create is in itself a pointer
to a PyObject in memory which has a type, value, and
reference count. So think of the "head" and "z" variables
as pointing to a node() object in memory that we can access
and change through these variables. But do not call
them "pointers" because they are not the same as those
found in Pascal or C++. Call them "variables"
'''
|
3796a0bc6fe44f5b96de92466cc3b0e942de2962
|
PPinto22/ProjectEuler
|
/p052.py
| 289 | 3.625 | 4 |
found = False
x = 0
while not found:
x += 1
for m in range(2,7):
smx = str(m*x)
sx = str(x)
if len(sx)!=len(smx) or not all(sx.count(digit) == smx.count(digit) for digit in sx):
break
else:
found = True
for i in range(1,7):
print(str(i) + " * " + str(x) + " = " + str(i*x))
|
10072a9d9cc5260af2eff37ead2ae63d65112ac7
|
dkp-1024/face_counter
|
/my_work/pro6.py
| 593 | 3.90625 | 4 |
#pasting of the image on another image
from PIL import Image
def main():
try:
#Relative Path
#Image on which we want to paste
img = Image.open("picture.jpg")
#Relative Path
#Image which we want to paste
img2 = Image.open("picture2.jpg")
img.paste(img2, (50, 50))
#Saved in the same relative location
img.save("pasted_picture.jpg")
except IOError:
pass
if __name__ == "__main__":
main()
##An additional argument for an optional image mask image is also available.
|
e5c02a47a1ab6dcca709a2691c3dc949ea880c02
|
221002-Fety/Tugas-Besar
|
/tugasBesar.py
| 10,280 | 3.515625 | 4 |
import csv
import datetime
import os
filecsv= 'loginPass.csv'
def clear():
os.system('cls')
def backtoMenuWarga():
print("\n")
input("Tekan ENTER untuk kembali...")
menuWarga()
def backtoMenuAdmin():
print("\n")
input("Tekan ENTER untuk kembali...")
menuAdmin()
def buatAkun() :
clear()
paswarga= '085232'
pasadmin= '128432'
subject = input('Warga/Admin= ')
penampung= []
if subject == 'warga':
nama = input('Nama = ')
password= input('Password = ')
penampung.append(nama)
penampung.append(password)
if password == paswarga:
with open(filecsv, 'w', newline='') as file:
penulis= csv.writer(file, delimiter=',')
penulis.writerow(penampung)
clear()
menuWarga()
else:
print('Password yang anda masukan salah!')
elif subject == 'admin':
nama = input('Nama = ')
password= input('Password = ')
penampung.append(nama)
penampung.append(password)
if password == pasadmin:
with open(filecsv, 'w', newline='') as file:
penulis= csv.writer(file, delimiter=',')
penulis.writerow(penampung)
clear()
menuAdmin()
else:
print('Password yang anda masukan salah!')
else :
print('Input anda salah, coba lagi!')
def login() :
clear()
print('===LOG IN===')
nama = input('nama = ')
password= input('password= ')
data = []
data.append(nama)
data.append(password)
dataDiri= []
with open(filecsv, 'r') as file:
pembaca= csv.reader(file, delimiter=',')
for data in pembaca:
dataDiri.append(data)
for sel in dataDiri:
sandi= sel[1]
if sandi=='085232':
clear()
menuWarga()
elif sandi== '128432':
clear()
menuAdmin()
else:
print('Password/nama yang anda masukan salah!')
def logout() :
clear()
menuWellcome()
fileSaran= 'saran.csv'
fileBerita= 'berita.csv'
iniPass= []
x = datetime.datetime.now()
tanggal= x.strftime("%A, %d-%b-%Y")
def tambahsaran() :
clear()
namaKolom = ['Tanggal', 'Nama', 'Saran']
nama = input('Nama penulis = ')
saran = input('Saran penulis= ')
databaru= dict()
penampung= []
databaru['Tanggal'] = tanggal
databaru['Nama'] = nama
databaru['Saran'] = saran
with open(fileSaran, 'r') as csvfile:
reader = csv.DictReader(csvfile, delimiter=',')
for data in reader:
penampung.append(data)
penampung.append(databaru)
with open(fileSaran, 'w', newline='') as csvFile:
writer= csv.DictWriter(csvFile, delimiter=',', fieldnames=namaKolom)
writer.writeheader()
writer.writerows(penampung)
clear()
backtoMenuWarga()
def bacasaran() :
clear()
with open(fileSaran, 'r') as csvfile:
reader = csv.DictReader(csvfile, delimiter=',')
for data in reader:
for key, value in data.items() :
print("{} = {}".format(key, value))
print()
clear()
backtoMenuAdmin()
def tambahberita() :
clear()
namaKolom = ['Tanggal', 'Judul', 'Isi Berita']
judul= input('Judul berita= ')
isi = input('Isi berita = ')
databaru= dict()
penampung= []
databaru['Tanggal'] = tanggal
databaru['Judul'] = judul
databaru['Isi Berita'] = isi
penampung.append(databaru)
with open(fileBerita, 'r') as csvfile:
reader = csv.DictReader(csvfile, delimiter=',')
for data in reader:
penampung.append(data)
with open(fileBerita, 'w', newline='') as csvFile:
writer= csv.DictWriter(csvFile, delimiter=',', fieldnames=namaKolom)
writer.writeheader()
writer.writerows(penampung)
clear()
backtoMenuAdmin()
def bacaberita() :
clear()
with open(fileBerita, 'r') as csvfile:
reader = csv.DictReader(csvfile, delimiter=',')
for data in reader:
for key, value in data.items() :
print("{} = {}".format(key, value))
print()
sandi= iniPass[0][1]
if sandi== '085232':
clear()
backtoMenuWarga()
elif sandi=='128432':
clear()
backtoMenuAdmin()
filesoal= 'kuesioner.csv'
filejawab= 'hasilvoting.csv'
def kirimQ() :
clear()
hasil=[]
with open(filejawab, 'w', newline='') as file:
penulis= csv.writer(file, delimiter=',')
penulis.writerows(hasil)
penampung= []
kuesioner= dict()
header= ['Apa pendapat anda tentang ', 'Pilih salah satu jawaban dari']
soal= '\n' + input('Tulis pertanyaan anda= ') + '\n'
pilihan= '\na. Sangat setuju\nb. Setuju\nc. Kurang setuju\nd. Tidak setuju'
kuesioner['Apa pendapat anda tentang ']= soal
kuesioner['Pilih salah satu jawaban dari']= pilihan
penampung.append(kuesioner)
with open(filesoal, 'w', newline='') as soal :
penulis= csv.DictWriter(soal, delimiter=',', fieldnames=header)
penulis.writeheader()
penulis.writerows(penampung)
clear()
print('Kuesioner berhasil di tambah.')
clear()
backtoMenuAdmin()
def bacaQ() :
with open(filesoal, 'r') as soal:
pembaca= csv.DictReader(soal, delimiter=',')
for data in pembaca:
for key, value in data.items() :
print("{} = {}".format(key, value))
print()
def voteUser():
clear()
bacaQ()
masukan= input('Jawab= ')
penampung= []
with open(filejawab, 'a', newline='') as file:
penulis= csv.writer(file, delimiter=',')
penulis.writerow(masukan)
jumlaha = []
jumlahb = []
jumlahc = []
jumlahd = []
with open(filejawab, 'r') as file:
scanner= csv.reader(file, delimiter=',')
for sel in scanner:
penampung.append(sel)
for data in penampung:
if data== ['a']:
jumlaha.append(1)
elif data== ['b']:
jumlahb.append(1)
elif data== ['c']:
jumlahc.append(1)
elif data== ['d']:
jumlahd.append(1)
print('=======Hasil Kuesioner=======')
print(' Sangat setuju= ', len(jumlaha))
print(' Setuju = ', len(jumlahb))
print(' Kurang setuju= ', len(jumlahc))
print(' Tidak setuju = ', len(jumlahd))
print('~Terimakasih untuk masukannya~')
clear()
backtoMenuWarga()
def voteAdmin():
clear()
bacaQ()
penampung= []
#nanti modelnya buat admin gausah ada inputan
#kalo user abis input langsung ada hasil
jumlaha = []
jumlahb = []
jumlahc = []
jumlahd = []
with open(filejawab, 'r') as file:
scanner= csv.reader(file, delimiter=',')
for sel in scanner:
penampung.append(sel)
for data in penampung:
if data== ['a']:
jumlaha.append(1)
elif data== ['b']:
jumlahb.append(1)
elif data== ['c']:
jumlahc.append(1)
elif data== ['d']:
jumlahd.append(1)
print('=======Hasil Kuesioner=======')
print(' Sangat setuju= ', len(jumlaha))
print(' Setuju = ', len(jumlahb))
print(' Kurang setuju= ', len(jumlahc))
print(' Tidak setuju = ', len(jumlahd))
print('~Terimakasih atas masukannya~')
clear()
backtoMenuAdmin()
def menuWarga():
while True:
print('''
::::::DESA BOX::::::
*MENU*
1. Kotak Saran
2. Berita Hari Ini
3. Isi Kuesioner
4. Keluar dari Akun
5. Keluar dari Menu
::::::::::::::::::::\n''')
menu= int(input(' Pilih Menu= '))
if menu == 1:
tambahsaran()
elif menu == 2:
bacaberita()
elif menu == 3:
voteUser()
elif menu == 4:
logout()
elif menu == 5:
clear()
break
else:
print('Input yang anda masukan salah!')
def menuAdmin() :
while True:
print('''
::::::DESA BOX::::::
*MENU*
1. Baca Kotak Saran
2. Tulis Berita
3. Baca Berita
4. Buat Kuesioner
5. Hasil Kuesioner
6. Keluar dari Akun
7. Keluar dari Menu
::::::::::::::::::::\n''')
menu= int(input(' Pilih Menu= '))
if menu == 1:
bacasaran()
elif menu == 2:
tambahberita()
elif menu == 3:
bacaberita()
elif menu == 4:
kirimQ()
elif menu == 5:
voteAdmin()
elif menu == 6:
logout()
elif menu == 7:
clear()
break
else:
print('Input yang anda masukan salah!')
def menuWellcome() :
clear()
while True:
print('''
::::::DESA BOX::::::
~Selamat Datang~
1. Login
2. Buat Akun Baru
3. Keluar
::::::::::::::::::::\n''')
menu= int(input(' Pilih Menu= '))
if menu == 1 :
login()
elif menu == 2 :
buatAkun()
elif menu == 3 :
clear()
break
with open(filecsv, 'r') as file:
pembaca= csv.reader(file, delimiter=',')
for sel in pembaca:
iniPass.append(sel)
print ("iniPass")
if len(iniPass) == 0:
menuWellcome()
elif len(iniPass) > 0:
sandi= iniPass[0][1]
if sandi=='085232':
menuWarga()
elif sandi== '128432':
menuAdmin()
print ("iniPass")
|
b077c1df0a453e800b4f483287248323df8366f2
|
Mr-Coxall/Computer-Based-Problem-Solving
|
/code_examples/4-Functions/1-Understanding_Functions/Python/main.py
| 1,106 | 3.875 | 4 |
#!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module uses user defined functions
"""
def calculate_area() -> None:
"""The calculate_area() function calculates area of a rectangle, returns None."""
# input
length = int(input("Enter the length of a rectangle (cm): "))
width = int(input("Enter the width of a rectangle (cm): "))
# process
area = length * width
# output
print(f"The area is {area} cm²")
print("")
def calculate_perimeter() -> None:
"""The calculate_perimeter() function calculates perimeter of a rectangle, returns None."""
# input
length = int(input("Enter the length of a rectangle (cm): "))
width = int(input("Enter the width of a rectangle (cm): "))
# process
perimeter = 2 * (length + width)
# output
print(f"The perimeter is {perimeter} cm")
print("")
def main() -> None:
"""The main() function just calls other functions, returns None."""
# call functions
calculate_area()
calculate_perimeter()
print("\nDone.")
if __name__ == "__main__":
main()
|
25ffe3668f47f84be295fda37e9fd12f895e7934
|
Nishitakesharbani/practice
|
/ex25.py
| 576 | 4.3125 | 4 |
def break_word(stuff):
"""This function will break your word"""
words=stuff.split(' ')
return words
def sort_words(words):
"""sort the word"""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off"""
word=words.pop(0)
print(word)
def print_last_word(words):
"""Prints the last word after popping it off"""
word=words.pop(-1)
print(word)
def sort_sentence(sentence):
"""Takes the full sentence and return the sorted part"""
words=break_word(sentence)
return sort_words(words)
|
1aeead6f35bce0a72ee2049c99e49a5ded83d403
|
watermelon-lee/leetcode
|
/code/406.根据升高重新建队.py
| 1,064 | 3.75 | 4 |
"""
@File : 406.根据升高重新建队.py
@Time : 2019-10-28 10:13
@Author : 李浩然
@Software: PyCharm
@Email: [email protected]
"""
from typing import List
import functools
class Solution:
def sorted_key(self,x,y):
if x[0]>y[0]:
return 1
if x[0]<y[0]:
return -1
else:
if x[1]>y[1]:
return -1
else:
return 1
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
# 按照身高降序,位置升序排列,然后以此选择位置插入
people_down=sorted(people,key=functools.cmp_to_key(self.sorted_key),reverse=True)
# x = [[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]]
# sorted(x, key=lambda x: x[0], reverse=True)
# [[7, 0], [7, 1], [6, 1], [5, 0], [5, 2], [4, 4]]
reRankList=[]
for i in people_down:
reRankList.insert(i[1],i)
return reRankList
s=Solution()
print(s.reconstructQueue([[9,0],[7,0],[1,9],[3,0],[2,7],[5,3],[6,0],[3,4],[6,2],[5,2]]))
|
27feb15854f24cfa9048ee76d8cee1006a8233b9
|
BartVandewoestyne/Python
|
/2.X/examples/mutable_default_arguments.py
| 880 | 4.71875 | 5 |
# Python's default arguments are evaluated once when the function is defined,
# not each time the function is called (like it is in say, Ruby). This means
# that if you use a mutable default argument and mutate it, you will and have
# mutated that object for all future calls to the function as well.
#
# References:
#
# [1] http://docs.python-guide.org/en/latest/writing/gotchas/
# A new list is created once when the function is defined, and the same list is
# used in each successive call!
def append_to1(element, to=[]):
to.append(element)
return to
my_list = append_to1(12)
print my_list
my_other_list = append_to1(42)
print my_other_list
# The good way to do it:
def append_to2(element, to=None):
if to is None:
to = []
to.append(element)
return to
my_list = append_to2(12)
print my_list
my_other_list = append_to2(42)
print my_other_list
|
b196ffa8065669971d998cc6c86fb39d9e5c93b9
|
lezakkaz/Python-workshop
|
/Examples/example_2-1.py
| 649 | 4.28125 | 4 |
# Python workshop Part 3 by Khiati Zakaria
# Example 2-1 (Functions)
# Create the function named helloWorld without any arguments and returns nothing
# it is suppose to print a number before it prints hello world!
# for exampe, if your input is helloWorld(5) it should print 5 Hello world!
def helloWorld(x):
print(x + " Hello world!")
# Use a loop to call the above function 10 times while giving i as an input
for i in range(10):
helloWorld(i)
# if you try to run this, the compiler will return an error
# TypeError: unsupported operand type(s) for +: 'int' and 'str'
# and that is because you can't add an integer to a string
|
c5b02b0d7e22e458c0d0952c02bd2ef9401cde91
|
SouzaCadu/guppe
|
/Secao_05_Lista_Ex_41e/ex_04.py
| 322 | 3.875 | 4 |
"""
Se o número digitado for positivo:
- calcule o quadrado
- calcule a raiz quadrada
"""
v1 = float(input("Digite um valor positivo para saber o quadrado e a raiz quadrada:"))
if v1 > 0:
print(f"O quadrado de {v1} é {v1 ** 2:.2f} e a raiz quadrada é {v1 ** 0.5:.2f}")
else:
print("Digite um valor positivo.")
|
b5eae3020cd8404311c6da6cba3123aabab728b6
|
taeheechoi/coding-practice
|
/implementStrStr.py
| 308 | 3.875 | 4 |
# Example 1:
# Input: haystack = "hello", needle = "ll"
# Output: 2
# Example 2:
# Input: haystack = "aaaaa", needle = "bba"
# Output: -1
# Example 3:
# Input: haystack = "", needle = ""
# Output: 0
def implmentStrStr(haystack, needle):
return haystack.find(needle)
print(implmentStrStr("", ""))
|
d9ef8101a0b2f8937b3460dc51150480e526f521
|
Skyy-Bluu/longest-substring-without-repeating-characters
|
/Longest Substring Without Repeating Characters.py
| 1,197 | 3.703125 | 4 |
def lengthOfLongestSubstring(string):
highscore = 0
counter = 1
if string == " " or len(string) == 1:
return 1
elif string == "":
return 0
substring = string[0]
longestString = ""
for i in range(1, len(string)):
print("Substring ", substring, " String[i] ", string[i], " Highscore ", len(longestString), " Counter ", counter)
if string[i] in substring:
if len(substring) > len(longestString):
longestString = substring
counter = 1
#substring = string[i]
dupCharsIndex = [i for i, ltr in enumerate(string) if ltr == string[i]]
index = dupCharsIndex[len(dupCharsIndex)-2]
substring = string[index:i]
print("new substring is ", substring)
else:
print("before appending", substring)
substring += string[i]
print("after appending", substring)
counter += 1
if len(substring) > len(longestString):
longestString = substring
print("longest string is ", len(longestString), " Longest String", longestString)
lengthOfLongestSubstring("aab") and "dvdf"
|
95f665d1f534415fb1c5e42db48b2250dc19375e
|
sribalakrish14/guvi-codekata
|
/noinletters.py
| 117 | 3.5625 | 4 |
num=int(input())
list=["Zero","One","Two","Three","Four","Five","Six" ,"Seven","Eight","Nine","Ten"]
print list[num]
|
acaca947838eb2dd10827b656aa2f9184d2fe4b8
|
victorsemenov1980/Coding-challenges
|
/findUnique1.py
| 931 | 4.25 | 4 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 25 12:02:50 2020
@author: user
"""
'''
There is an array with some numbers. All numbers are equal except for one.
Try to find it!
find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2
find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55
It’s guaranteed that array contains at least 3 numbers.
The tests contain some very huge arrays, so think about performance.
'''
def find_uniq(arr):
unique_list = []
count=0
for x in arr:
if x not in unique_list:
unique_list.append(x)
for i in range(3): #we have condition about at least 3 entries in the arr
if arr[i]==unique_list[0]:
count+=1
if count>1:
return unique_list[1]
else:
return unique_list[0]
print(find_uniq([ 1, 1, 1, 2, 1, 1 ]))
print()
print(find_uniq([ 0, 0, 0.55, 0, 0 ]))
print()
print(find_uniq([ 0, 1, 1 ]))
|
670592e91b66013b4f50b59beeda938c0e81eca2
|
GBenia/PythonforABM
|
/Q4_OopsDoo.py
| 487 | 3.703125 | 4 |
# -*- coding: utf-8 -*-
"""
Questão 4 - Escreva um programa que corre os números de 1 a 50 e imprime. Mas, quando for múltiplo
de três, imprima ‘Oops’, quando for múltiplo de 5 imprima ‘Doo’, quando for de ambos
imprima ‘OopsDoo’.
"""
for i in range(1, 51):
if i % 3 == 0 and i % 5 != 0:
print(i, 'Oops')
elif i % 5 == 0 and i % 3 != 0:
print(i, 'Doo')
elif i % 3 == 0 and i % 5 == 0:
print(i, 'OopsDoo')
else:
print(i)
|
e67e44f7b7d74555ffe140c188bd16d833c40459
|
davelpat/Fundamentals_of_Python
|
/Ch11 exercises/producer-consumer.py
| 3,672 | 3.71875 | 4 |
import time, random
from threading import Thread, currentThread, Condition
class SharedCell(object):
"""Shared data for the producer / consumer problem."""
def __init__(self):
"""Data undefined at startup."""
self.data = -1
self.writeable = True
self.condition = Condition()
def block_thread_on(self, block_condition):
self.condition.acquire()
while block_condition:
self.condition.wait()
def release_thread_lock(self):
self.condition.notify()
self.condition.release()
def setData(self, data):
"""Second caller must wait until someone has
consumed the data before restting it."""
# block_condition = not self.writeable
# self.block_thread_on(block_condition)
self.condition.acquire()
# while block_condition:
while not self.writeable:
self.condition.wait()
print("%s setting data to %d" % \
(currentThread().getName(), data))
self.data = data
self.writeable = False
self.release_thread_lock()
def getData(self):
"""Caller must wait until someon has written the data to access it."""
# block_condition = self.writeable
# self.block_thread_on(block_condition)
self.condition.acquire()
# while block_condition:
while self.writeable:
self.condition.wait()
print("%s accessing data %d" % \
(currentThread().getName(), self.data))
self.writeable = True
self.release_thread_lock()
return self.data
class Producer(Thread):
"""A producer of data in a shared cell."""
def __init__(self, cell, accessCount, sleepMax):
"""Create a producer with the given shared cell,
number of accesses, and maximum sleep interval."""
Thread.__init__(self, name="Producer")
self.accessCount = accessCount
self.cell = cell
self.sleepMax = sleepMax
def run(self):
"""Announce start-up, sleep and write to shared
cell the given number of times, and announce
completion."""
print("%s starting up" % self.getName())
for count in range(self.accessCount):
time.sleep(random.randint(1, self.sleepMax))
self.cell.setData(count + 1)
print("%s is done producing\n" % self.getName())
class Consumer(Thread):
"""A consumer of data in a shared cell."""
def __init__(self, cell, accessCount, sleepMax):
"""Create a consumer with the given shared cell,
number of accesses, and maximum sleep interval."""
Thread.__init__(self, name="Consumer")
self.accessCount = accessCount
self.cell = cell
self.sleepMax = sleepMax
def run(self):
"""Announce start-up, sleep and read from shared
cell the given number of times, and announce
completion."""
print("%s starting up" % self.getName())
for count in range(self.accessCount):
time.sleep(random.randint(1, self.sleepMax))
value = self.cell.getData()
print("%s is done consuming\n" % self.getName())
def main():
"""Get the number of accesses from the user, create a
shared cell, and create and start up a producer and a
consumer."""
accessCount = int(input("Enter the number of accesses: "))
sleepMax = 4
cell = SharedCell()
producer = Producer(cell, accessCount, sleepMax)
consumer = Consumer(cell, accessCount, sleepMax)
print("Starting the threads")
producer.start()
consumer.start()
if __name__ == '__main__':
main()
|
f80311b0d70570da1fc0a08dd3380aa72b960b2d
|
Fjelle/penguin-breakfast
|
/player.py
| 2,985 | 3.71875 | 4 |
import os
class Player():
def __init__(self,playernumber):
self.score=[]
self.rewarded_by=[]
self.playernumber=playernumber
self.victory_points=0
self.money=5
def return_victory_points(self):
return self.victory_points
def tell_rewarded(self,company_number):
self.rewarded_by.append(company_number)
def tell_score(self,score):
self.score=score
def return_money(self):
return self.money
def give_money(self,reward):
self.money=self.money+reward
def asktoinvest(self,companies_ingame):
#clear the screen to that players do not see their opponents numbers.
os.system('cls||clear')
input("are you ready player " + str(self.playernumber +1)+"? \n")
#give the player the necessary information about the game
print('\n Company 1, 2 and 3 are worth 1 pound. \n Company 4 and 5 are worth 2 pounds. \n Company 6 is worth 3 pounds. \n \n company 7,8 and 9 are worth 1 victory point \n company 10 and 11 are worth 2 victory point\n company 12 is worth 3 victory points\n')
for x in range(0,len(self.score)):
print("Player " + str(x + 1) + " has " + str(self.score[x]) + " victory points")
print("\n")
for x in range(0,len(self.rewarded_by)):
print("you have been rewarded by company "+str(self.rewarded_by[x]+1))
print("\n")
self.rewarded_by=[]
#ask the player to invest in the various companies
for x in range (0, len(companies_ingame)):
company_number=x+1
investment = -1
while not (0 <= investment <= self.money):
try:
investment = int(input("How much would you like to invest in company " + str(company_number)+ "? You have invested "+str(companies_ingame[x].return_investment(self.playernumber))+" in this company so far." +" You currently have " + str(self.money)+" pounds available to invest.\n"))
if investment > self.money:
print("You don't have that much money.")
elif investment == -3:
break
elif investment < 0 :
print("that is silly.")
except ValueError:
print("Please return a number.")
investment = -1
if investment == -3: #allows to quickly skip a player by entering -3 for an investment
break
self.money=self.money-int(investment)
companies_ingame[x].ownership[self.playernumber]=companies_ingame[x].ownership[self.playernumber]+int(investment)
def reward_money(self,reward_earned):
self.money=self.money+reward_earned
def reward_victory_points(self,reward_earned):
self.victory_points=self.victory_points+reward_earned
|
c9ec092763c94610b3cca5797021c5fa5da5a142
|
Nolagg/DataAnalysisMatplotlib
|
/script20_pieLabel.py
| 744 | 3.515625 | 4 |
import codecademylib
from matplotlib import pyplot as plt
import numpy as np
payment_method_names = ["Card Swipe", "Cash", "Apple Pay", "Other"]
payment_method_freqs = [270, 77, 32, 11]
#make your pie chart here
# Legend can be added with
# plt.legend(payment_method_names)
# or
# plt.pie(payment_method_freqs, labels=payment_method_names)
#
# autopct opion adds the percentage of each slice
# '%0.2f' — 2 decimal places, like 4.08
# '%0.2f%%' — 2 decimal places, but with a percent sign at the end, like 4.08%
# '%d%%' — rounded to the nearest int and with a percent sign at the end, like 4%
#
plt.pie(payment_method_freqs, labels=payment_method_names, autopct='%0.1f%%')
plt.legend(payment_method_names)
plt.axis('equal')
plt.show()
|
52414bec08d6de6cc45d82a8e047c4fff39f7b94
|
Praveenramkannan/Python_Assignments
|
/python-solutions/problem set 1/books.py
| 485 | 3.5625 | 4 |
'''
name:books.py
date:2-12-20017
author:[email protected]
question:Suppose the cover price of a book is Rs.24.95, but bookstores get a 40% discount. Shipping costs
Rs.3 for the first copy and 0.75p for each additional copy. What is the total wholesale cost for
60 copies?
'''
def calculate_sp(n):
sell_price=(24.95-(0.40*24.95))*n
shipping_cost=3+(0.75*(n-1))
total_price=sell_price+shipping_cost
print total_price
num=int(raw_input("enter the no.of books:"))
calculate_sp(num)
|
dc67a74409667fbf7eb51ecc9c5dce729b5b1b69
|
jayanthnagasai/pythongames
|
/Countdown.py
| 1,326 | 3.921875 | 4 |
import time
import sys
print()
print("Jay's countdown timer")
print()
c = ':'
print()
years = input("Years: ")
months = input("Months: ")
days = input("Days: ")
hours = input("Hours: ")
mins = input("Minutes: ")
secs = input("Seconds: ")
print()
hour = int(hours)
min = int(mins)
sec = int(secs)
day = int(days)
month = int(months)
year = int(years)
while year > -1:
while month > -1:
while day > -1:
while hour > -1:
while min > -1:
while sec > 0:
sec = sec - 1
time.sleep(1)
sec1 = ('%02.f' % sec)
min1 = ('%02.f' % min)
hour1 = ('%02.f' % hour)
day1 = ('%02.f' % day)
month1 = ('%02.f' % month)
year1 = ('%02.f' % year)
sys.stdout.write('\r' + str(year1) + c + str(month1) + c + str(day1) + c + str(hour1) + c + str(min1) + c + str(sec1))
min = min -1
sec = 59
hour = hour - 1
min = 59
day = day - 1
hour = 23
month = month - 1
day = 29
year = year - 1
month = 11
print()
print('Countdown Complete!!!')
time.sleep(10)
|
f7ef83c89889a516ed410ea3a00e4ac74b236144
|
JoseVale99/CursoPyQt5
|
/mult_inheritance.py
| 273 | 4.15625 | 4 |
class A:
"""
Example of multiple inheritance
"""
def a(self):
print("- From to A")
class B:
def b(self):
print("- From to B")
class C(A,B):
def c(self):
print("- From to C")
letter = C()
letter.a()
letter.b()
letter.c()
|
82001e0cb34cce6563eb114abd61484cbc2f5274
|
iankronquist/dotfiles
|
/windows/untag.py
| 838 | 3.875 | 4 |
import sys
import string
def is_hex_string(s):
# Is the set of actual characters - set of allowed characters == empty set?
return set(s) - set(string.hexdigits + 'xX') == set()
def num_string_to_tag(s):
tag = ''
if s.startswith('0x') or s.startswith('0X'):
s = s[2:]
for pair in list(zip(s,s[1:]))[::2]: # iterate pairwise
# Convert the pair to a base 16 int, and then convert it to a character and add it to the tag
tag += chr(int(pair[0] + pair[1], 16))
tag = tag[::-1] # reverse
return tag
def main(argv):
if len(argv) != 2 or not is_hex_string(argv[1]):
print("usage: ", argv[0], "HEXNUMBER")
return -1
s = argv[1]
tag = num_string_to_tag(s)
print(tag)
return 0
if __name__ == '__main__':
exit(main(sys.argv))
|
e940094bb4e5086e439ef7fb67aa794f950223b8
|
Teslatic/SC2-Freiburg
|
/cartpole/assets/helperFunctions/plotter.py
| 11,572 | 3.5 | 4 |
import numpy as np
import matplotlib.pyplot as plots
class Plotter():
"""
The Plotter class is used to plot the results from the experiment reports.
"""
def __init__(self, experiment_dir):
self.cwd = experiment_dir
###############################################################################
# open funtions
###############################################################################
def open_report(self):
"""
Opens the csv file.
"""
train_reports_dir = self.cwd + '/training_reports'
test_reports_dir = self.cwd + '/test_reports'
with open( self.cwd, mode=r) as f:
reader = csv.reader(f)
multireports = []
feature_vector = []
for parameter in sweepReport:
multiReport = sweepReport[parameter]
multireports.append(multiReport)
feature_vector.append(parameter)
return multireports, feature_vector
###############################################################################
# save method
###############################################################################
def _save_plot(self, save_path, name):
now = datetime.datetime.now()
file_string_png = '{}/plots/png/{}_{}.png'.format(save_path, now.strftime('%Y%m%d_%H%M%S'), name)
file_string_pdf = '{}/plots/pdf/{}_{}.pdf'.format(save_path, now.strftime('%Y%m%d_%H%M%S'), name)
print('saving png format')
print(file_string_png)
plt.savefig(file_string_png)
print('saving pdf format')
plt.savefig(file_string_pdf)
print(file_string_pdf)
###############################################################################
# statistics calculation
###############################################################################
def training_statistics(self, multiReport):
"""
Gets a multiReport and calculates mean and standard deviation of the test_report.
"""
training_reports, _, _ = self.open_multiReport(multiReport)
mean_vector = [np.mean(i) for i in zip(*training_reports)]
std_vector = [np.std(i) for i in zip(*training_reports)]
return mean_vector, std_vector
def test_statistics(self, multiReport):
"""
Gets a multiReport and calculates mean and standard deviation of the test_report.
"""
_, test_reports, test_each = self.open_multiReport(multiReport)
mean_vector = [np.mean(i) for i in zip(*test_reports)]
std_vector = [np.std(i) for i in zip(*test_reports)]
return mean_vector, std_vector, test_each[0]
def training_statistics_sweep(self, multireports):
feature_mean_vector = []
feature_std_vector = []
for report in range(len(multireports)):
mean_vector, std_vector = self.training_statistics(multireports[report])
feature_mean_vector.append(mean_vector)
feature_std_vector.append(std_vector)
meanofmeans = [np.mean(i) for i in zip(*feature_mean_vector)]
stdofstd = [np.std(i) for i in zip(*feature_std_vector)]
return meanofmeans, stdofstd
def test_statistics_sweep(self, multireports):
feature_mean_vector = []
feature_std_vector = []
for report in range(len(multireports)):
mean_vector, std_vector, test_each = self.test_statistics(multireports[report])
feature_mean_vector.append(mean_vector)
feature_std_vector.append(std_vector)
meanofmeans = [np.mean(i) for i in zip(*feature_mean_vector)]
stdofstd = [np.std(i) for i in zip(*feature_std_vector)]
return meanofmeans, stdofstd, test_each
###############################################################################
# Plotting funtions - single runs
###############################################################################
def plot_training(self, save_path, training_report, run_num=None):
"""
Make sure that the directory has been created by the FileManager.
"""
plt.figure()
x_data = np.arange(len(training_report))
plt.plot(x_data, training_report,label = "DankAgent")
plt.xlabel("Training episode")
plt.ylabel("Total episode reward")
plt.legend(loc='upper left')
if run_num is None:
self._save_plot(save_path, 'training_report')
else:
self._save_plot(save_path, 'training_report_run{}'.format(run_num))
plt.close()
def plot_test(self, save_path, test_report, run_num=None, testeach=None):
"""
Make sure that the directory has been created by the FileManager.
"""
plt.figure()
if testeach is None:
plt.plot(test_report, label = "DankAgent")
else:
x_data = testeach*(np.arange(len(test_report))+1)
plt.plot(x_data, test_report, label = "DankAgent")
plt.xlabel("Test episode")
plt.ylabel("Average Test Reward")
plt.legend(loc='upper left')
if run_num is None:
self._save_plot(save_path, 'test_report')
else:
self._save_plot(save_path, 'test_report_run{}'.format(run_num))
plt.close()
###############################################################################
# Plotting funtions - multiple runs (with multiReport)
###############################################################################
def plot_test_multireport(self, multiReport, save_path, name):
"""
"""
_, test_reports, _ = self.open_multiReport(multiReport)
mean_vector, std_vector, test_each = self.test_statistics(multiReport)
# create_plot_test_mean_std
plt.figure()
x_data = test_each*(np.arange(len(mean_vector))+1) # +1
for run in range(len(multiReport)):
plt.plot(x_data, test_reports[run], label = 'run {}'.format(run))
plt.plot(x_data, mean_vector, label ='mean reward')
plt.plot(x_data, np.add(mean_vector, std_vector), label='+STD', linestyle = '-.')
plt.plot(x_data, np.subtract(mean_vector, std_vector), label='-STD', linestyle = '-.')
plt.title("Test results for several runs")
plt.xlabel("Intermediate test after training episode")
plt.ylabel("Average reward")
plt.legend(loc='upper left')
self._save_plot(save_path, name)
plt.close()
def plot_training_multireport(self, multiReport, save_path, name):
"""
"""
training_report, _, _ = self.open_multiReport(multiReport)
mean_vector, std_vector = self.training_statistics(multiReport)
plt.figure()
x_data = np.arange(len(mean_vector)) # +1
for run in range(len(multiReport)):
plt.plot(x_data, training_report[run], label = 'run {}'.format(run))
plt.plot(x_data, mean_vector, label ='mean of means')
plt.plot(x_data, np.add(mean_vector, std_vector), label='+STD', linestyle = '-.')
plt.plot(x_data, np.subtract(mean_vector, std_vector), label='-STD', linestyle = '-.')
plt.title("Training results for several runs")
plt.xlabel("Training episode")
plt.ylabel("Episode reward")
plt.legend(loc='upper left')
self._save_plot(save_path, name)
plt.close()
###############################################################################
# Plotting funtions - multiple features (with sweepReport)
###############################################################################
def plot_training_sweep(self, sweepReport, save_path, name):
multireports, feature_vector = self.open_sweepReport(sweepReport)
meanofmeans, stdofstd = self.training_statistics_sweep(multireports)
self.plot_mean_std_training(meanofmeans, stdofstd, feature_vector, save_path, name)
self.create_sweep_plot_training(multireports, meanofmeans, stdofstd, feature_vector, save_path, name)
def plot_mean_std_training(self, mean_vector, std_vector, feature_vector, save_path, name):
plt.figure()
x_data = np.arange(len(mean_vector)) # +1
plt.plot(x_data, mean_vector, label ='mean of means')
plt.plot(x_data, np.add(mean_vector, std_vector), label='+STD', linestyle = '-.')
plt.plot(x_data, np.subtract(mean_vector, std_vector), label='-STD', linestyle = '-.')
plt.title("Training results for several sweeps")
plt.xlabel("Training episode")
plt.ylabel("Episode reward")
plt.legend(loc='upper left')
self._save_plot(save_path, '{}_clean'.format(name))
plt.close()
def create_sweep_plot_training(self, multireports, mean_vector, std_vector, feature_vector, save_path, name):
plt.figure()
x_data = np.arange(len(mean_vector)) # +1
for feature in range(len(multireports)):
feature_mean, _ = self.training_statistics(multireports[feature])
plt.plot(x_data, feature_mean, label = 'feature {}'.format(feature_vector[feature]))
plt.plot(x_data, mean_vector, label ='mean of means')
plt.plot(x_data, np.add(mean_vector, std_vector), label='+STD', linestyle = '-.')
plt.plot(x_data, np.subtract(mean_vector, std_vector), label='-STD', linestyle = '-.')
plt.title("Training results for several sweeps")
plt.xlabel("Training episode")
plt.ylabel("Episode reward")
plt.legend(loc='upper left')
self._save_plot(save_path, name)
plt.close()
def plot_test_sweep(self, sweepReport, save_path, name):
multireports, feature_vector = self.open_sweepReport(sweepReport)
meanofmeans, stdofstd, test_each = self.test_statistics_sweep(multireports)
self.plot_mean_std_test(meanofmeans, stdofstd, feature_vector, test_each, save_path, name)
self.create_sweep_plot_test(multireports, meanofmeans, stdofstd, feature_vector, test_each, save_path, name)
def plot_mean_std_test(self, mean_vector, std_vector, feature_vector, test_each, save_path, name):
plt.figure()
x_data = test_each*(np.arange(len(mean_vector))+1) # +1
plt.plot(x_data, mean_vector, label ='sweep mean')
plt.plot(x_data, np.add(mean_vector, std_vector), label='+STD', linestyle = '-.')
plt.plot(x_data, np.subtract(mean_vector, std_vector), label='-STD', linestyle = '-.')
plt.title("Test results for several sweeps")
plt.xlabel("Training episode")
plt.ylabel("Episode reward")
plt.legend(loc='upper left')
self._save_plot(save_path, '{}_clean'.format(name))
plt.close()
def create_sweep_plot_test(self, multireports, mean_vector, std_vector, feature_vector, test_each, save_path, name):
plt.figure()
x_data = test_each*(np.arange(len(mean_vector))+1) # +1
for feature in range(len(multireports)):
feature_mean, _, _ = self.test_statistics(multireports[feature])
plt.plot(x_data, feature_mean, label = 'feature {}'.format(feature_vector[feature]))
plt.plot(x_data, mean_vector, label ='mean of means')
plt.plot(x_data, np.add(mean_vector, std_vector), label='+STD', linestyle = '-.')
plt.plot(x_data, np.subtract(mean_vector, std_vector), label='-STD', linestyle = '-.')
plt.title("Test results for several sweeps")
plt.xlabel("Training episode")
plt.ylabel("Episode reward")
plt.legend(loc='upper left')
self._save_plot(save_path, name)
plt.close()
|
bd5e847ceb798755e1ecc40bbfb40f4c56510409
|
danfinn/pythoncode
|
/russian_peasant.py
| 337 | 4.03125 | 4 |
#! /usr/bin/python
# Uses the russian peasant algorithim to add 2 numbers
num1 = int(raw_input('First number please: '))
num2 = int(raw_input('Second number please: '))
def russian_peasant(a,b):
x = a; y =b
z = 0
while x > 0:
if x % 2 == 1: z += y
x = x >> 1
y = y << 1
return z
print russian_peasant(num1,num2)
|
eecc4718a355cfb23fc57f441cda775b13ae4592
|
DuongNg0403/PythonDA
|
/Data Structures/Set.py
| 268 | 3.609375 | 4 |
s1 = {1,1,5,3,4,7,5}
print(s1)
s2 = {2,3,7,5,9}
print(s1|s2) #s1|=s2 equivalent to s1 = s1|s2
print(s1&s2) #s1&=s2 equivalent to s1 = s1&s2
print(s1-s2) #s1-=s2 equivalent to s1 = s1-s2
print(s1^s2) #s1^=s2 equivalent to s1 = s1^s2
print(s1.isdisjoint(s2))
|
6b3b208b669687b5dd6d1da5c8d4e4024829f8de
|
xy2333/Leetcode
|
/leetcode/addTwoNumbers.py
| 726 | 3.78125 | 4 |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
res = ListNode(0)
p = res
while l1 is not None and l2 is not None:
p.next = ListNode(0)
p.next.val += l1.val+l2.val
p = p.next
l1 = l1.next
l2 = l2.next
if l1 is None and l2 is None:
pass
elif l1 is None:
p.next = l2
else:
p.next = l1
q = res
while q is not None:
if q.val >= 10:
if q.next is None:
q.next = ListNode(0)
q.next.val += q.val//10
q.val = q.val%10
q = q.next
return res.next
|
9f880cdc098dbae21342e97d3d99c3cf91ff8e58
|
cerealkella/rpi-examples
|
/salt_level.py
| 2,239 | 3.5 | 4 |
import RPi.GPIO as GPIO
import time
import signal
import sys
import send_email
from creds import TO
def close(signal, frame):
print("\nTurning off ultrasonic distance detection...\n")
GPIO.cleanup()
sys.exit(0)
def calculate_distance_mean():
# use Raspberry Pi board pin numbers
GPIO.setmode(GPIO.BCM)
# set GPIO Pins
pinTrigger = 18
pinEcho = 24
signal.signal(signal.SIGINT, close)
# set GPIO input and output channels
GPIO.setup(pinTrigger, GPIO.OUT)
GPIO.setup(pinEcho, GPIO.IN)
readings = 20
i = 0
distance = 0.0
cumulative_distance = 0.0
print(time.localtime())
while i < readings:
# set Trigger to HIGH
GPIO.output(pinTrigger, True)
# set Trigger after 0.01ms to LOW
time.sleep(0.00001)
GPIO.output(pinTrigger, False)
startTime = time.time()
stopTime = time.time()
# save start time
while 0 == GPIO.input(pinEcho):
startTime = time.time()
# save time of arrival
while 1 == GPIO.input(pinEcho):
stopTime = time.time()
# time difference between start and arrival
TimeElapsed = stopTime - startTime
# multiply with the sonic speed (34300 cm/s)
# and divide by 2, because there and back
distance = (TimeElapsed * 34300) / 2
print("Distance: %.1f cm" % distance)
time.sleep(1)
i += 1
cumulative_distance += distance
dist_average = round((cumulative_distance / readings), 2)
print("Average distance: {}".format(dist_average))
return dist_average
def level_notifier(distance):
if distance > 14:
return "getting low"
else:
return "okay"
salt_level = calculate_distance_mean()
if salt_level > 25:
print("low salt -- sending email")
subject = "Salt Level"
text = """
This message is sent from your water softener.
Yeah, that's right, your water softener is now
self-aware.
The salt is {0} cm from the sensor. Might wanna
add a bag or two.
""".format(salt_level)
msg = 'Subject: {}\n\n{}'.format(subject, text)
for recipient in TO:
send_email.send_mail(msg=msg, to=recipient)
|
d9f55994a26c042a822072a86f2bb3383d94f27a
|
agronja/cse-34872-su20-examples
|
/lecture07/02_cookies/cookies.py
| 645 | 3.59375 | 4 |
#!/usr/bin/env python3
import sys
# Functions
def feed_children(children, cookies):
count = 0
while cookies and children:
child = children.pop(0)
cookie = cookies[0]
if child <= cookie:
cookies.pop(0)
count += 1
return count
def main():
while ((children := sys.stdin.readline().split()) and
(cookies := sys.stdin.readline().split())):
children = sorted(map(int, children), reverse=True)
cookies = sorted(map(int, cookies) , reverse=True)
print(feed_children(children, cookies))
# Main execution
if __name__ == '__main__':
main()
|
805884a12554012df8f5597409fded6a87268523
|
JenZhen/LC
|
/lc_ladder/company/gg/high_freq/My_Calendar_II.py
| 4,513 | 3.84375 | 4 |
#! /usr/local/bin/python3
# https://leetcode.com/problems/my-calendar-ii/
# Example
# Implement a MyCalendarTwo class to store your events. A new event can be added if adding the event will not cause a triple booking.
#
# Your class will have one method, book(int start, int end). Formally, this represents a booking on the half open interval [start, end), the range of real numbers x such that start <= x < end.
#
# A triple booking happens when three events have some non-empty intersection (ie., there is some time that is common to all 3 events.)
#
# For each call to the method MyCalendar.book, return true if the event can be added to the calendar successfully without causing a triple booking. Otherwise, return false and do not add the event to the calendar.
#
# Your class will be called like this: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end)
# Example 1:
#
# MyCalendar();
# MyCalendar.book(10, 20); // returns true
# MyCalendar.book(50, 60); // returns true
# MyCalendar.book(10, 40); // returns true
# MyCalendar.book(5, 15); // returns false
# MyCalendar.book(5, 10); // returns true
# MyCalendar.book(25, 55); // returns true
# Explanation:
# The first two events can be booked. The third event can be double booked.
# The fourth event (5, 15) can't be booked, because it would result in a triple booking.
# The fifth event (5, 10) can be booked, as it does not use time 10 which is already double booked.
# The sixth event (25, 55) can be booked, as the time in [25, 40) will be double booked with the third event;
# the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.
#
#
# Note:
#
# The number of calls to MyCalendar.book per test case will be at most 1000.
# In calls to MyCalendar.book(start, end), start and end are integers in the range [0, 10^9].
"""
Algo:
D.S.: sweeping line, interval
Solution:
Time: O(n)
Space: O(n)
interval non-merge
这个题目如果要用sweeping Line需要sort端点,端点需要用treemap 结构
case 1: b ends before a ends:
a: a0 |-------------| a1
b: b0 |-----| b1
case 2: b ends after a ends:
a: a0 |--------| a1
b: b0 |--------| b1
case 3: b starts after a ends: (negative overlap)
a: a0 |----| a1
b: b0 |----| b1
Corner cases:
"""
class MyCalendarTwo:
def __init__(self):
self.overlap = [] # interval of book overlap, intervals no overlap
self.books = [] # books interval, may have overlap, no triple overlaps
def book(self, start: int, end: int) -> bool:
# iterate through self.overlap to see if valid
for intv in self.overlap:
new_start = max(intv[0], start)
new_end = min(intv[1], end)
if new_start < new_end:
return False
# if valid need to update self.overlap and self.books
for book in self.books:
# find all overlap intervals added to self.overlap
# no need to merge
# simply append new book interval at the end
new_start = max(book[0], start)
new_end = min(book[1], end)
if new_start < new_end:
# a valid overlap
self.overlap.append((new_start, new_end))
self.books.append((start, end))
return True
# Your MyCalendarTwo object will be instantiated and called as such:
# obj = MyCalendarTwo()
# param_1 = obj.book(start,end)
class MyCalendarTwo {
private TreeMap<Integer, Integer> map;
public MyCalendarTwo() {
map = new TreeMap<>(); // key: position, val: cnt, start point +1, end point -1
}
public boolean book(int start, int end) {
map.put(start, map.getOrDefault(start, 0) + 1);
map.put(end, map.getOrDefault(end, 0) - 1);
int count = 0;
// iterate treemap entry, which is a sorted list based on key
// this is like sorted endpoints like in sweepingline method.
for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
count += entry.getValue();
if(count > 2) {
map.put(start, map.get(start) - 1);
if(map.get(start) == 0) {
map.remove(start);
}
map.put(end, map.get(end) + 1);
if(map.get(end) == 0) {
map.remove(end);
}
return false;
}
}
return true;
}
}
# Test Cases
if __name__ == "__main__":
solution = Solution()
|
4934cda57fe6f2f81ebe7fa01d77d9213eb4a79e
|
xxcocoymlxx/Study-Notes
|
/CSC108/practices/class example/Class_example2.py
| 1,036 | 3.703125 | 4 |
class Actor:
def __init__(self, HP, AP, sex):
self.HP = HP
self.AP = AP
self.sex = sex
class Monster(Actor):
def attack(self,other, AP, HP_cost):
if (other.HP >= HP_cost):
other.HP -= HP_cost
print("Attack Successfully")
return True
else:
print("The actor is dead")
return False
def __str__(self):
return "The actor info: {0}, {1}, {2}".format(self.HP, self.AP, self.sex)
class Hero(Actor):
def __init__(self, HP, AP, sex, money): # magic method
super().__init__(HP,AP, sex) #constant variables
self.armour_set = []
self.money = money
def attack(self, other1, other2, AP, HP_cost):
if (other1.HP >= HP_cost and other2.HP >= HP_cost):
other1.HP -= HP_cost
other2.HP -= HP_cost
print("Attack Successfully")
return True
else:
print("The actor is dead")
return False
|
0a497a4a10622fa93aaa4eaa97b461e77a44af1d
|
josecervan/Python-Developer-EOI
|
/module2/lambda_funcs/sorting_a_sequence.py
| 619 | 3.859375 | 4 |
notas = [{'nombre': 'Lola', 'final': 9},
{'nombre': 'Javier', 'final': 9.2},
{'nombre': 'Marta', 'final': 9.5}]
if __name__ == '__main__':
nombres_ordenados = sorted(notas, key=lambda nota: nota.get('nombre'))
notas_ordenadas = sorted(notas, key=lambda nota: nota.get('nombre'))
minima = min(notas, key=lambda nota: nota.get('final'))
maxima = max(notas, key=lambda nota: nota.get('final'))
print(f'Notas: {notas}')
print(f'Por nombre: {nombres_ordenados}')
print(f'Por nota: {notas_ordenadas}')
print(f'Nota mínima: {minima}')
print(f'Nota mínima: {maxima}')
|
9611d0b89d91166cdb607f6692de77cc2d44a2ae
|
RolfHaakon/PythonExercises
|
/Exercises/SimpleNeuralNetwork.py
| 1,150 | 4.21875 | 4 |
"""
https://www.kode24.no/guider/the-best-way-to-learn-deep-learning/71003527
Simple neural network
"""
def simple_neural_netowrk(input, weight, goal_prediction, train):
for i in range(train):
prediction = input * weight
"""
Squared root error is used to always get a positive number to work with
"""
error = (prediction - goal_prediction) ** 2
"""Delta is a measurement of the differation between the true prediction and NN prediction
For example if the true prediction is 1.0 and the NN prediction is 0.85, the delta is negative 0.15"""
delta = prediction - goal_prediction
"""
Weight_Delta is a value of how much the a weight caused the network to miss, this value
will help us understand and reduce the amount we missed
"""
weight_delta = delta * input
"""
Before updating the weight we multiply with alpah, this is to set the pace the NN learn on
"""
alpah = 3
weight -= weight_delta * alpah
print('Error: ',error, ' Prediction: ', prediction)
simple_neural_netowrk(0.3,0.1,0.7, 10)
|
b75ac45c451be2c68c87f5bd0ae53b8d69266d3a
|
risoyo/CodingInterviews
|
/剑指offer-牛客/08-跳台阶.py
| 478 | 3.5625 | 4 |
# -*- coding:utf-8 -*-
class Solution:
def jumpFloor(self, number):
if number == 1:
return 1
elif number == 0:
return 0
elif number == 2:
return 2
result = [0, 1, 2]
jt = 0
j1 = 1
j2 = 2
for i in range(1, number-1):
jt = j1 + j2
j1 = j2
j2 = jt
return jt
if __name__ == '__main__':
bat = Solution()
print bat.jumpFloor(6)
|
b1020091986a1897a0246022f15bc97310eec117
|
Shraddha0501/Covid-19-Analysis
|
/covid19 analysis.py
| 1,732 | 3.859375 | 4 |
#Importing Pandas
import pandas as pd
#Library used to fetch the data from web
import requests
#Data collection/scraping from url(wikipedia)
url = 'https://en.wikipedia.org/wiki/COVID-19_pandemic_by_country_and_territory'
request_url = requests.get(url)
#The desired data will be filtered and stored in req_data
req_data = pd.read_html(request_url.text)
#Data frame is fetched by assigning the variable and index in which it exists
df = req_data[10]
#Data cleaning
#Renaming column names
df.columns = ['column0', 'Country name' , 'Total Cases', 'Total Deaths','Total Recoveries','column5']
#Removing unnecessary columns, column0 and column5 in this case from the dataframe
df = df[['Country name' , 'Total Cases', 'Total Deaths','Total Recoveries']]
#Removing irrelevant rows from data, i.e row index 243 and 244(last 2 rows)
rem_index = df.index[-1]
df = df.drop([rem_index,rem_index-1])
#Removing strings inside the brackets in the Country name column and Total Deaths column using regular expression
df['Country name'] = df['Country name'].str.replace('\[.*\]','')
df['Total Deaths'] = df['Total Deaths'].str.replace('+','')
#Replacing 'no data' in Total Recoveries column with 0
df['Total Recoveries'] = df['Total Recoveries'].str.replace('No data','0')
#Changing data type of 'Total Cases', 'Total Deaths','Total Recoveries' to int
df['Total Cases'] = pd.to_numeric(df['Total Cases'])
df['Total Deaths'] = pd.to_numeric(df['Total Deaths'])
df['Total Recoveries'] = pd.to_numeric(df['Total Recoveries'])
#Data Organization
#Exporting data set
#df.to_csv(r'covid19 analysis.csv')
df.to_excel(r'covid19 analysis.xlsx')
|
793bc622604a641cb69f6b9ce39d06c8ddcede38
|
ljubicamiljkovic56/op2018
|
/ProjekatOP2018 ver2/funkcije/pretragaRezervacija.py
| 2,057 | 3.515625 | 4 |
def formatTabela():
print("Sifra |Sb|Datum rezervac. |Datum prijave |Datum odjave |K.ime |Tip sobe|Kl|Tv|Kp|Tr|Cena|Rezerv.|O")
print("------+--+----------------+----------------+----------------+------+--------+--+--+--+--+----+-------+-")
def pretragaRezervacija():
print("Pretraga rezervacija")
print("1 - Pretraga po korisniku")
print("2 - Pretraga po bilo kom kriterijumu")
unos = input(">>>")
print("--------------------")
if unos == '1':
korisnik = input("Unesite tacno korisnicko ime korisnika: ")
lista = []
otvori = open("rezervacija.txt", "r")
redovi = otvori.readlines()
recnik = {}
formatTabela()
for red in redovi:
red = red.split("|")
if red[5] == korisnik:
recnik = {'sf':red[0],'sb':red[1],'dr':red[2],'dp':red[3],'do':red[4],'k':red[5],'t':red[6],'kl':red[7],'tv':red[8],'tr':red[9],'kp':red[10],'c':red[11],'r':red[12],'o':red[13]}
lista = [recnik]
for i in lista:
print("{0:2}|{1:2}|{2:4}|{3:4}|{4:4}|{5:4}|{6:4}|{7:2}|{8:2}|{9:2}|{10:2}|{11:3}|{12:3}|{13:1}".format(i['sf'],i['sb'],i['dr'],i['dp'],i['do'],i['k'],i['t'],i['kl'],i['tv'],i['tr'],i['kp'],i['c'],i['r'],i['o']))
print("--------------------")
otvori.close()
elif unos == '2':
inf = input("Unesite informaciju: ")
lista = []
otvori = open("rezervacija.txt", "r")
redovi = otvori.readlines()
recnik = {}
formatTabela()
for red in redovi:
red = red.split("|")
recnik = {'sf':red[0],'sb':red[1],'dr':red[2],'dp':red[3],'do':red[4],'k':red[5],'t':red[6],'kl':red[7],'tv':red[8],'tr':red[9],'kp':red[10],'c':red[11],'r':red[12],'o':red[13]}
lista = [recnik]
for i in red:
if i == inf:
for i in lista:
print("{0:2}|{1:2}|{2:4}|{3:4}|{4:4}|{5:4}|{6:4}|{7:2}|{8:2}|{9:2}|{10:2}|{11:3}|{12:3}|{13:1}".format(i['sf'],i['sb'],i['dr'],i['dp'],i['do'],i['k'],i['t'],i['kl'],i['tv'],i['tr'],i['kp'],i['c'],i['r'],i['o']))
print("-----------------------")
otvori.close()
else:
print("Uneli ste nepostojecu opciju.")
pretragaRezervacija()
|
33b606e8032349fd9feb44aea503fb09b22d47c4
|
mkokol/design_patterns
|
/structural/decorator/src/component.py
| 524 | 3.59375 | 4 |
from abc import ABC, abstractmethod
class AbstractComponent(ABC):
@abstractmethod
def render(self):
pass
@abstractmethod
def get_size(self):
pass
class TextComponent(AbstractComponent):
def __init__(self, text):
self.text = text
@property
def text(self):
return self.__text
@text.setter
def text(self, value):
self.__text = value
def render(self):
print(self.text, end='')
def get_size(self):
return len(self.text)
|
f7abfa9863b7dade169f9ccf6422138011336e57
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/python/rna-transcription/708dfc085bc34edcb36a606113c3da87.py
| 253 | 3.59375 | 4 |
class DNA(object):
def __init__(self,strand):
self.strand = strand
def to_rna(self):
tr = {'G':'C', 'C':'G', 'T':'A', 'A':'U'}
rna = ''
for strand in self.strand:
rna += tr[strand]
return rna
|
32a88153fa15eb016907e2a4f7255d1b2467d36c
|
pkmm91/competitive-programming-solutions
|
/URI/1070.py
| 209 | 3.671875 | 4 |
import os
import sys
num = int(raw_input())
count = 0
while (1):
if (num % 2 != 0):
print (num)
count = count + 1
num = num + 1
if (count == 6):
break
|
671a7c9934c89837e0c43e17561749889de17657
|
mandypar/Python-Coursework
|
/PythonCode/Assignment5_2a.py
| 412 | 4.15625 | 4 |
largest = None
smallest = None
while True:
num=raw_input('Enter a number:')
if num == "done": break
try:
numfinal = int(num)
except:
print 'Invalid input'
continue
if numfinal>largest:
largest=numfinal
continue
if numfinal is not smallest:
smallest=numfinal
continue
if numfinal<smallest:
smallest=numfinal
print "Maximum is", largest
print "Minimum is", smallest
|
f6d6e6cb0179be2b73ff66ae3a72fbe59e4dd13c
|
osmarsalesjr/AtividadesProfFabioGomesEmPython3
|
/Atividades1/At1Q16.py
| 294 | 3.796875 | 4 |
def main():
lado_quadrado = float(input("Digite o valor do lado do quadrado para obter sua area: "))
print("A area desse quadrado é ", calcula_area(lado_quadrado), "u².")
def calcula_area(valor_lado):
area = valor_lado ** 2
return area
if __name__ == '__main__':
main()
|
ae661253d50c9d9843e75196ed8988c47e05e739
|
jkohans/adventofcode2020
|
/day5/day5.py
| 1,900 | 3.75 | 4 |
import math
def find_passport(input_filename):
num_rows = 128
num_columns = 8
seat_codes = []
current_max = 0
for line in open(input_filename):
line = line.rstrip("\n")
row_directions = line[:7]
column_directions = line[7:]
row_answer = bin_search(num_rows, row_directions, "F", "B")
column_answer = bin_search(num_columns, column_directions, "L", "R")
# print(row_answer, column_answer)
# print("------------")
seat_code = row_answer * 8 + column_answer
seat_codes.append(seat_code)
if seat_code > current_max:
current_max = seat_code
return seat_codes
def find_missing_seat(seat_codes):
seat_codes.sort()
for idx, id in enumerate(seat_codes):
if idx - 1 >= 0: # check that lower number is right
if seat_codes[idx - 1] != id - 1:
return id - 1
def bin_search(num_items, directions, lower_string, upper_string):
current_range = (0, num_items) # max is exclusive
for direction in directions:
# print(direction)
if direction == upper_string:
new_min = current_range[0] + math.ceil((current_range[1] - current_range[0]) / 2)
current_range = (new_min, current_range[1])
elif direction == lower_string:
new_max = current_range[1] - math.floor((current_range[1] - current_range[0]) / 2)
current_range = (current_range[0], new_max)
else:
print("shit done broke on unknown direction", direction)
exit(1)
# print(current_range)
if not (0 <= current_range[0] < num_items):
print("chose an index out of range", current_range[0], num_items)
exit(1)
return current_range[0]
if __name__ == "__main__":
seat_codes = find_passport("day5_input.txt")
print(find_missing_seat(seat_codes))
|
1b87ded4567a47b0a7bb30ec38be246d2caadec2
|
pflun/advancedAlgorithms
|
/threeSumSmaller.py
| 922 | 3.703125 | 4 |
# -*- coding: utf-8 -*-
class Solution(object):
# two pointer, one from left (after i), the other one from most right
# 跟 3 sum 一样,固定一点,从这点下一个开始两头往中间扫
# 利用 sum < target 时,i 和 left 不动,介于 left 和 right (包括 right) 之间的所有元素 sum 也一定小于 target 的单调性。
def threeSumSmaller(self, nums, target):
nums.sort()
length = len(nums) - 1
res = []
for i in range(length):
j = i + 1
k = length
# two pointer
while j < k:
if nums[i] + nums[j] + nums[k] < target:
for l in range(j, k):
res.append([nums[i], nums[l], nums[k]])
j += 1
else:
k -= 1
return res
test = Solution()
print test.threeSumSmaller([-2, 0, 1, 3], 2)
|
d8d9c686e622429780d9db46d0457601a1cd1cd5
|
rongpenl/k16math-course
|
/exercises/solution_02_02_01.py
| 364 | 4.09375 | 4 |
# Given a __distance__ in miles, find its value in __kilometers__.
def mileToKilometers(mile):
if mile > 100 or mile < 0:
print("{} is not valid. Please make sure it is between 0 and 100.".format(mile))
return None
else:
kilo = mile*1.6
print("{} mile(s) is roughly () kilometer(s).".format(mile, kilo))
return kilo
|
6c742d854ea4efa2c99ed384588f118ea717511e
|
35sebastian/Proyecto_Python_1
|
/CaC Python/EjerciciosPy1/Ej5.py
| 161 | 4.0625 | 4 |
nombre = input("Ingrese su nombre: ")
numero_entero = int(input("Ingrese un numero: "))
print()
for i in range(numero_entero):
print(str(i+1) + " " + nombre)
|
26cb69c5b86bafb8ae702b9ae54a6e5d49335ebf
|
rafaelperazzo/programacao-web
|
/moodledata/vpl_data/389/usersdata/313/73603/submittedfiles/poligono.py
| 68 | 3.65625 | 4 |
n=int(input('digite o valor de n'))
nd=n(n-3)/2
print('%d' % nd)
|
1709904989c53e8b793c94b008a48f36811a636d
|
nhatsmrt/AlgorithmPractice
|
/LeetCode/369. Plus One Linked List/Solution.py
| 668 | 3.578125 | 4 |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def plusOne(self, head: ListNode) -> ListNode:
carry = self.plus(head)
if carry:
return ListNode(carry, head)
return head
def plus(self, node: ListNode) -> int:
if node.next:
carry = self.plus(node.next)
sum = node.val + carry
else:
sum = node.val + 1
if sum >= 10:
node.val = sum % 10
return 1
else:
node.val = sum
return 0
|
de502088598a929241f3eda2d9e671e4a7b21f6e
|
ARSimmons/IntroToPython
|
/Students/A.Kramer/session03/mailroom.py
| 2,402 | 3.859375 | 4 |
def execute():
"""Run the main program """
donors = [["Jon Doe", 50, 2], ["Jane Doe", 35, 7], ["Anonymous", 30, 10]]
prompt = "Please, select the following options\n1 - Send a Thank you Letter\n2 - Create Report\n3 - Quit\n"
while True:
print prompt
answer = raw_input("What is your choice: ")
if answer == '2':
print_report(donors)
elif answer == '1':
generate_letters(donors)
elif answer == '3':
print "Have a good day"
break
else:
print "Unrecognized option"
print ""
def print_report(d):
"""Print users' report"""
for donor in d:
avg_amnt = 0
if donor[2] == 0:
avg_amnt = 0
else:
avg_amnt = donor[1]/donor[2]
print "Name: %s\tTotal Donated: $%2.2f\tNumber of Donations: %i\tAverage Donation: $%2.2f" % (donor[0], donor[1], donor[2], avg_amnt)
print ""
def generate_letters(d):
"""Generate Thank you letter"""
name = select_donor(d)
donation = get_donation(name)
email_text = "Dear " + name + ",\n\nThank you very much for your generous donation of $" + str(donation) + ".\nThis donation will go a long way."
email_text = email_text + "\n\nThank you again,\n\nSupport Staff"
print "\n======================================================================="
print email_text
print "=======================================================================\n"
for k in d:
if k[0] == name:
k[1] = k[1] + float(donation)
k[2] = k[2] + 1
def get_donation(n):
"""Obtain donation ammount"""
while True:
amount = raw_input("\nProvide donation amount: ")
try:
if float(amount):
return float(amount)
except ValueError:
print "Invalid Number provided for donation"
def select_donor(d):
"""Obtain Donor name to use"""
while True:
n = raw_input("\nType the name of the donor or type the work 'list': ")
if n == "list":
print n == "list"
for x in d:
print x[0]
else:
for g in d:
if g[0] == n:
return n
d.append([n, 0, 0])
return n
if __name__ == "__main__":
"""Execute the main program"""
execute()
|
3cecccb85d1114a64abe8c5e6f5a9c5e74d2f05f
|
a69e/LeetCode
|
/DFS/51.n-queens.py
| 2,252 | 3.796875 | 4 |
#
# @lc app=leetcode id=51 lang=python3
#
# [51] N-Queens
#
# https://leetcode.com/problems/n-queens/description/
#
# algorithms
# Hard (55.13%)
# Likes: 4654
# Dislikes: 137
# Total Accepted: 322.7K
# Total Submissions: 584K
# Testcase Example: '4'
#
# The n-queens puzzle is the problem of placing n queens on an n x n chessboard
# such that no two queens attack each other.
#
# Given an integer n, return all distinct solutions to the n-queens puzzle. You
# may return the answer in any order.
#
# Each solution contains a distinct board configuration of the n-queens'
# placement, where 'Q' and '.' both indicate a queen and an empty space,
# respectively.
#
#
# Example 1:
#
#
# Input: n = 4
# Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
# Explanation: There exist two distinct solutions to the 4-queens puzzle as
# shown above
#
#
# Example 2:
#
#
# Input: n = 1
# Output: [["Q"]]
#
#
#
# Constraints:
#
#
# 1 <= n <= 9
#
#
#
from typing import List
# @lc code=start
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
board = ['.' * n for _ in range(n)]
ans = []
def backtrack(board, row):
if row == n:
ans.append(list(board))
return
for col in range(n):
if not isValid(board, row, col):
continue
temp = list(board[row])
temp[col] = 'Q'
board[row] = ''.join(temp)
backtrack(board, row + 1)
board[row] = '.' * n
def isValid(board, row, col):
for r in range(n):
if board[r][col] == 'Q':
return False
r, c = row, col
while r > 0 and c > 0:
if board[r-1][c-1] == 'Q':
return False
r -= 1
c -= 1
r, c = row, col
while r > 0 and c < n - 1:
if board[r-1][c+1] == 'Q':
return False
r -= 1
c += 1
return True
backtrack(board, 0)
return ans
# @lc code=end
# Test
print(Solution().solveNQueens(4))
|
3310a3de21a47bae6def014f018ee22b6b6d2d92
|
bhakes/Sprint-Challenge--Algorithms
|
/Short-Answer/scratch_pad.py
| 811 | 3.59375 | 4 |
import time
def test(n):
a = 0
t0 = time.time()
while (a < n):
print(a)
a = a + 1
t1 = time.time()
total = t1-t0
print(total)
test(10000)
def test2(n):
t0 = time.time()
sum = 0
for i in range(n):
i += 1
for j in range(i + 1, n):
j += 1
for k in range(j + 1, n):
k += 1
for l in range(k + 1, 10 + k):
l += 1
sum += 1
t1 = time.time()
total = t1-t0
print(total)
# test2(1000)
def test3(n):
def bunnyEars(bunnies):
if bunnies == 0:
return 0
return 2 + bunnyEars(bunnies-1)
t0 = time.time()
print(bunnyEars(n))
t1 = time.time()
total = t1-t0
print(total)
test3(990)
|
6b6b490f63b1be54482cd36444e3c88e5bb461a9
|
NoeNeira/practicaPython
|
/Guia_2/Ejercicio1.py
| 662 | 4.40625 | 4 |
"""
Pedir al usuario que ingrese un mensaje cualquiera, si el mensaje tiene más de 100 caracteres
imprimirlo por pantalla, si tiene entre 50 y 100 caracteres imprimirlo al revés,
si no se cumple ninguna de las opciones anteriores, por pantalla devolver un mensaje que diga
"su mensaje es demasiado corto"
"""
texto = input("Por favor ingrese un texto")
if len(texto) >= 100:
print(texto)
elif 50 <= len(texto) and len(texto) < 100:
print(texto[::-1])
else:
print("Su mensaje es demasiado corto")
# str(a[::-1]))
# Return the slice of the string that starts at the end and steps backward one element at a time
# mensaje[start:stop:step]
|
927edb4da224aa650898b1ab1a5ec4e3557a4f3d
|
xprime480/projects
|
/examples/python/circlepoints.py
| 914 | 4.1875 | 4 |
#!/usr/bin/env python3
"""
Generate and print points on the radius of a circle.
"""
import random
import math
def main(radius, count) :
points = make_points(radius, count)
print (count_quadrant(points))
for x in points :
print (x[0], x[1])
def count_quadrant(points) :
quad = [0,0,0,0]
for x in points :
if x[0] >= 0 :
if x[1] >= 0 :
quad[0] += 1
else:
quad[3] += 1
else :
if x[1] >= 0 :
quad[1] += 1
else :
quad[2] += 1
return quad
def make_points(radius, count) :
points = []
for x in range(count) :
p = make_point(radius)
points.append(p)
return points
def make_point(radius) :
point1d = 2.0 * random.random() * math.pi
return (radius * math.cos(point1d), radius * math.sin(point1d))
main(1000, 1000)
|
7465cde937dd5a02c432c40ac89a58524d18cf05
|
Hyunwoo29/python-oop
|
/encapsulation/calculator-constructor.py
| 728 | 3.796875 | 4 |
def add_fucntion(first, second):
return first + second
def mul_fucntion(first, second):
return first * second
def sub_fucntion(first, second):
return first - second
def div_fucntion(first, second):
return first / second
class Calculator:
def setdata(self, first, second):
self.first = first
self.second = second
def add(self):
return c.first + c.second
def mul(self):
return c.first * c.second
def sub(self):
return c.first - c.second
def div(self):
return c.first / c.second
if __name__ == '__main__':
c = Calculator()
print(add_fucntion(1, 3))
print(mul_fucntion(1, 3))
print(sub_fucntion(1, 3))
print(div_fucntion(1, 3))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.