blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3590d8728084047df0859084113c7281eb208afb | ggm1207/cs | /data-structure/03-list.py | 3,054 | 3.9375 | 4 | import copy
class ArrayList:
def __init__(self, max_list_size):
self.arraylist = [0] * max_list_size
self.length = 0
self.max_list_size = max_list_size
def is_empty(self):
return self.length == 0
def is_full(self):
return self.length == self.max_list_size
def add(self, position, item):
"""
just practice, it's not perfect.
"""
if not self.is_full() and position >= 0 and position < self.max_list_size:
if self.arraylist[position] != 0:
self.arraylist[position + 1 :] = self.arraylist[position:-1]
self.arraylist[position] = item
self.length += 1
else:
raise IndexError("Index Error!")
def delete(self, position):
if position < 0 or position >= self.max_list_size:
raise IndexError("Index Error!")
# for pos in range(position, self.length):
# self.arraylist[pos-1] = self.arraylist[pos]
self.arraylist[position:-1] = self.arraylist[position + 1 :]
self.length -= 1
x = ArrayList(10)
print(x.is_empty())
x.add(3, 4)
x.add(0, 0)
x.add(1, 1)
x.add(2, 2)
print(x.arraylist)
x.add(3, 3)
print(x.arraylist)
x.delete(3)
print(x.arraylist)
print(x.length)
print("ArrayList" + "-" * 20)
class ListNode(object):
def __init__(self, data=None):
self.data = data
self.link = None
def insert_node(head_node, prev_node, new_node):
if head_node.link == None:
head_node.link = new_node
elif prev_node.data == None:
new_node.link = head_node.link
head_node.link = new_node
else:
new_node.link = prev_node.link
prev_node.link = new_node
def delete_node(head_node, prev_node, removed_node):
if prev_node.data == None:
head_node.link = removed_node.link
else:
prev_node.link = removed_node.link
def search_node(head_node, x):
cur_node = head_node
while cur_node.link:
cur_node = cur_node.link
if cur_node.data == x:
print("cur_node's data: {} and id: {}".format(x, id(cur_node)))
def concat_nodes(head1, head2):
if head1.link == None:
return head2
elif head2.link == None:
return head1
else:
p = head1
while p.link:
p = p.link
p.link = head2.link
return head1
def print_node(node):
print(node.data, end=" ")
if not node.link:
return
print_node(node.link)
h_node = ListNode()
node_1 = ListNode(1)
node_2 = ListNode(2)
node_3 = ListNode(3)
node_4 = ListNode(4)
node_5 = ListNode(5)
insert_node(h_node, h_node, node_1)
insert_node(h_node, node_1, node_2)
insert_node(h_node, node_2, node_3)
print_node(h_node)
print()
delete_node(h_node, node_1, node_2)
print_node(h_node)
search_node(h_node, 3)
print(id(node_3))
h2_node = ListNode()
insert_node(h2_node, h2_node, node_4)
insert_node(h2_node, h2_node, node_5)
print_node(h2_node); print()
new_node = concat_nodes(h_node, h2_node)
print_node(new_node); print()
|
b15eac6ee5ff855ee4e5fafc0918f9f659e5751f | Aasthaengg/IBMdataset | /Python_codes/p02392/s632564114.py | 116 | 3.875 | 4 | num1,num2,num3 = map(int,input().split(" "))
if (num1 < num2) and (num2 < num3):
print("Yes")
else:
print("No")
|
9749fc3e081e500d94552438417c80d8ac07baa6 | yuju13488/pyworkspace | /Homework/if_else/if_else3.py | 1,387 | 4.1875 | 4 | #3.選擇性敘述的練習-electricity
#輸入何種用電和度數,計算出需繳之電費。
#電力公司使用累計方式來計算電費,分工業用電及家庭用電。
# 家庭用電 工業用電
#240度(含)以下 0.15元 0.45元
#240~540(含)度 0.25元 0.45元
#540度以上 0.45元 0.45元
elect=input('What kind of electricity, \'home\' or \'industry\':')
kwh=eval(input('Please input kilowatt hour for uesd:'))
if elect == 'industry':
print('Electricity fee is',kwh*0.45)
elif elect == 'home':
if kwh <= 240:
print('Electricity fee is', kwh*0.15)
elif 240 < kwh <= 540:
print('Electricity fee is', 240*0.15+(kwh-240)*0.25)
elif 540 < kwh:
print('Electricity fee is', 240*0.15+300*0.25+(kwh-540)*0.45)
else:
print('輸入錯誤')
# if kwh <= 240 and elect == 'home':
# print('Electricity fee is',kwh*0.15)
# if kwh <= 240 and elect == 'industry':
# print('Electricity fee is',kwh*0.45)
# if 240 < kwh <= 540 and elect == 'home':
# print('Electricity fee is',240*0.15+(kwh-240)*0.25)
# if 240 < kwh <= 540 and elect == 'industry':
# print('Electricity fee is',kwh*0.45)
# if 540 < kwh and elect == 'home':
# print('Electricity fee is',240*0.15+300*0.25+(kwh-540)*0.45)
# if 540 < kwh and elect == 'industry':
# print('Electricity fee is',kwh*0.45) |
7a53229a8525f487b8284925d3d8f040fbed2238 | lnarasimha94/Everest.Engineering.Assignment | /everest_engineering_1_2.py | 5,623 | 3.671875 | 4 | import itertools
def calculateCost(basecost,weight,distance):
return basecost+(weight*10)+(distance * 5)
# Defining main function
def main():
coupons = {
# couponcode, percent, distance, weight
'OFR001':[10,'<200','70-200'],
'OFR002':[7,'50-150','100-250'],
'OFR003':[5,'50-250','10-150']
}
firstLine = input(" ")
base_delivery_cost = float(firstLine.split(" ")[0])
no_of_packges = int(firstLine.split(" ")[1])
package_details = []
package_details_dict= {}
for i in range(no_of_packges):
packageInput = input("")
package_details.append(packageInput.split(" "))
package_details_dict[packageInput.split(" ")[0]] = packageInput.split(" ")
secondLine = input(" ")
no_of_vehicles = int(secondLine.split(" ")[0])
max_speed = int(secondLine.split(" ")[1])
max_load = int(secondLine.split(" ")[2])
final_Resp = {}
print("*****************")
package_names = []
for package in package_details:
package_weight = float(package[1])
package_distance = float(package[2])
package_name = package[0]
package_names.append(package_name)
delivery_cost = calculateCost(base_delivery_cost,package_weight,package_distance)
applied_coupon = package[3].upper()
if applied_coupon in coupons.keys():
coupon_details = coupons[applied_coupon]
weight_check = False
if('-' in coupon_details[2]):
weight_split = coupon_details[2].split('-')
min_weight = float(weight_split[0])
max_weight = float(weight_split[1])
if package_weight >= min_weight and package_weight <= max_weight:
weight_check = True
elif('<' in coupon_details[2]):
max_weight = coupon_details[2].replace('<','')
max_weight = float(max_weight)
if package_weight < max_weight:
weight_check = True
elif('>' in coupon_details[2]):
min_weight = coupon_details[2].replace('>','')
min_weight = ifloatnt(min_weight)
if package_weight > min_weight:
weight_check = True
elif float(coupon_details[2]) == package_weight:
weight_check = True
distance_check = False
if('-' in coupon_details[1]):
dist_split = coupon_details[1].split('-')
min_distance = float(dist_split[0])
max_distance = float(dist_split[1])
if package_distance >= min_distance and package_distance <= max_distance:
distance_check = True
elif('<' in coupon_details[1]):
max_distance = coupon_details[1].replace('<','')
max_distance = float(max_distance)
if package_distance < max_distance:
distance_check = True
elif('>' in coupon_details[1]):
min_distance = coupon_details[1].replace('>','')
min_distance = float(min_distance)
if package_distance > min_distance:
distance_check = True
elif float(coupon_details[1]) == package_distance:
distance_check = True
if(distance_check and weight_check):
delivery_cost = delivery_cost - (delivery_cost/100)*coupon_details[0]
#print(package[0] +":"+str(delivery_cost))
final_Resp[package[0]] = [package[0],coupon_details[0],delivery_cost]
listOfLists = [0] * no_of_vehicles
while(len(package_names) != 0):
combinations = [combination for i in range(len(package_names)+1) for combination in itertools.combinations(package_names, i)]
total_weights = []
combinations_valid = []
max_dist_each_combo = []
for combination in combinations:
sum_weight = 0
max_dist = 0
for pkg in combination:
sum_weight = sum_weight + int(package_details_dict[pkg][1])
if(int(package_details_dict[pkg][1]) > max_dist):
max_dist = int(package_details_dict[pkg][1])
if(max_weight > sum_weight):
total_weights.append(sum_weight)
combinations_valid.append(combination)
max_dist_each_combo.append(max_dist)
max_w_index = total_weights.index(max(total_weights))
print(combinations_valid[max_w_index])
distances_picked = []
for i in combinations_valid[max_w_index]:
distances_picked.append(int(package_details_dict[i][2]))
time_taken_for_total_drive = (max(distances_picked)/max_speed)
try:
#print(time_taken_for_total_drive)
index = listOfLists.index(0)
listOfLists[index] = float("{:.2f}".format(time_taken_for_total_drive*2))
except:
index = listOfLists.index(min(listOfLists))
listOfLists[index] = ( float("{:.2f}".format(time_taken_for_total_drive*2)) )+listOfLists[index]
for ele in combinations_valid[max_w_index]:
if ele in package_names:
package_names.remove(ele)
if(len(package_names) == 0):
listOfLists[index] = listOfLists[index] - time_taken_for_total_drive
print("*****************")
print("Vehicle wise time spent on delivery :"+str(listOfLists))
if __name__=="__main__":
main()
|
94046c10ab86358f623bcab5eb9d740d252a5900 | paulsenj/HearMeCode | /slice3.py | 1,858 | 4.03125 | 4 | #Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays (using input), compare them, print out a message of congratulations to the winner, and ask if the players want to start a new game)
#Remember the rules: Rock beats scissors Scissors beats paper Paper beats rock
def rockpaperscissors():
options = ["rock","paper","scissors"]
player1 = raw_input("Player 1, what do you choose? Rock, paper, or scissors?").lower()
player2 = raw_input("Player 2, what do you choose? Rock, paper, or scissors?").lower()
if player1 in options and player2 in options:
while player1 == "rock":
if player2 == "paper":
print "Player 2 wins! Paper beats rock."
break
elif player2 == "scissors":
print "Player 1 wins! Rock beats scissors."
break
elif player2 == "rock":
print "Try again. You both chose rock."
break
while player1 == "paper":
if player2 == "rock":
print "Player 1 wins! Paper beats rock."
break
elif player2 == "scissors":
print "Player 2 wins! Scissors beats paper."
break
elif player2 == "paper":
print "Try again. You both chose paper."
break
while player1 == "scissors":
if player2 == "rock":
print "Player 2 wins! Rock beats scissors."
break
elif player2 == "paper":
print "Player 1 wins! Scissors beats paper."
break
elif player2 == "scissors":
print "Try again. You both chose scissors."
break
else:
print "Someone chose something other than rock, paper, or scissors. Try again!"
#to play for the first time
play = raw_input("Would you like to play Rock-Paper-Scissors? y/n").lower()
while play == "y":
rockpaperscissors()
play = raw_input("Would you like to play again? y/n").lower()
else:
print "Ok, come back another time."
|
9f88ec90ba7adf2a5f10bcb9867a34d4e9653b98 | muskankapoor/fall2017projects | /Python/PracticePython.py | 4,612 | 3.984375 | 4 | #Excerice 1-11
"""
#basic age and name program
name=input("Enter your name: ")
age=int(input("Enter your age: "))
number=int(input('How many times" '))
year=(100-age)+2017
statement=('Hi ' + str(name) + ' You will turn 100 in ' + str(year) + 'this \n')
print (statement * number)
#another simpler solution
name = input("What is your name: ")
age = int(input("How old are you: "))
year = str((2014 - age)+100)
print(name + " will be 100 years old in the year " + year)
#odd or even program
user=int(input('enter a number: '))
if user%2==0:
print ('even number')
elif user%2==1:
print ('odd number')
check=int(input('ennter a number check: '))
user=int(input('user: '))
if check//user==0:
print ('divides evenly')
elif user%4==0:
print ('divides by four')
import sys
=
str = input("Please enter an integer: ")
num = int(float(str)) # force the input to an int
# Part the first
if num % 2 == 0:
print ('Your number is even.')
else:
print ('Your number is odd.')
if num % 4 == 0:
print ('Your number is a multiple of 4.')
str1 = input("\nPlease enter an integer numerator: ")
str2 = input("Please enter an integer denominator: ")
numerator = int(float(str1))
denominator = int(float(str2))
if denominator == 0:
print ('Cannot accept zero divisor. Exiting.')
sys.exit()
else:
if numerator % denominator == 0:
print ("{} divides evenly into {}".format(denominator, numerator))
else:
print ("{} does not divide evenly into {}".format(denominator, numerator))
#list less than 10 list
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
new_list = []
for i in a:
if i < 5:
new_list.append(i)
print (new_list)
#divisors
newlist=[]
user=int(input())
for i in range(1, user+1):
if user%i==0:
newlist.append(i)
print (newlist)
#common values in two lists
import random
list1 = random.sample(range(20), 13)
list2 = random.sample(range(20), 17)
newlist=[] #newlist
print ("Random List 1:", list1)
print ("Random List 2:" ,list2, "\n")
if len(list1)>len(list2):
for i in list1:
if i in list2:
newlist.append(i)
elif len(list2)>len(list1):
for i in list2:
if i in list1:
newlist.append(i)
print (newlist)
#palindrome is a string that reads the same forwards and backward
def palindrome(str):
str=str.lower()
if str[:]==str[::-1]:
return 'is a palindrome'
else:
return 'not a palindrome'
print (palindrome('Dad'))
print (palindrome('wassup'))
#list comphrehension
def comphrenshion(list):
b = [number for number in list if number % 2 == 0]
return (b)
print (comphrenshion([1, 2, 4, 7, 9]))
#another solution
import random
numlist = []
list_length = random.randint(5,15) #returns a random integer
while len(numlist) < list_length:
numlist.append(random.randint(1,75))
evenlist = [number for number in numlist if number % 2 == 0]
print(numlist)
print(evenlist)"
#rock paper and sccisors
user1 = input("What's your name?")
user2 = input("And your name?")
user1_answer = input("%s, do yo want to choose rock, paper or scissors?" % user1)
user2_answer = input("%s, do you want to choose rock, paper or scissors?" % user2)
def compare(u1, u2):
if u1 == u2:
return("It's a tie!")
elif u1 == 'rock':
if u2 == 'scissors':
return("Rock wins!")
else:
return("Paper wins!")
elif u1 == 'scissors':
if u2 == 'paper':
return("Scissors win!")
else:
return("Rock wins!")
elif u1 == 'paper':
if u2 == 'rock':
return("Paper wins!")
else:
return("Scissors win!")
else:
return("Invalid input! You have not entered rock, paper or scissors, try again.")
sys.exit()
print(compare(user1_answer, user2_answer))
#import random module
import random
count=1
number=random.randint(1, 9)
while (count<=5):
user=int(input())
if user<number:
print ('guess is too low')
count=count+1
elif user>number:
print ('guess is too high')
count=count+1
elif user==number:
count=count+1
print ('You got it right in', count, 'guesses')
break
#list overlap
import random
a = random.sample(range(1,50),10)
b = random.sample(range(1,50),10)
common = [i for i in a if i in b]
print(common)"""
#check primality
usernum = int(input("Please input a number: ")) #3
divisors = ([i for i in range(2,usernum) if(usernum%i == 0)]) #(2, 3)
if(len(divisors)>0):
print("Your number is not a prime.")
else:
print("Your number is a prime.") |
f59a3697c26db6e993f271da1e09290d55744b93 | SteveGledsGames/morsels | /count_words/count.py | 874 | 4.0625 | 4 | def count_words(sentence):
words = sentence.split()
words = [word.lower() for word in words]
word_count = {}
for word in words:
if word_count.get(word):
word_count[word] = word_count[word] + 1
else:
word_count[word] = 1
return word_count
print(count_words("oh what a day What a lovely day"))
# {'oh': 1, 'what': 2, 'a': 2, 'day': 2, 'lovely': 1}
print(count_words("don't stop believing"))
# {"don't": 1, 'stop': 1, 'believing': 1}
# As a bonus, make sure your function works well with mixed case words:
# >>> count_words("Oh what a day what a lovely day")
# {'oh': 1, 'what': 2, 'a': 2, 'day': 2, 'lovely': 1}
# For even more of a bonus try to get your function to ignore punctuation outside of words:
# >>> count_words("Oh what a day, what a lovely day!")
# {'oh': 1, 'what': 2, 'a': 2, 'day': 2, 'lovely': 1} |
56c8f763b16f44024d74aa28c4e711d5265a8096 | swaroop1995/assignment | /ass2_13.py | 189 | 4.03125 | 4 | no1=int(input("enter the no1:"))
no2=int(input("enter the no2:"))
if no1==no2:
sum=2*(no1+no2)
print("the sum is",sum)
else:
total=no1+no2
print("the sum is",total)
|
0211a144d82d5cdc4cedd6e09ad8bdc082755f8e | Sum-Sovann2018/Bootamp4 | /03_vote.py | 211 | 4.15625 | 4 | A = int(input("Input your age:"))
if A >= 18:
print("You are eligible to vote")
elif A>=0 and A < 18:
print("You aren't adult yet...Sorry can't vote")
else:
print("Age must be a positive digit")
|
fb5fe3775b73b79dd1ec2ac0bc74a5f0b04591c7 | Jhynn/programming-concepts-and-logic | /solutions/2nd-conditionals/l2_a9.py | 759 | 4.1875 | 4 | number_1 = float(input('Type a number: '))
number_2 = float(input('Type another one: '))
number_3 = float(input('Type the last one, please: '))
if number_1 > number_2 and number_1 > number_3:
if number_2 > number_3:
print(f'{number_1} + {number_2} = {number_1 + number_2}')
else:
print(f'{number_1} + {number_3} = {number_1 + number_3}')
elif number_2 > number_3 and number_2 > number_1:
if number_1 > number_3:
print(f'{number_2} + {number_1} = {number_2 + number_1}')
else:
print(f'{number_2} + {number_3} = {number_3 + number_2}')
else:
if number_1 > number_2:
print(f'{number_3} + {number_1} = {number_3 + number_1}')
else:
print(f'{number_3} + {number_2} = {number_2 + number_3}')
|
e4e48058908a2009bcf8bc9175ca333e7550ee2c | imharsh94/ALGO-DS | /dil.py | 68 | 3.59375 | 4 | a = "hello boy"
print(a)
if 5>1:
print('there is no great guy')
|
dc75b93746c342c40c66f71fb16afdcdeeed4e3d | xiang-123352/code_snippets | /python/beispiele/07_Basistypen/_08_functions.py | 842 | 3.875 | 4 | # -*- coding: utf-8 -*-
# Funtionen von Sequenzen
string = "Wie lang bin ich wohl?"
print(len(string))
# Anzahl der Elemente
zahl = len(["Hallo", 5, 2, 3, "Welt"])
print(zahl)
# min und max
L = [5,1,10,-9.5,12,-5]
print(max(L))
print(min(L))
# Fehler
#l = [1,2, "welt"]
#print( min(l) )
# Geht auch bei Strings
print( max("Wer gewinnt wohl"))
print( min("Zeichenkett"))
# Position (index)
ziffern = [1, 2, 3, 4, 5, 6, 7, 8, 9]
zahl = ziffern.index(3)
print(zahl)
# Geht auch bei String
s = "Hallo Welt"
foundAt = s.index("l")
print(foundAt)
# Mit Parameter Start-Ende
ziffer = [1, 22, 333, 4444, 333, 22, 1].index(1, 3, 7)
# Suche 1 zwischen block 3 und 7
# ab 333 ( index4 )
print(ziffer)
zahl = "Hallo Welt".index("l", 5, 100)
# hinter Hallo
print(zahl)
# Anzahl mit count
s = [1, 2, 2, 3, 2]
print(s.count(2))
print("Hallo Welt".count("l"))
|
0e8ea8fa78d83a94c4af9fd365e6516d291b155f | KunyiLiu/algorithm_problems | /kunyi/Tree/binary_tree_postorder.py | 2,409 | 3.921875 | 4 | # Push the root node to the first stack.
# Pop a node from the first stack, and push it to the second stack.
# Then push its left child followed by its right child to the first stack.
# Repeat step 2) and 3) until the first stack is empty.
# Once done, the second stack would have all the nodes ready to be traversed in post-order. Pop off the nodes from the second stack one by one and you’re done.
class Solution:
"""
@param: root: A Tree
@return: Postorder in ArrayList which contains node values.
"""
def postorderTraversal(self, root):
# write your code here
result = []
stack = []
rev_stack = []
if root is None:
return result
stack.append(root)
while len(stack) > 0:
node = stack.pop()
rev_stack.append(node)
if node.left is not None:
stack.append(node.left)
if node.right is not None:
stack.append(node.right)
while len(rev_stack) > 0:
node = rev_stack.pop()
result.append(node.val)
return result
######### reverse of root right left, similar to preorder###############
class Solution:
"""
@param root: A Tree
@return: Postorder in ArrayList which contains node values.
"""
def postorderTraversal(self, root):
# reserve - root right left
current = root
result, stack, reverse_result = [], [], []
while len(stack) > 0 or current is not None:
if current:
reverse_result.append(current.val)
stack.append(current)
current = current.right
else:
current = stack.pop()
current = current.left
return reverse_result[::-1]
#############3 recursion ###################
class Solution:
"""
@param root: A Tree
@return: Postorder in ArrayList which contains node values.
"""
def postorderTraversal(self, root):
# reserve - root right left
result = []
self.helper(root, result)
return result
def helper(self, root, result):
# traverse top down
if root is None:
return
self.helper(root.left, result)
self.helper(root.right, result)
result.append(root.val)
return
|
a278b8f0ce88e9865705c0970264885a0f641cf3 | vijayb5hyd/class_notes | /class_snake.py | 346 | 4.03125 | 4 | class Snake:
"""This class allows you to create objects of type snake."""
def __init__(self,name):
self.name=name
def change_name(self,new_name):
self.name=new_name
snake1=Snake("Python")
snake2=Snake("Black Mamba")
print(snake1.name)
print(snake2.name)
snake1.change_name("Anaconda")
print(snake1.name)
print(Snake.__doc__) |
b1b89bc07bf2a928d1897e1a3605c1f36b0924aa | lakshyatyagi24/daily-coding-problems | /python/345.py | 3,035 | 3.953125 | 4 | # --------------------------
# Author: Tuan Nguyen
# Date created: 20200422
#!345.py
# --------------------------
"""
You are given a set of synonyms, such as (big, large) and (eat, consume).
Using this set, determine if two sentences with the same number of words are equivalent.
For example, the following two sentences are equivalent:
* "He wants to eat food."
* "He wants to consume food."
Note that the synonyms (a, b) and (a, c) do not necessarily imply (b, c):
consider the case of (coach, bus) and (coach, teacher).
Follow-up: what if we can assume that (a, b) and (a, c) do in fact imply (b, c)?
"""
def check_equivalent_sentences(sentence_1, sentence_2, synonyms):
""" Returns True if sentence_1 is equivalent with sentence_2 w.r.t pair of synonyms """
words_1, n1 = split_sentence_into_words(sentence_1)
words_2, n2 = split_sentence_into_words(sentence_2)
if n1 != n2: # there must be words without equivalence
return False
equivalence_map = build_equivalence_map(synonyms)
for i in range(n1):
if not check_equivalent_words(words_1[i], words_2[i], equivalence_map):
return False
return True
def split_sentence_into_words(sentence):
import re
sentence = re.sub(r"[^\w\s]", "", sentence) # remove punctuation from sentence
words = sentence.split(" ")
return words, len(words)
def check_equivalent_words(word_1, word_2, equivalence_map):
if word_1 == word_2: # the same word at same position in 2 sentence
return True
if word_1 not in equivalence_map.keys() or word_2 not in equivalence_map.keys():
return False
word_1_equals = equivalence_map[word_1]
word_2_equals = equivalence_map[word_2]
if word_1 not in word_2_equals or word_2 not in word_1_equals:
return False
return True
def build_equivalence_map(synonyms):
equivalence_map = initialize_equivalence_map(synonyms)
for pair in synonyms:
a, b = pair[0], pair[1]
equivalence_map[a].append(b)
equivalence_map[b].append(a)
return equivalence_map
def initialize_equivalence_map(synonyms):
equivalence_map = {}
for pair in synonyms:
a, b = pair[0], pair[1]
equivalence_map[a] = []
equivalence_map[b] = []
return equivalence_map
# ----- Unit Tests -----
def test1():
sentence_1 = "He wants to eat food."
sentence_2 = "He wants to consume food."
synonyms = [("eat", "consume")]
assert check_equivalent_sentences(sentence_1, sentence_2, synonyms) == True
def test2():
sentence_1 = "Tom eats a big hamburger."
sentence_2 = "Tom eats a large hamburger."
synonyms = [("big", "large")]
assert check_equivalent_sentences(sentence_1, sentence_2, synonyms) == True
def test3():
sentence_1 = "Jimmy goes to supermarket."
sentence_2 = "Jimmy goes to work."
synonyms = [("supermarket", "mall")]
assert check_equivalent_sentences(sentence_1, sentence_2, synonyms) == False
if __name__ == "__main__":
test1()
test2()
test3() |
c1a10e3466b1199aa2a50c481b456465f87d9561 | Esdeaz/Python_Course | /Lab5_Ex2_Variant_3.py | 695 | 3.515625 | 4 | import re
f = open('students.txt', 'r', encoding = "UTF-8")
list_st = f.readlines()
f.close()
list_form = []
for el in list_st:
list_form.append(re.split(r'\s+', re.sub(r'[;.,\-!?]', ' ', el).strip()))
for list_a in list_form:
for el in list_a:
if el.endswith('111'):
print('БО-111111: ', end = '')
for elem in list_a:
if elem != '111111' and not elem.endswith('О'):
print(elem, ' ', end = '')
if el.endswith('222'):
print('БО-222222: ', end = '')
for elem in list_a:
if elem != '222222' and not elem.endswith('О'):
print(elem, ' ', end = '') |
231a6035e9bb1945d684e0fee2a3a1c7660dbbcb | Shubhrita/Hackerrank | /Code2.py | 809 | 3.78125 | 4 | # Finding duplicate elements in an array
# Importing required libraries
from __future__ import print_function
import sys
# Taking input line by line
inp=[]
raw=0
while raw != '':
try:
raw = raw_input()
inp.append(raw)
except (EOFError):
break #end of file reached
# Function to find duplicate in an array
def find_dup(arr):
dup=[]
new_list=[]
for r in arr:
if r not in new_list:
new_list.append(r)
else:
dup.append(r)
return dup
# Passing array to function to find duplicates
for i in range(int(inp[0])):
passed = inp[2].split(' ')
result = find_dup(passed)
if result != []:
for r in result:
print(r,file=sys.stdout)
else:
print(-1,file=sys.stdout)
|
c5fb5b5db5222e4bc780a65badba24b837498136 | towzeur/momDl | /v1 Work/test.py | 1,779 | 3.5625 | 4 | # import the Beautiful soup functions to parse the data returned from the website
from bs4 import BeautifulSoup
# import the library used to query a website
import urllib.request as urllib2
# 1 Revolution
# Regret & Loss 1
url = "http://milesofmusik.com/music_catalog/album-156591"
# Query the website and return the html to the variable 'page'
page = urllib2.urlopen(url)
# Parse the html in the 'page' variable, and store it in Beautiful Soup format
soup = BeautifulSoup(page, "lxml")
print(soup.prettify())
# tr-156581
# storage/tracks/1RM/015/1RM-015_01 Fading Hopes Full.mp3
# storage/tracks/1RM/015/1RM-015_03 Fading Hopes No Harp.mp3
# storage/tracks/1RM/015/1RM-015_63 Dearly Departed No Str.mp3
# storage/tracks/1M1/014/1M1-014_01 World Stage.mp3
alb = "1M1",
albNum = "014",
trackNum = "01",
trackName = "World Stage"
format0 = "storage/tracks/{alb}/{albNum}/{alb}-{albNum}_{trackNum} {trackName}.mp3".format(alb="1M1",
albNum="014",
trackNum="01",
trackName="World Stage")
print(format0)
# soup.mom-table-header
'''
# soup.find()
content = soup.find(id='content-content')
# print(content)
albumTitle = soup.findAll("div", {"class": "mom-table-header"})[0].string[6:]
# print(albumTitle)
# on s'interesse maintenant au tableau
table = soup.find('table', attrs={'class': 'sticky-enabled'})
# print(table)
tableBody = table.find('tbody')
rows = tableBody.find_all('tr')'''
if __name__ == '__main___':
pass
url = "http://milesofmusik.com/music_catalog/album-156591/#tr-156581"
|
e670975b09813e7958fccb6325a15acf12e64098 | drtamermansour/chickenAnn | /scripts/distance3.py | 316 | 3.890625 | 4 | #!/usr/bin/env python
# -*- coding=utf-8 -*-
import sys
import Levenshtein
if __name__ == '__main__':
if len(sys.argv) != 3:
print 'Usage: You have to enter a source_word and a target_word'
sys.exit(-1)
source, target = sys.argv[1], sys.argv[2]
print Levenshtein.distance(source, target)
|
f2f33d660a0217a6c2f54e1075bafd57ad0c5181 | kbuzby/euler | /euler10.py | 129 | 3.625 | 4 | primes = 5
for x in range (5,2000000,2):
for y in range(2,x):
if x%y==0:
break
else:
primes = primes + x
print primes
|
86ca90fd31a09060144e0a06bf68b5423967344f | rootrUW/Python210-W19 | /students/KevinCavanaugh/session3/list_lab.py | 1,668 | 4.1875 | 4 | #!/usr/bin/env python3
# ----------------------------------------------------------------------- #
# Title: List_Lab
# Author: Kevin Cavanaugh
# Change Log: (Who,What,When)
# kcavanau, created document & completed assignment, 01/29/2019
# ----------------------------------------------------------------------- #
import sys
# --- Series 1 --- #
fruits = ['Apples', 'Pears', 'Oranges', 'Peaches']
print('\n'.join(fruits))
new_fruit = input('add fruit to list: ').title()
fruits.append(new_fruit)
print('\n'.join(fruits))
n = int(input('Index number of fruit you would like to view: '))
print(fruits[n - 1])
new_fruit = input('add fruit to list: ').title()
fruits = [new_fruit] + fruits
print('\n'.join(fruits))
new_fruit = input('add fruit to list: ').title()
fruits.insert(0, new_fruit)
print('\n'.join(fruits))
for i in fruits:
if i[0] == "P":
print(i)
# # # --- Series 2 --- #
print('\n'.join(fruits))
del fruits[-1]
print('\n'.join(fruits))
remove_fruit = input('fruit to remove from list: ')
fruits.remove(remove_fruit.title())
print('\n'.join(fruits))
# # --- Series 3 --- #
for fruit in fruits:
do_i_like = input('Do you like {}?'.format(fruit.lower()))
do_i_like = do_i_like.lower()
while True:
if do_i_like == 'yes':
pass
elif do_i_like == 'no':
fruits.remove(fruit.title())
else:
do_i_like = input('Please input "yes" or "no".')
break
print('\n'.join(fruits))
# --- Series 4 --- #
fruits_reversed = list()
for fruit in fruits:
fruit_reversed = fruit[::-1]
fruits_reversed.append(fruit_reversed.title())
print(fruits_reversed)
print(fruits)
|
f8c76da03421568515886bc5f0bf915383e8b1d2 | jeffreyegan/MachineLearning | /03_Classification/Lesson_4_K_Nearest_Neighbor_Regression.py | 9,476 | 4.65625 | 5 | '''
Regression
The K-Nearest Neighbors algorithm is a powerful supervised machine learning algorithm typically used for classification. However, it can also perform regression.
In this lesson, we will use the movie dataset that was used in the K-Nearest Neighbors classifier lesson. However, instead of classifying a new movie as either good or bad, we are now going to predict its IMDb rating as a real number.
This process is almost identical to classification, except for the final step. Once again, we are going to find the k nearest neighbors of the new movie by using the distance formula. However, instead of counting the number of good and bad neighbors, the regressor averages their IMDb ratings.
For example, if the three nearest neighbors to an unrated movie have ratings of 5.0, 9.2, and 6.8, then we could predict that this new movie will have a rating of 7.0.
1.
We've imported most of the K-Nearest Neighbor algorithm. Before we dive into finishing the regressor, let's refresh ourselves with the data.
At the bottom of your code, print movie_dataset["Life of Pi"]. You should see a list of three values. These values are the normalized values for the movie's budget, runtime, and release year.
2.
Print the rating for "Life of Pi". This can be found in movie_ratings.
3.
We've included the majority of the K-Nearest Neighbor algorithm in the predict() function. Right now, the variable neighbors stores a list of [distance, title] pairs.
Loop through every neighbor and find its rating in movie_ratings. Add those ratings together and return that sum divided by the total number of neighbors.
4.
Call predict with the following parameters:
[0.016, 0.300, 1.022]
movie_dataset
movie_ratings
5
Print the result.
Note that the list [0.016, 0.300, 1.022] is the normalized budget, runtime, and year of the movie Incredibles 2! The normalized year is larger than 1 because our training set only had movies that were released between 1927 and 2016 — Incredibles 2 was released in 2018.
'''
from movies import movie_dataset, movie_ratings
def distance(movie1, movie2):
squared_difference = 0
for i in range(len(movie1)):
squared_difference += (movie1[i] - movie2[i]) ** 2
final_distance = squared_difference ** 0.5
return final_distance
def predict(unknown, dataset, movie_ratings, k):
distances = []
# Looping through all points in the dataset
for title in dataset:
movie = dataset[title]
distance_to_point = distance(movie, unknown)
# Adding the distance and point associated with that distance
distances.append([distance_to_point, title])
distances.sort()
# Taking only the k closest points
neighbors = distances[0:k]
total = 0
for neighbor in neighbors:
title = neighbor[1]
total += movie_ratings[title]
return total / len(neighbors)
print(movie_dataset["Life of Pi"]) # [0.00982356711895032, 0.30716723549488056, 0.9550561797752809]
print(movie_ratings["Life of Pi"]) # 8.0
print(predict([0.016, 0.300, 1.022], movie_dataset, movie_ratings, 5)) # 6.86
'''
Weighted Regression
We're off to a good start, but we can be even more clever in the way that we compute the average. We can compute a weighted average based on how close each neighbor is.
Let's say we're trying to predict the rating of movie X and we've found its three nearest neighbors. Consider the following table:
Movie Rating Distance to movie X
A 5.0 3.2
B 6.8 11.5
C 9.0 1.1
If we find the mean, the predicted rating for X would be 6.93. However, movie X is most similar to movie C, so movie C's rating should be more important when computing the average. Using a weighted average, we can find movie X's rating:
The numerator is the sum of every rating divided by their respective distances. The denominator is the sum of one over every distance. Even though the ratings are the same as before, the weighted average has now gone up to 7.9.
1.
Let's redo our predict() function so it computes the weighted average.
Before you begin looping through the neighbors, create a variable named numerator and set it to 0. Loop through every neighbor and add the neighbor's rating (found in movie_ratings) divided by the neighbor's distance to numerator.
For now, return numerator.
2.
Let's now calculate the denominator of the weighted average. Before your loop, create a variable named denominator and set it equal to 0.
Inside your for loop, add 1 divided by the neighbor's distance to denominator.
Outside the loop, return numerator/denominator.
3.
Once again call your predict function using Incredibles 2's features. Those features were [0.016, 0.300, 1.022]. Set k = 5. Print the results.
How did using a weighted average change the predicted rating? Remember, before calculating the weighted average the prediction was 6.86.
'''
from movies import movie_dataset, movie_ratings
def distance(movie1, movie2):
squared_difference = 0
for i in range(len(movie1)):
squared_difference += (movie1[i] - movie2[i]) ** 2
final_distance = squared_difference ** 0.5
return final_distance
def predict(unknown, dataset, movie_ratings, k):
distances = []
# Looping through all points in the dataset
for title in dataset:
movie = dataset[title]
distance_to_point = distance(movie, unknown)
# Adding the distance and point associated with that distance
distances.append([distance_to_point, title])
distances.sort()
# Taking only the k closest points
neighbors = distances[0:k]
numerator = 0
denominator = 0
for neighbor in neighbors:
title = neighbor[1]
numerator += movie_ratings[title] / neighbor[0]
denominator += 1 / neighbor[0]
return numerator / denominator
print(predict([0.016, 0.300, 1.022], movie_dataset, movie_ratings, 5)) # 6.84913967844
'''
Scikit-learn
Now that you've written your own K-Nearest Neighbor regression model, let's take a look at scikit-learn's implementation. The KNeighborsRegressor class is very similar to KNeighborsClassifier.
We first need to create the regressor. We can use the parameter n_neighbors to define our value for k.
We can also choose whether or not to use a weighted average using the parameter weights. If weights equals "uniform", all neighbors will be considered equally in the average. If weights equals "distance", then a weighted average is used.
classifier = KNeighborsRegressor(n_neighbors = 3, weights = "distance")
Next, we need to fit the model to our training data using the .fit() method. .fit() takes two parameters. The first is a list of points, and the second is a list of values associated with those points.
training_points = [
[0.5, 0.2, 0.1],
[0.9, 0.7, 0.3],
[0.4, 0.5, 0.7]
]
training_labels = [5.0, 6.8, 9.0]
classifier.fit(training_points, training_labels)
Finally, we can make predictions on new data points using the .predict() method. .predict() takes a list of points and returns a list of predictions for those points.
unknown_points = [
[0.2, 0.1, 0.7],
[0.4, 0.7, 0.6],
[0.5, 0.8, 0.1]
]
guesses = classifier.predict(unknown_points)
1.
Create a KNeighborsRegressor named regressor where n_neighbors = 5 and weights = "distance".
2.
We've also imported some movie data. Train your classifier using movie_dataset as the training points and movie_ratings as the training values.
3.
Let's predict some movie ratings. Predict the ratings for the following movies:
[0.016, 0.300, 1.022],
[0.0004092981, 0.283, 1.0112],
[0.00687649, 0.235, 1.0112].
These three lists are the features for Incredibles 2, The Big Sick, and The Greatest Showman. Those three numbers associated with a movie are the normalized budget, runtime, and year of release.
Print the predictions!
'''
from movies import movie_dataset, movie_ratings
from sklearn.neighbors import KNeighborsRegressor
regressor = KNeighborsRegressor(n_neighbors = 5, weights = 'distance')
regressor.fit(movie_dataset, movie_ratings)
unk_data = [[0.016, 0.300, 1.022], [0.0004092981, 0.283, 1.0112], [0.00687649, 0.235, 1.0112]]
guesses = regressor.predict(unk_data)
print(guesses) # [ 6.84913968 5.47572913 6.91067999]
'''
Review
Great work! Here are some of the major takeaways from this lesson:
The K-Nearest Neighbor algorithm can be used for regression. Rather than returning a classification, it returns a number.
By using a weighted average, data points that are extremely similar to the input point will have more of a say in the final result.
scikit-learn has an implementation of a K-Nearest Neighbor regressor named KNeighborsRegressor.
In the browser, you'll find an example of a K-Nearest Neighbor regressor in action. Instead of the training data coming from IMDb ratings, you can create the training data yourself! Rate the movies that you have seen. Once you've rated more than k movies, a K-Nearest Neighbor regressor will train on those ratings. It will then make predictions for every movie that you haven't seen.
As you add more and more ratings, the predictor should become more accurate. After all, the regressor needs information from the user in order to make personalized recommendations. As a result, the system is somewhat useless to brand new users — it takes some time for the system to "warm up" and get enough data about a user. This conundrum is an example of the cold start problem.
'''
|
348d21a438a800b502932d1febdf0cda06a6b5f0 | haoccheng/pegasus | /leetcode/remove_element.py | 670 | 3.578125 | 4 | # Given an array and a value, remove all instances of that value in place
# and return the new length.
# The order of elements can be changed.
def remove_elements(nums, val):
if len(nums) == 0:
return 0
x = 0
y = len(nums) - 1
while (x < y):
if nums[y] == val:
y -= 1
elif nums[x] == val:
nums[x] = nums[y]
x += 1
y -= 1
else:
x += 1
if nums[x] == val:
x -= 1
return min(y+1, x+1)
input = [1, 1, 1, 1]
print remove_elements(input, 1), input
input = [1, 2, 1, 2]
print remove_elements(input, 1), input
input = [4, 5]
print remove_elements(input, 4), input
input = [1]
print remove_elements(input, 1), input
|
7d5a54d78175decf6bee32146ed26ab6ca688913 | QiuZiXian/python-learning-process | /extend_work/six/julia.py | 454 | 3.515625 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = 'QiuZiXian' http://blog.csdn.net/qqzhuimengren/ 1467288927@qq.com
# @time :2020/9/8 19:46
# @abstract :
for i: # 循环 i次
A = rand([1, 2, 3], 3, 3) # 随机生成矩阵
value = det(A)
if value != 0: # 判断det不等于0
print(A)
def test(x):
return x%2
for i in range(100): # 循环100次
value = test(i)
if value == 0:
print(i) # 输出所有的偶数
|
07fbe8e136b0a55defec00e1a2abffff61b63900 | kshitij-aggarwal/Artificial-Intelligence-Pacman | /Multi-Agent Search/Final.py | 3,326 | 3.703125 | 4 | #The structure has an array with which it has a state, the next move
class game():
def term(self,state,p):
if ((state[0] == state[1] == state[2])
or (state[3] == state[4] == state[5] == p)
or (state[6] == state[7] == state[8] == p)
or (state[0] == state[3] == state[6] == p)
or (state[1] == state[4] == state[7] == p)
or (state[2] == state[5] == state[8] == p)
or (state[0] == state[4] == state[8] == p)
or (state[2] == state[4] == state[6] == p)):
return True
return False
def blanks(self,state):
blank=[]
for b in state:
if b != "X" and b != "O":
blank.append(b)
return blank
def utility(self,state):
if self.term(state,"X"):
return 1
elif self.term(state,"O"):
return -1
elif len(self.blanks(state)) == 0:
return 0
else:
return None
def minimax(self,board,p):
currentblanks = self.blanks(board)
if self.term(board,"X"):
return 1
elif self.term(board,"O"):
return -1
elif (len(currentblanks) ==0):
return 0
currentmoves = []
for i in currentblanks:
board[i] = p
if p == "X":
result = self.minimax(board,"O")
else:
result = self.minimax(board,"X")
board[i] = i
currentmoves.append((i,result))
bmove = -1
if p == "X":
bscore = -1000
for i in range(0,len(currentmoves)):
if currentmoves[i][1] > bscore:
bscore = currentmoves[i][1]
bmove = i
else:
bscore = 1000
for i in range(0,len(currentmoves)):
if currentmoves[i][1] < bscore:
bscore = currentmoves[i][1]
bmove = i
print "Move for: %s"%p
print currentmoves
return currentmoves[bmove][1]
if __name__ == '__main__':
newgame = game()
board_state = (["O","O","X","X",4,"O",6,7,"X"]) #Question d, consistent with the tree in the assignment also show utility as 1 for question e
print board_state
print newgame.minimax(board_state,"X")
#board_state = [i for i in range (0,9)] #Intial state
#board_state = ([0,1,2,3,4,5,6,7,"X"]) # question e, draw
#print board_state
#print newgame.minimax(board_state,"O")
#board_state = (["O",1,2,3,4,5,6,7,"X"]) # question e, Max
#print board_state
#print newgame.minimax(board_state,"X")
#board_state = (["O",1,2,"X",4,5,6,7,"X"]) # question e, draw
#print board_state
#print newgame.minimax(board_state,"O")
#board_state = (["O","O",2,"X",4,5,6,7,"X"]) # question e, max
#print board_state
#print newgame.minimax(board_state,"X")
#board_state = (["O","O","X","X",4,5,6,7,"X"]) # question e, max
#print board_state
#print newgame.minimax(board_state,"O")
#board_state = (["O","O","X","X",4,5,6,7,"X"]) # question e, none utility
#print board_state
#print newgame.utility(board_state)
|
5793d56dcb33db6a73f91e3679011309f4fa8708 | mhdz9/python_exercises | /List2.py | 331 | 3.578125 | 4 | zoo_animals = ['elephant', 'zebra', 'tiger', 'lion']
zoo_animals.append('cheetah')
print len(zoo_animals)
print zoo_animals
#zoo_animals.insert(zoo_animals.index('lion'),'giraffe')
for i in zoo_animals:
if i == 'lion':
zoo_animals[zoo_animals.index('lion')] = 'giraffe'
zoo_animals.remove('zebra')
print zoo_animals |
3e7de1ae3e11579c98cc36fe963454b8668817c7 | georgebzhang/Python_LeetCode | /77_combinations_2.py | 578 | 3.75 | 4 | class Solution(object):
def combine(self, n, k):
def backtrack(num=1, comb=[]):
if len(comb) == k:
result.append(comb[:])
for i in range(num, n+1):
comb.append(i)
backtrack(i+1, comb)
comb.pop()
result = []
backtrack()
return result
def print_answer(self, ans):
print(ans)
def test(self):
n, k = 4, 2
ans = self.combine(n, k)
self.print_answer(ans)
if __name__ == '__main__':
s = Solution()
s.test()
|
d10435b9850aa230aecbcff4de649d1797df65e1 | camagar/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/100-weight_average.py | 221 | 3.5 | 4 | #!/usr/bin/python3
def weight_average(my_list=[]):
if my_list is None or len(my_list) == 0:
return 0
suma = sum(i[0] * i[1] for i in my_list)
suma2 = sum(j[1] for j in my_list)
return (suma/suma2)
|
a8c91bf3e62418323b8c5d8850881b904689e222 | can1ball/minimum-path | /src/Search.py | 2,037 | 3.546875 | 4 | from Graph import Node, Graph
from Utils import add_to_open
def astar_search(graph, heuristics, src, dest):
open = []
explored = []
# Create the start node and the goal node
start = Node(src, None)
goal = Node(dest, None)
# Add the first node to the open list
open.append(start)
# Loop until the list is empty
while len(open) > 0:
# Keep the list sorted so we extract only the smallest element
open.sort()
# Get the node with the lowest cost
current_node = open.pop(0)
# Add the current node to the explored nodes list
explored.append(current_node)
# Check if the current node is the goal node
# If we reached the goal, return the path
if current_node == goal:
# Store the path from destination node to the source node
path = []
while current_node != start:
path.append(current_node.name)
current_node = current_node.parent
path.append(src)
# Return reversed path
return path[::-1]
# Get neighbors
neighbors = graph.get(current_node.name)
# Loop through neighbors
for key, value in neighbors.items():
# Create a neighbor node
neighbor = Node(key, current_node)
# Check if the neighbor is in the closed list
if(neighbor in explored):
continue
# Calculate full path cost
neighbor.g = current_node.g + graph.get(current_node.name, neighbor.name)
neighbor.h = heuristics[neighbor.name]
neighbor.f = neighbor.g + neighbor.h
# Check if neighbor is in open list and if it has a lower f value
if(add_to_open(open, neighbor) == True):
# Everything is green, add neighbor to open list
open.append(neighbor)
# Return None if no path is found
return None |
ed0e4eba20272ed9dc4833de2498701709f596f1 | shinws9090/pythonProject | /35.클래스활용/3.클래스메서드.py | 798 | 3.828125 | 4 | class Calc:
__count = 0
def __init__(self):
Calc.__count += 1
@classmethod
def print_count(cls): # 스테틱메서드
print("{}번 생성됨".format(cls.__count))
a = Calc()
b = Calc()
n = Calc()
d = Calc()
f = Calc()
Calc.print_count()
class User:
def __init__(self, email, password):
self.email = email
self.password = password
@classmethod
def fromTuple(cls, tup):
return cls(tup[0], tup[1]) # 클래스 생성자를 불러와서 인스턴스 생성
@classmethod
def fromDictionary(cls, dic):
return cls(dic["email"], dic["password"])
user1 = User("user@test1.com", "1234")
user2 = User.fromTuple(("user@test2.com", "1234"))
user3 = User.fromDictionary({"email": "user@test3.com", "password": "1234"})
|
030d1280ca46eab0519a15100efa3f66a953fe48 | axefx/Data-Structures | /queue/queue.py | 3,524 | 4.4375 | 4 | """
A queue is a data structure whose primary purpose is to store and
return elements in First In First Out order.
1. Implement the Queue class using an array as the underlying storage structure.
Make sure the Queue tests pass.
2. Re-implement the Queue class, this time using the linked list implementation
as the underlying storage structure.
Make sure the Queue tests pass.
3. What is the difference between using an array vs. a linked list when
implementing a Queue?
Stretch: What if you could only use instances of your Stack class to implement the Queue?
What would that look like? How many Stacks would you need? Try it!
"""
class Queue:
def __init__(self):
self.size = 0
self.storage = []
def __len__(self):
return self.size
def enqueue(self, value):
self.storage.append(value)
self.size+=1
def dequeue(self):
if self.size == 0:
return None
self.size-=1
return self.storage.pop(0)
if __name__ == "__main__":
print("Queue with list as storage")
a_queue = Queue()
print(f"a_queue: {a_queue}")
for i in range(10):
a_queue.enqueue(i)
print(f"a_queue len: {len(a_queue)}")
print(f"a_queue storage: {(a_queue.storage)}")
print("dequeue a value...")
print(f"a_queue dequeue: {(a_queue.dequeue())}")
print(f"a_queue storage: {(a_queue.storage)}")
print(f"a_queue len: {len(a_queue)}")
print("----------"*8)
import sys
sys.path.append('./singly_linked_list')
from singly_linked_list import LinkedList
class Queue2:
def __init__(self):
self.size = 0
self.storage = LinkedList()
def __len__(self):
return self.size
def enqueue(self, value):
self.storage.add_to_tail(value)
self.size+=1
def dequeue(self):
if self.size == 0:
return None
self.size-=1
return self.storage.remove_head()
if __name__ == "__main__":
print("Queue with linked list as structure")
a_queue = Queue2()
print(f"a_queue: {a_queue}")
for i in range(10):
a_queue.enqueue(i)
print(f"a_queue len: {len(a_queue)}")
print(f"a_queue head: {(a_queue.storage.head.value)}")
print("dequeue a value...")
print(f"a_queue dequeue: {(a_queue.dequeue())}")
print(f"a_queue head: {(a_queue.storage.head.value)}")
print(f"a_queue len: {len(a_queue)}")
print("----------"*8)
## stretch
sys.path.append("./stack")
from stack import Stack
class Queue3:
def __init__(self):
self.size = 0
self.storage = Stack()
def __len__(self):
return self.size
def enqueue(self, value):
self.storage.push(value)
self.size+=1
def dequeue(self):
if self.size == 0:
raise RuntimeError("empty queue")
self.size-=1
return self.storage.pop()
if __name__ == "__main__":
print("Queue with stacks")
a_queue = Queue3()
print(f"a_queue: {a_queue}")
for i in range(10):
a_queue.enqueue(i)
print(f"a_queue len: {len(a_queue)}")
print(f"a_queue head: {(a_queue.storage.storage)}")
print("dequeue a value...")
tempStack = Stack()
for i in range(len(a_queue)-1):
tmp = a_queue.dequeue()
tempStack.push(tmp)
a_queue.enqueue(tempStack.pop())
# print(f"a_queue dequeue: {(a_queue.dequeue())}")
print(f"a_queue head: {(a_queue.storage.storage)}")
print(f"a_queue len: {len(a_queue)}")
|
13aa0b10bfb59b9f7b41a32d4d48f046e20bd8e4 | javianleu/Rosalind | /Complementing a Strand of DNA/DNAComplement.py | 769 | 4.25 | 4 | # Complementing A Strand of DNA
# Javier Anleu - 17149
# Opening DNA strand file
dnaF = open("Complementing a Strand of DNA/rosalind_revc.txt", "r")
# Reading DNA strand file
if dnaF.mode == 'r':
dna = dnaF.read()
# Closing file
dnaF.close()
# Function to reverse string
# Obtained from: https://www.journaldev.com/23647/python-reverse-string#python-reverse-string-using-slicing
def reverseSlicing(s):
return s[::-1]
# DNA complement strand
dnaC = ""
# Iterating DNA strand to generate complement
for i in dna:
if i == "A":
dnaC = dnaC + "T"
elif i == "C":
dnaC = dnaC + "G"
elif i == "G":
dnaC = dnaC + "C"
elif i == "T":
dnaC = dnaC + "A"
# Reversing sequence
dnaC = reverseSlicing(dnaC)
# Output
print (dnaC)
|
409fcf27e018b3e66fa2c871c0e9d10c50ddbfc9 | abr-98/image-reader-python | /image_rotation.py | 1,211 | 3.671875 | 4 | from PIL import Image
import imutils
import cv2
import os
ch="1"
def img_rotate(str):
while ch != "3":
img=Image.open(str)
img0=cv2.imread(str)
#img.show()
im=img.copy()
print("-----------------------OPTIONS-----------------------")
print("1.Right angle")
print("2.180 rotate")
print("3.exit")
ch=raw_input("Enter your choice: ")
if ch=="1":
#rotating image by 90
img = imutils.rotate_bound(img0, 90)
cv2.imwrite('test00.png',img)
imk=Image.open('test00.png')
imk.load()
imk.show()
des=raw_input("Do you want to save y-yes n-no ")
if des=="y":
#Saved in the same relative location else discarded
imk.save(str)
print("Saved")
else:
print("change discarded")
os.remove('test00.png')
elif ch=="2":
#rotating image by 90
im = im.rotate(180)
im.show()
des=raw_input("Do you want to save y-yes n-no ")
if des=="y":
#Saved in the same relative location else discarded
img.save(str)
print("Saved ")
else:
print("change discarded")
|
7513b303c8fe0a15147df3e06c115ff0cc952b09 | nadiavhansen/Python-Projects | /pythonProject2/jogoJokenpo.py | 2,810 | 3.59375 | 4 | import random
class Jogo():
print('PEDRA, PAPEL, TESOURA!')
def distribuir_cartas(self):
cartas_sorteadas = [random.randint(1, 3), random.randint(1, 3), random.randint(1, 3)]
return cartas_sorteadas
class Jogador():
def selecionar_carta(self, mao_de_cartas):
carta_selecionada = int(input('\nSelecione a carta desejada: '))
carta_selecionada = mao_de_cartas[carta_selecionada]
mao_de_cartas.remove(carta_selecionada)
print('A carta selecionada foi', carta_selecionada)
return carta_selecionada
class Computador():
def jogadas_computador(self):
jogada_computador = random.randint(1, 3)
return jogada_computador
class Round(Jogo):
def vencedor_do_round(self, carta_computador, carta_selecionada):
resultado = ''
for i in range(len(self.distribuir_cartas())):
if carta_computador == 1:
if carta_selecionada == 1:
resultado = 'Empate'
elif carta_selecionada == 2:
resultado = 'Venceu'
pass
elif carta_selecionada == 3:
resultado = 'Perdeu'
if carta_computador == 2:
if carta_selecionada == 1:
resultado = 'Perdeu'
elif carta_selecionada == 2:
resultado = 'Empate'
elif carta_selecionada == 3:
resultado = 'Venceu'
pass
if carta_computador == 3:
if carta_selecionada == 1:
resultado = 'Venceu'
pass
elif carta_selecionada == 2:
resultado = 'Perdeu'
elif carta_selecionada == 3:
resultado = 'Empate'
print(resultado)
return resultado
jogo = Jogo()
jogador = Jogador()
cartas_jogador = jogo.distribuir_cartas()
print('\nAs suas cartas são: ')
print(cartas_jogador)
carta_selecionada = jogador.selecionar_carta(cartas_jogador)
computador = Computador()
carta_computador = computador.jogadas_computador()
print('\nComputador selecionou', carta_computador)
round_atual = Round()
round_atual.vencedor_do_round(carta_computador, carta_selecionada)
print("")
# jogada.jogador()
# jogada.resultado_da_jogada()
# carta = int(input('Opções: '
# '\n1 - Pedra'
# '\n2 - Papel'
# '\n3 - Tesoura'))
# def ver_cartas(self, cartas):
#
# cartas_jogador = self.distribuir_cartas()
# print(cartas_jogador)
# return cartas_jogador
#
# carta_sorteada_1 = cartas_sorteadas[0]
# carta_sorteada_2 = cartas_sorteadas[1]
# carta_sorteada_3 = cartas_sorteadas[2]
|
6c1b904f5e10ec20e946b57f981a0ad2d96af334 | apabhishek178/website_work | /untitled/button3.py | 317 | 3.59375 | 4 | #button3.py
from tkinter import *
import tkinter
root=None
def buttonpushed():
global root
root.destroy()
def main():
global root
root=Tk()
w=Label(root,text="hello everyone!")
w.pack()
mybutton=Button(root,text="exit",command=buttonpushed)
mybutton.pack()
root.mainloop()
main() |
fc2e307316c47cdb721caebda2aee6fad9440697 | justdoit1990/leetCode | /lis/LIS_.py | 427 | 3.671875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/11/21 下午12:08
# @Author : Yanheng Wei
# @File : LIS_.py
# @Software: PyCharm
def lis(ls):
d = [1]*len(ls)
max_length = 1
for i in range(len(ls)):
for j in range(i):
if ls[i] > ls[j] and d[i] < d[j]+1:
d[i] = d[j] + 1
if max_length < d[i]:
max_length = d[i]
return max_length
if __name__ == "__main__":
a = [5, 3, 4, 8, 6, 7]
print lis(a) |
8b8cfa51e9349bf91cb5221833d14826d090ebfc | type-null/earthInsights | /jobs/affinitysolution/analyzer.py | 2,855 | 3.5 | 4 | """
Homework Exercise - SDE in DS Internship
Affinity Solutions
Author: Weihang Ren
"""
import re
import json
import numpy as np
from names import STATES, COUNTRIES, BRANDS
def similarity(token, brand):
"""
Similarity computed using the Levenshtein distance
ref: https://www.datacamp.com/community/tutorials/fuzzy-string-python
"""
# Initialize matrix of zeros
rows = len(token)+1
cols = len(brand)+1
distance = np.zeros((rows, cols), dtype=int)
# index each character
for i in range(1, rows):
for k in range(1, cols):
distance[i][0] = i
distance[0][k] = k
# Iterate over the matrix to save the cost of difference
for col in range(1, cols):
for row in range(1, rows):
if token[row-1] == brand[col-1]:
# the characters are the same
cost = 0
else:
cost = 2
distance[row][col] = min(distance[row-1][col] + 1, # Cost of deletions
distance[row][col-1] + 1, # Cost of insertions
distance[row-1][col-1] + cost) # Cost of substitutions
return ((len(token)+len(brand)) - distance[row][col]) / (len(token)+len(brand))
def process(description: str):
"""
Convert input to output format
"""
# init variables
state, country, phone_no = "", "", ""
# clean special characters
string = re.sub(re.compile(r'[\'*-]+'), '', description.lower())
# tokenize input
tokens = string.strip().split()
# classify tokens
tokens_used = []
for token in tokens:
# number
if token.isnumeric():
# TODO: will phone_no be in other format: 222-222-2222 ?
phone_no = token
tokens_used.append(token)
# two character: country or state abbreviation
elif len(token) == 2:
if token in COUNTRIES:
country = token
tokens_used.append(token)
elif token in STATES.keys():
state = token
tokens_used.append(token)
tokens_remain = [t for t in tokens if t not in tokens_used]
# match rest tokens to brands
brands = {}
for i in range(len(tokens_remain)):
if tokens_remain[i] in BRANDS:
brand = tokens_remain[i]
else:
probability = {brand: similarity(brand, tokens_remain[i]) for brand in BRANDS}
brand_guess = sorted([(p, b) for b, p in probability.items()], reverse=True)
brand_guess = [b for _, b in brand_guess]
brand = brand_guess[0]
brands[f"{i+1}"] = brand
data = {
"brands": [brands],
"state": state,
"country": country,
"ph no": phone_no,
}
return json.dumps(data)
|
6376cdb0ac07699083ef88a47d2885cafb1e260a | meduka/guess-a-number | /guess_a_number2.py | 4,446 | 3.71875 | 4 | import random
import math
# config
low = 1
high = 10
limit_calc = (math.log(high,2))
limit = math.ceil(limit_calc)
# helper functions
def show_start_screen():
print()
print()
print(" GGGG UU UU EEEEEEE SSSSS SSSSS AAA NN NN UU UU MM MM BBBBB EEEEEEE RRRRRR !!! !!! ")
print(" GG GG UU UU EE SS SS AAAAA NNN NN UU UU MMM MMM BB B EE RR RR !!! !!! ")
print(" GG UU UU EEEEE SSSSS SSSSS AA AA NN N NN UU UU MM MM MM BBBBBB EEEEE RRRRRR !!! !!!")
print(" GG GG UU UU EE SS SS AAAAAAA NN NNN UU UU MM MM BB BB EE RR RR ")
print(" GGGGGG UUUUU EEEEEEE SSSSS SSSSS AA AA NN NN UUUUU MM MM BBBBBB EEEEEEE RR RR !!! !!!")
print()
print()
print()
def show_credits():
print()
print("Goodbye.")
print()
print("Created by Manuela Cano.")
def get_guess():
while True:
guess = input("Guess a number: ")
if guess.isnumeric():
guess = int(guess)
return guess
else:
print()
print("You must enter a number.")
print()
def pick_number():
print()
print()
print()
print("I'm thinking of a number from " + str(low) + " to " + str(high) +".")
print()
print()
print("You will get " + str(limit) + " tries. Good luck.")
print()
print()
return random.randint(low, high)
def check_guess(guess, rand):
if guess < rand:
print("You guessed too low.")
print()
elif guess > rand:
print("You guessed too high.")
print()
def show_result(guess, rand):
if guess == rand:
print()
print("You win!")
print()
print()
print("/$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$ /$$ /$$ /$$ /$$$$$$ /$$$$$$$$ /$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$")
print("/$$__ $$ /$$__ $$| $$$ | $$ /$$__ $$| $$__ $$ /$$__ $$ /$$__ $$| $$ | $$| $$ /$$__ $$|__ $$__/|_ $$_/ /$$__ $$| $$$ | $$ /$$__ $$| $$")
print("| $$ \__/| $$ \ $$| $$$$| $$| $$ \__/| $$ \ $$| $$ \ $$| $$ \__/| $$ | $$| $$ | $$ \ $$ | $$ | $$ | $$ \ $$| $$$$| $$| $$ \__/| $$")
print("| $$ | $$ | $$| $$ $$ $$| $$ /$$$$| $$$$$$$/| $$$$$$$$| $$ /$$$$| $$ | $$| $$ | $$$$$$$$ | $$ | $$ | $$ | $$| $$ $$ $$| $$$$$$ | $$")
print("| $$ | $$ | $$| $$ $$$$| $$|_ $$| $$__ $$| $$__ $$| $$|_ $$| $$ | $$| $$ | $$__ $$ | $$ | $$ | $$ | $$| $$ $$$$ \____ $$|__/")
print("| $$ $$| $$ | $$| $$\ $$$| $$ \ $$| $$ \ $$| $$ | $$| $$ \ $$| $$ | $$| $$ | $$ | $$ | $$ | $$ | $$ | $$| $$\ $$$ /$$ \ $$ ")
print("| $$$$$$/| $$$$$$/| $$ \ $$| $$$$$$/| $$ | $$| $$ | $$| $$$$$$/| $$$$$$/| $$$$$$$$| $$ | $$ | $$ /$$$$$$| $$$$$$/| $$ \ $$| $$$$$$/ /$$")
print("\______/ \______/ |__/ \__/ \______/ |__/ |__/|__/ |__/ \______/ \______/ |________/|__/ |__/ |__/ |______/ \______/ |__/ \__/ \______/ |__/")
print()
print()
print()
else:
print()
print("You lose... The number I was thinking of was " + str(rand) + ".")
print()
print()
def play_again():
while True:
decision = input("Would you like to play again? (y/n) ")
decision = decision.casefold()
if decision == 'y' or decision == 'yes':
return True
print()
print()
print()
elif decision == 'n' or decision == 'no':
return False
print()
print()
print()
else:
print("I don't understand. Please enter 'y' or 'n'.")
print()
print()
print()
def play():
guess = -1
tries = 0
rand = pick_number()
while guess != rand and tries < limit:
guess = get_guess()
check_guess(guess, rand)
tries += 1
show_result(guess, rand)
# Game starts running
show_start_screen()
playing = True
while playing:
play()
playing = play_again()
show_credits()
|
b40a58abb043d8076d26b289dacf029d6bd5080d | dougtc1/algorithms2 | /proyecto2/clases.py | 3,432 | 3.625 | 4 | # Universidad Simon Bolivar
#
# Laboratorio de Algoritmos y Estructuras II
#
# Ricardo Churion. Carnet: 11-10200
# Douglas Torres. Carnet: 11-11027
# Grupo: 06
#
# * VA SIN ACENTOS *
#
# Archivo que contiene las clases usadas en el archivo simulador.py
# Definicion de la clase paquete
class Paquete:
def __init__(self,destinatario=None,prioridad=None,capacidad=None,\
duracion=None,subpaquetes=None):
self.destinatario = destinatario
self.prioridad = prioridad
self.capacidad = capacidad
self.duracion = duracion
self.subpaquetes = subpaquetes
# Definicion de la clase Cola de Prioridades
class ColaP:
def __init__(self,valor=None,siguiente=None):
self.valor = valor
self.siguiente = siguiente
def longitud(self):
if self.siguiente:
return self.siguiente.longitud() + 1
elif self.valor:
return 1
else:
return 0
def obtener(self,indice):
if indice == 0:
return self.valor
elif self.siguiente:
return self.siguiente.obtener(indice-1)
else:
return None
def encolar(self,valor):
if self.valor == None:
self.valor = valor
else:
if self.valor.prioridad > valor.prioridad:
temp = ColaP()
temp.valor = self.valor
temp.siguiente = self.siguiente
self.valor = valor
self.siguiente = temp
elif self.siguiente:
self.siguiente.encolar(valor)
else:
self.siguiente = ColaP()
self.siguiente.valor = valor
def desencolar(self):
salida = self.valor
if (self.siguiente == None):
self.valor = None
else:
temp = ColaP()
temp.valor = self.siguiente.valor
temp.siguiente = self.siguiente.siguiente
self.valor = temp.valor
self.siguiente = temp.siguiente
return (salida)
def esVacia(self):
if self.valor:
return False
else:
return True
# Definicion de la clase Pila que sera usada en cada mensajero
class Pila:
def __init__(self,valor=None,siguiente=None):
self.valor = valor
self.siguiente = siguiente
def remover(self,indice):
if indice == 0:
if self.siguiente:
self.valor = self.siguiente.valor
self.siguiente = self.siguiente.siguiente
else:
self.valor = None
return True
elif self.siguiente:
self.siguiente.remover(indice-1)
else:
return False
def longitud(self):
if self.siguiente:
return self.siguiente.longitud() + 1
elif self.valor:
return 1
else:
return 0
def obtener(self,indice):
if indice == 0:
return self.valor
elif self.siguiente:
return self.siguiente.obtener(indice-1)
else:
return None
def empilar (self,valor):
if self.valor == None:
self.valor = valor
elif self.siguiente:
self.siguiente.empilar(valor)
else:
self.siguiente = Pila(valor)
def desempilar(self):
salida = self.obtener(self.longitud() - 1)
self.remover(self.longitud() - 1)
return(salida)
def mostrarUlt(self):
elemento = self.desempilar()
self.empilar(elemento)
return (elemento)
def esVacia(self):
if self.valor:
return False
else:
return True
# Definicion de la clase Mensajero
class Mensajero:
def __init__(self,identificador=None,paquetesEmpilados=None,\
tiempoEmpilado=None,ini=False):
self.identificador = identificador
self.paquetesEmpilados = Pila()
# Momento en el que inicia
self.tiempoEmpilado = tiempoEmpilado
# Inicializacion, dice si el mensajero ya inicio la entrega del paquete
self.ini = ini |
016c2b098b98c911622373cedf31b280cd78142a | KaraCo/python_basics | /webapp/student.py | 797 | 4.09375 | 4 | # A student class to add students to a web application
# create an empty list
students = []
class Student:
'''
instance variable school_name
init, str, capitalize name and school name functions
'''
school_name = "Springfield High School"
def __init__(self, name, last_name, student_id = 332):
self.name = name
self.last_name = last_name
self.student_id = student_id
students.append(self)
# since the init, initializes the object in the heap,
# if we want to print it, we need to convert it to a string
def __str__(self):
return "Student " + self.name
def get_name_capitalize(self):
return self.name.capitalize()
def get_school_name(self):
return self.school_name |
d21159f97bfb4cadeacd52875da8a113b785de4a | xiaolonghao/chainercv | /chainercv/utils/iterator/apply_to_iterator.py | 10,046 | 3.78125 | 4 | import warnings
from chainercv.utils.iterator.unzip import unzip
def apply_to_iterator(func, iterator, n_input=1, hook=None, comm=None):
"""Apply a function/method to batches from an iterator.
This function applies a function/method to an iterator of batches.
It assumes that the iterator iterates over a collection of tuples
that contain inputs to :func:`func`.
Additionally, the tuples may contain values
that are not used by :func:`func`.
For convenience, we allow the iterator to iterate over a collection of
inputs that are not tuple.
Here is an illustration of the expected behavior of the iterator.
This behaviour is the same as :class:`chainer.Iterator`.
>>> batch = next(iterator)
>>> # batch: [in_val]
or
>>> # batch: [(in_val0, ..., in_val{n_input - 1})]
or
>>> # batch: [(in_val0, ..., in_val{n_input - 1}, rest_val0, ...)]
:func:`func` should take batch(es) of data and
return batch(es) of computed values.
Here is an illustration of the expected behavior of the function.
>>> out_vals = func([in_val0], ..., [in_val{n_input - 1}])
>>> # out_vals: [out_val]
or
>>> out_vals0, out_vals1, ... = func([in_val0], ..., [in_val{n_input - 1}])
>>> # out_vals0: [out_val0]
>>> # out_vals1: [out_val1]
With :func:`apply_to_iterator`, users can get iterator(s) of values
returned by :func:`func`. It also returns iterator(s) of input values and
values that are not used for computation.
>>> in_values, out_values, rest_values = apply_to_iterator(
>>> func, iterator, n_input)
>>> # in_values: (iter of in_val0, ..., iter of in_val{n_input - 1})
>>> # out_values: (iter of out_val0, ...)
>>> # rest_values: (iter of rest_val0, ...)
Here is an exmple, which applies a pretrained Faster R-CNN to
PASCAL VOC dataset.
>>> from chainer import iterators
>>>
>>> from chainercv.datasets import VOCBBoxDataset
>>> from chainercv.links import FasterRCNNVGG16
>>> from chainercv.utils import apply_to_iterator
>>>
>>> dataset = VOCBBoxDataset(year='2007', split='test')
>>> # next(iterator) -> [(img, gt_bbox, gt_label)]
>>> iterator = iterators.SerialIterator(
... dataset, 2, repeat=False, shuffle=False)
>>>
>>> # model.predict([img]) -> ([pred_bbox], [pred_label], [pred_score])
>>> model = FasterRCNNVGG16(pretrained_model='voc07')
>>>
>>> in_values, out_values, rest_values = apply_to_iterator(
... model.predict, iterator)
>>>
>>> # in_values contains one iterator
>>> imgs, = in_values
>>> # out_values contains three iterators
>>> pred_bboxes, pred_labels, pred_scores = out_values
>>> # rest_values contains two iterators
>>> gt_bboxes, gt_labels = rest_values
Args:
func: A callable that takes batch(es) of input data and returns
computed data.
iterator (iterator): An iterator of batches.
The first :obj:`n_input` elements in each sample are
treated as input values. They are passed to :obj:`func`.
If :obj:`comm` is specified, only the iterator of the root
worker is used.
n_input (int): The number of input data. The default value is :obj:`1`.
hook: A callable that is called after each iteration.
:obj:`in_values`, :obj:`out_values`, and :obj:`rest_values`
are passed as arguments.
Note that these values do not contain data from the previous
iterations.
If :obj:`comm` is specified, only the root worker executes
this hook.
comm (~chainermn.communicators.CommunicatorBase):
A ChainerMN communicator.
If it is specified, this function scatters the iterator of
root worker and gathers the results to the root worker.
Returns:
Three tuples of iterators:
This function returns three tuples of iterators:
:obj:`in_values`, :obj:`out_values` and :obj:`rest_values`.
* :obj:`in_values`: A tuple of iterators. Each iterator \
returns a corresponding input value. \
For example, if :func:`func` takes \
:obj:`[in_val0], [in_val1]`, :obj:`next(in_values[0])` \
and :obj:`next(in_values[1])` will be \
:obj:`in_val0` and :obj:`in_val1`.
* :obj:`out_values`: A tuple of iterators. Each iterator \
returns a corresponding computed value. \
For example, if :func:`func` returns \
:obj:`([out_val0], [out_val1])`, :obj:`next(out_values[0])` \
and :obj:`next(out_values[1])` will be \
:obj:`out_val0` and :obj:`out_val1`.
* :obj:`rest_values`: A tuple of iterators. Each iterator \
returns a corresponding rest value. \
For example, if the :obj:`iterator` returns \
:obj:`[(in_val0, in_val1, rest_val0, rest_val1)]`, \
:obj:`next(rest_values[0])` \
and :obj:`next(rest_values[1])` will be \
:obj:`rest_val0` and :obj:`rest_val1`. \
If the input \
iterator does not give any rest values, this tuple \
will be empty.
"""
if comm is None or comm.rank == 0:
in_values, out_values, rest_values = unzip(
_apply(func, iterator, n_input, hook, comm))
# in_values: iter of ([in_val0], [in_val1], ...)
# -> (iter of in_val0, iter of in_val1, ...)
in_values = tuple(map(_flatten, unzip(in_values)))
# out_values: iter of ([out_val0], [out_val1], ...)
# -> (iter of out_val0, iter of out_val1, ...)
out_values = tuple(map(_flatten, unzip(out_values)))
# rest_values: iter of ([rest_val0], [rest_val1], ...)
# -> (iter of rest_val0, iter of rest_val1, ...)
rest_values = tuple(map(_flatten, unzip(rest_values)))
return in_values, out_values, rest_values
else:
# dummy loop to proceed generator
for _ in _apply(func, None, n_input, None, comm):
pass
def _apply(func, iterator, n_input, hook, comm):
if comm is None:
comm_size = 1
comm_rank = 0
else:
comm_size = comm.size
comm_rank = comm.rank
batchsize_checked = False
while True:
if comm_rank == 0:
try:
batch = next(iterator)
# batch: [(in_val0, in_val1, ... , rest_val0, rest_val1, ...)]
# or [in_val]
q = len(batch) // comm_size
r = len(batch) % comm_size
if not batchsize_checked:
if not r == 0:
warnings.warn(
'The batchsize of the given iterator ({}) is not '
'a multiple of the number of workers ({}). '
'The total batchsize among all workers should be '
'specified and current setting will have a bad '
'effect on performace. '
.format(len(batch), comm_size),
RuntimeWarning)
batchsize_checked = True
in_values = []
rest_values = []
in_values_locals = [[] for _ in range(comm_size)]
for i, sample in enumerate(batch):
if i < (q + 1) * r:
k = i // (q + 1)
else:
k = (i - r) // q
if isinstance(sample, tuple):
in_values.append(sample[0:n_input])
rest_values.append(sample[n_input:])
in_values_locals[k].append(sample[0:n_input])
else:
in_values.append((sample,))
rest_values.append(())
in_values_locals[k].append((sample,))
except StopIteration:
in_values_locals = [None] * comm_size
else:
in_values_locals = None
if comm is None:
in_values_local = in_values_locals[0]
else:
in_values_local = comm.mpi_comm.scatter(in_values_locals)
if in_values_local is None:
break
elif len(in_values_local) == 0:
out_values_local = None
else:
# in_values_local: [(in_val0, in_val1, ...)]
# -> ([in_val0], [in_val1], ...)
in_values_local = tuple(list(v) for v in zip(*in_values_local))
# out_values_local: ([out_val0], [out_val1], ...) or [out_val]
out_values_local = func(*in_values_local)
if not isinstance(out_values_local, tuple):
# out_values_local: [out_val] -> ([out_val],)
out_values_local = out_values_local,
if comm is None:
out_values_locals = [out_values_local]
else:
out_values_locals = comm.gather_obj(out_values_local)
if comm_rank == 0:
out_values = out_values_locals.pop(0)
for out_values_local in out_values_locals:
if out_values_local is None:
break
for out_val, out_val_local in zip(
out_values, out_values_local):
out_val += out_val_local
# in_values: [(in_val0, in_val1, ...)]
# -> ([in_val0], [in_val1], ...)
in_values = tuple(list(v) for v in zip(*in_values))
# rest_values: [(rest_val0, rest_val1, ...)]
# -> ([rest_val0], [rest_val1], ...)
rest_values = tuple(list(v) for v in zip(*rest_values))
if hook:
hook(in_values, out_values, rest_values)
yield in_values, out_values, rest_values
def _flatten(iterator):
return (sample for batch in iterator for sample in batch)
|
8170a5a28e3c6ef424b30ea30e5d7a3ac4b38fc2 | ademaas/python-ex | /round9/playerprogram.py | 3,153 | 3.96875 | 4 | # CS-A111 Fall 2018
# A test program for Exercise 9.3
# Author Kerttu Pollari-Malmi
#
# The main program has not been split to several functions to keep
# it as simple as possible for beginners.
import player
# A function to read an integer with exception handling.
def read_integer():
int_ok = False
while not int_ok:
try:
luku = int(input())
int_ok = True
return luku
except ValueError:
print("Invalid integer. Enter a new intetger!")
def main():
name1 = input("Enter the name of the first player.\n")
name2 = input("Enter the name of the second player.\n")
player1 = player.Player(name1)
player2 = player.Player(name2)
print("First player:")
print("Name:", player1.get_name())
print("Number of games:", player1.get_no_of_games())
print("Record:", player1.get_record())
print("Average: {:.2f}".format(player1.average()))
if player1.is_master():
print("The player has a master title.")
else:
print("The player has not achieved a master title.")
print()
print("Second player:")
print("Name:", player2.get_name())
print("Number of games:", player2.get_no_of_games())
print("Record:", player2.get_record())
print("Average: {:.2f}".format(player2.average()))
if player2.is_master():
print("The player has a master title.")
else:
print("The player has not achieved a master title.")
print()
print("Adding game results...")
print("How many games will be added to the first player?")
count1 = read_integer()
for i in range(count1):
print("Enter the points of the next game.")
gamepoints = read_integer()
player1.add_game(gamepoints)
print("How many games will be added to the second player?")
count2 = read_integer()
for i in range(count2):
print("Enter the points of the next game.")
gamepoints = read_integer()
player2.add_game(gamepoints)
print("The playes after adding the games:")
print("Name:", player1.get_name())
print("Number of games:", player1.get_no_of_games())
print("Record:", player1.get_record())
print("Average: {:.2f}".format(player1.average()))
if player1.is_master():
print("The player has a master title.")
else:
print("The player has not achieved a master title.")
print("Name:", player2.get_name())
print("Number of games:", player2.get_no_of_games())
print("Record:", player2.get_record())
print("Average: {:.2f}".format(player2.average()))
if player2.is_master():
print("The player has a master title.")
else:
print("The player has not achieved a master title.")
print()
if player1.is_better(player2):
print("The first player is better than the second player.")
elif player2.is_better(player1):
print("The second player is better than the first player.")
else:
print("The players are equal.")
print
print("The player information by using method __str__:")
print(player1)
print(player2)
main() |
43f34c7509bf297cf3c0d00bcaae9d0548017c2e | BrettMZig/PythonFun | /primes.py | 454 | 3.765625 | 4 |
def composite_gen(prime, first, last):
c = prime + prime
while c < last:
if c > first:
yield c
c = c + prime
def find_primes(first, last):
if first < 2: first = 2
mSet = set(xrange(first, last))
primes = []
for x in xrange(2, last):
if x in mSet:
primes.append(x)
mSet = mSet - set(composite_gen(x, first, last))
return primes
if __name__ == "__main__":
first = 200
last = 10000
print find_primes(first, last)
|
3c83bfff0eb932ac8efbae3fc85756ffd27bdf9b | WeDias/RespPPZ | /WesleyDiasII.py | 2,944 | 3.9375 | 4 | # Wesley Dias (1º Semestre ADS-B), Lista II
# Exercício 1
lado1 = int(input('Digite o tamanho do lado 1: '))
lado2 = int(input('Digite o tamanho do lado 2: '))
lado3 = int(input('Digite o tamanho do lado 3: '))
if lado2-lado3 < lado1 < (lado2+lado3) and lado1-lado3 < lado2 < (lado1+lado3) and lado1-lado2 < lado3 < (lado1+lado2):
if lado1 == lado2 == lado3:
print('Pode formar um triângulo equilátero')
elif lado1 != lado2 != lado3:
print('Pode formar um triângulo escaleno')
else:
print('Pode formar um triângulo Isósceles')
else:
print('Não pode formar um triângulo')
# Exercício 2
ano = int(input('Digite um ano: '))
if ano % 4 == 0 and ano % 100 != 0 and ano != 0 or ano % 400 == 0 and ano != 0:
print(f'{ano} é um ano bissexto')
else:
print(f'{ano} não é um ano bissexto')
# Exercício 3
peso = int(input('Digite o peso total de peixes em KG: '))
if peso > 50:
excesso = peso-50
multa = excesso*4
print(f'Com um excesso de {excesso}KG a multa será de R${multa:.2f}')
else:
excesso = multa = 'ZERO'
print(f'Excesso: {excesso}. Multa: {multa}.')
# Exercício 4
n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número: '))
n3 = int(input('Digite mais um número: '))
if n2 <= n1 >= n3:
print(f'O maior número foi {n1}')
elif n1 <= n2 >= n3:
print(f'O maior número foi {n2}')
else:
print(f'O maior número foi {n3}')
# Exercício 5
n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número: '))
n3 = int(input('Digite mais um número: '))
if n2 <= n1 >= n3:
print(f'O maior número foi: {n1}')
elif n1 <= n2 >= n3:
print(f'O maior número foi: {n2}')
elif n1 <= n3 >= n2:
print(f'O maior número foi: {n3}')
if n2 >= n1 <= n3:
print(f'O menor número foi: {n1}')
elif n1 >= n2 <= n3:
print(f'O menor número foi: {n2}')
elif n1 >= n3 <= n2:
print(f'O menor número foi: {n3}')
# Exercício 6
ganho = float(input('Digite seu ganho R$ por hora: '))
horas = int(input('Digite quantas horas foram trabalhadas no mês: '))
salbruto = ganho * horas
ir = salbruto * 11/100
inss = salbruto * 8/100
sindicato = salbruto * 5/100
salliquido = salbruto - ir - inss - sindicato
print(f'Seu salário bruto neste neste mês foi de R${salbruto:.2f}')
print(f'Será descontado para o imposto de renda o valor de R${ir:.2f}')
print(f'Será descontado para o INSS o valor de R${inss:.2f}')
print(f'Será descontado para o sindicato o valor de R${sindicato:.2f}')
print(f'Seu salário líquido será de R${salliquido:.2f}')
# Exercício 7
m2 = int(input('Digite a quantidade de metros quadrados a ser pintados: '))
if m2 <= 54:
print(f'Compre 1 lata de tinta, preço: R$80,00')
else:
latas = m2 // 54
if m2 % 54 > 0:
latas += 1
print(f'Compre {latas} latas de tinta, preço: R${latas*80:.2f}')
|
5e53917125b152a0525e1404d09dfad644a8b94f | TerryRPatterson/Coursework | /python/test.py | 246 | 3.90625 | 4 | import math
def isPrime(n):
a = 2
b = -1
while n % 2 == 0:
return False
while a + b < n :
b = math.sqrt(abs((a ** 2)-n))
if b.is_integer() and b > 1:
return False
a += 1
return True
|
868c9f7d9b55824ea5d219737c4d4972f223385c | jcshott/interview_prep | /recursive_index/recursive_index.py | 1,222 | 4.21875 | 4 | def recursive_search(needle, haystack, idx=0):
"""Given list (haystack), return index (0-based) of needle in the list.
Return None if needle is not in haystack.
Do this with recursion. You MAY NOT USE A `for` OR `while` LOOP.
>>> lst = ["hey", "there", "you"]
>>> recursive_search("hey", lst)
0
>>> recursive_search("you", lst)
2
>>> recursive_search("porcupine", lst) is None
True
"""
# def _recursive_haystack(needle, haystack, idx=0):
# # if the index is equal to len of haystack, then we've gone thru haystack & needle not there
# if idx == len(haystack):
# return None
# # if the haystack item at index is the needle. we found it, return that index
# if haystack[idx] == needle:
# return idx
# # if we haven't found it, go to next index
# return _recursive_haystack(needle, haystack, idx+1)
# # call the recursive function with a new variable, indx starting at zero
# return _recursive_haystack(needle, haystack, 0)
if idx == len(haystack):
return None
if haystack[idx] == needle:
return idx
return recursive_search(needle, haystack, idx+1)
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TESTS PASSED!\n"
|
4da965a4532ae946609e8e6f6e00ca4e13624703 | KevinCabeza/myrepo | /PycharmProjects/introduccion/estructurasdecontrol/suma_2_numeros.py | 283 | 4.0625 | 4 | # visualiza la suma de dos numeros enteros introducidos por teclado
#introducimos por teclado
num1 = int(input("num1 :"))
num2 = int(input("num2 :"))
#guardamos la suma
suma = (num1 + num2)
# imprimimos el resultado en pantalla
print("La suma de :", num1, "y", num2, "=", suma)
|
d162a6fbb83133e976dbcb71efac5172ae6a90d5 | cpamieta/547-202 | /Artificial Intelligence Exercise/Bot Building/Bot saves princess - 2.py | 780 | 3.78125 | 4 | #In this version of "Bot saves princess", Princess Peach and bot's position are randomly set. Can you save the princess?
#
def nextMove(n,r,c,grid):
nn=n-1
m=int(n/2)
x=0
xx=0
yy=0
notFound=True
while(notFound):
y=0
while(y<n):
if(grid[x][y]== 'p'):
notFound=False
yy = x-r
xx = y -c
y=y+1
x=x+1
if(xx<0):
return("LEFT")
elif(xx>0):
return("RIGHT")
elif(yy<0):
return("UP")
elif(yy>0):
return("DOWN")
n = int(input())
r,c = [int(i) for i in input().strip().split()]
grid = []
for i in range(0, n):
grid.append(input())
print(nextMove(n,r,c,grid))
|
de1dd27f57164f26eedf5671a92c99aa5be1b990 | raor23/GameDesign2020 | /Major-Playingwithforloop.py | 707 | 4.125 | 4 | #Rohan Rao
#This program contains ForLoops Program, Prime Numbers, and the Fibonacci sequence
#Forloops
for line in range(5):
print()
for number in range(5-line,0,-1):
print(number, end =' ')
#Prime Numbers Program
start = 25 #First Value of finding prime number
end = 50 #Last Value of finding prime number
for num in range(start, end + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
#Fibonacci Sequence Program
def fib(number_of_terms):
a=0
x= 0
y= 1
z= 0
while a <= number_of_terms:
print(x)
z= x + y
x = y
y = z
a= a + 1
fib(10)
|
b32ebe68eff7e6244127362d51a0e0a1bc17eb74 | sssunda/solve_algorithms | /programmers/count_of_py.py | 384 | 3.6875 | 4 | def solution(s):
word_dict = {}
for element in s.lower():
word_dict[element] = word_dict.get(element, 0) + 1
if word_dict.get('p', 0) == word_dict.get('y', 0):
return True
return False
if __name__ == '__main__':
s = 'pPoooyY'
print(solution(s))
"""
def solution(s):
return s.lower().count('p') == s.lower().count('y')
""" |
9a23e426709fb456247f9c447741b7cd83ca2556 | Moglten/Nanodegree-Data-structure-and-Algorithm-Udacity | /Advanced Algorithm/greed/Greedy Algorithm.py | 3,863 | 4.46875 | 4 | In Greedy Algorithm
- U taking that choice give u max benefit neverless after that u take ducsion just for now .
-Examlple Code1-
------------------------------------------------------------------
Given arrival and departure times of trains on a single day in a railway platform, find out the minimum number of platforms
required so that no train has to wait for the other(s) to leave.
You will be given arrival and departure times in the form of a list.
Note: Time hh:mm would be written as integer hhmm for e.g. 9:30 would be written as 930. Similarly, 13:45 would be given as 1345
-----------------------------------------------------------------------------------------------------------
Solution:-
from queue import PriorityQueue
def min_platforms(arrival, departure):
#departure
platforms =PriorityQueue()
if platforms.qsize() == 0:
platforms.put_nowait(departure[0])
for i in range(1,len(arrival)):
if arrival[i]>=platforms.queue[0]:
platforms.get_nowait()
platforms.put_nowait(departure[i])
else :
platforms.put_nowait(departure[i])
return platforms.qsize()
-Examlple Code1-
------------------------------------------------------------------
Given arrival and departure times of trains on a single day in a railway platform, find out the minimum number of platforms
required so that no train has to wait for the other(s) to leave.
You will be given arrival and departure times in the form of a list.
Note: Time hh:mm would be written as integer hhmm for e.g. 9:30 would be written as 930. Similarly, 13:45 would be given as 1345
-----------------------------------------------------------------------------------------------------------
Solution:-
from queue import PriorityQueue
def min_platforms(arrival, departure):
#departure
platforms =PriorityQueue()
if platforms.qsize() == 0:
platforms.put_nowait(departure[0])
for i in range(1,len(arrival)):
if arrival[i]>=platforms.queue[0]:
platforms.get_nowait()
platforms.put_nowait(departure[i])
else :
platforms.put_nowait(departure[i])
return platforms.qsize()
-Examlple Code(1)-
------------------------------------------------------------------
Given arrival and departure times of trains on a single day in a railway platform, find out the minimum number of platforms
required so that no train has to wait for the other(s) to leave.
You will be given arrival and departure times in the form of a list.
Note: Time hh:mm would be written as integer hhmm for e.g. 9:30 would be written as 930. Similarly, 13:45 would be given as 1345
-----------------------------------------------------------------------------------------------------------
Solution:-
from queue import PriorityQueue
def min_platforms(arrival, departure):
platforms =PriorityQueue()
if platforms.qsize() == 0:
platforms.put_nowait(departure[0])
for i in range(1,len(arrival)):
if arrival[i]>=platforms.queue[0]:
platforms.get_nowait()
platforms.put_nowait(departure[i])
else :
platforms.put_nowait(departure[i])
return platforms.qsize()
-Examlple Code(2)-
------------------------------------------------------------------
Starting from the number 0, find the minimum number of operations required to reach a given positive target number. You can only use the following two operations:
1. Add 1
2. Double the number
-----------------------------------------------------------------------------------------------------------
Solution:-
def min_operations(number):
steps = 0
while number > 0:
if number % 2 == 0 :
number /= 2
steps += 1
else :
number -=1
steps += 1
return steps
|
0527f1dd7ad27fe105397b868b67aa3dbf972972 | AllenAnZifeng/leetcode | /Past interview Questions/Amazon OA prep/k_closest_points.py | 4,478 | 3.984375 | 4 | #
# """
# Definition for a point.
# class Point:
# def __init__(self, a=0, b=0):
# self.x = a
# self.y = b
# """
from typing import List
#
#
# class Point:
# def __init__(self, a=0, b=0):
# self.x = a
# self.y = b
#
# class Solution:
# """
# @param points: a list of points
# @param origin: a point
# @param k: An integer
# @return: the k closest points
# """
# def kClosest(self, points:List[Point], origin:Point, k):
# res = [] # point, distance
# for i in range(k):
# distance = ((points[i].x - origin.x) ** 2 + (points[i].y - origin.y) ** 2) ** 0.5
# res.append((points[i],distance))
#
# res.sort(key=lambda x:x[0].y)
# res.sort(key=lambda x:x[0].x)
# res.sort(key=lambda x: x[1])
#
# for i in range(k,len(points)):
# distance = ((points[i].x - origin.x) ** 2 + (points[i].y - origin.y) ** 2) ** 0.5
# if distance<res[-1][1] or \
# (distance==res[-1][1] and points[i].x<res[-1][0].x) or \
# (distance==res[-1][1] and points[i].x==res[-1][0].x and points[i].y <res[-1][0].y):
# res[-1] = (points[i],distance)
# res.sort(key=lambda x: x[0].y)
# res.sort(key=lambda x: x[0].x)
# res.sort(key=lambda x: x[1])
#
#
# return [p[0] for p in res]
# class Solution:
# def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
# points.sort(key=lambda x:x[0]**2+x[1]**2)
# return points[:k]
class Solution:
def kClosest(self, points, k: int) -> List[List[int]]:
def heapify_up(heap:List,element):
heap.append(element)
cur_index = len(heap)-1
while (cur_index-1)//2>=0:
parent_index = (cur_index-1)//2
if heap[cur_index][1]>heap[parent_index][1]:
heap[cur_index],heap[parent_index] = heap[parent_index],heap[cur_index]
cur_index = parent_index
else:
break
return heap
def heapify_down(heap):
cur_index = 0
left_child_index = 2 * cur_index + 1
right_child_index = 2 * cur_index + 2
while left_child_index <= len(heap)-1 and right_child_index<=len(heap)-1:
if heap[cur_index][1]<heap[left_child_index][1]:
if heap[right_child_index][1]>heap[left_child_index][1]:
heap[cur_index], heap[right_child_index] = heap[right_child_index], heap[cur_index]
cur_index = right_child_index
left_child_index = 2 * cur_index + 1
right_child_index = 2 * cur_index + 2
# print('right ', heap)
else:
heap[cur_index],heap[left_child_index] = heap[left_child_index],heap[cur_index]
cur_index = left_child_index
left_child_index = 2 * cur_index + 1
right_child_index = 2 * cur_index + 2
# print('left ',heap)
elif heap[cur_index][1]<heap[right_child_index][1]:
heap[cur_index], heap[right_child_index] = heap[right_child_index], heap[cur_index]
cur_index = right_child_index
left_child_index = 2 * cur_index + 1
right_child_index = 2 * cur_index + 2
# print('right ', heap)
else:
# print('done')
break
if left_child_index <= len(heap)-1:
if heap[cur_index][1]<heap[left_child_index][1]:
heap[cur_index],heap[left_child_index] = heap[left_child_index],heap[cur_index]
return heap
heap = []
for i in range(k):
heap = heapify_up(heap,[points[i], points[i][0] ** 2 + points[i][1] ** 2])
# print(heap)
for i in range(k,len(points)):
distance = points[i][0] ** 2 + points[i][1] ** 2
if distance < heap[0][1]:
heap[0] = [points[i],distance]
# print(heap)
heap = heapify_down(heap)
return [p[0] for p in heap]
print(Solution().kClosest([[68,97],[34,-84],[60,100],[2,31],[-27,-38],[-73,-74],[-55,-39],[62,91],[62,92],[-57,-67]],5)) |
b05638f89a2c58ed45da93f17f4b83fa8716f80a | Srilalitha/Projects | /online_pdsa_class/ListQuiz.py | 1,547 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 3 12:09:54 2020
@author: shanmukha
"""
def f():
pass
print(type(f()))
print(type(1J))
import re
sentence = 'Learn Python Programming'
test = re.match(r'(.*) (.*?) (.*)', sentence)
print(test.group())
a = [1,2,3,None,(),[],]
print( len(a))
print (abc)
num = '5'*'5'
list1 = [ 'Tech', 404, 3.03, 'Beamers', 33.3 ]
print (list1[1:3])
def a(b, c, d):
pass
print(a(1,2,3))
tuple1 = (1231, 'griet',[40,90] )
print (tuple1 * 2)
k=3/5
print(type(1/2))
x = True #False
y = False #True
z = False #True
if not x or y:
print (1)
elif not x or not y and z:
print( 2)
elif not x or y or not y and x:
print (3)
else:
print( 4)
test_list = [1, 5, 5, 5, 5, 1]
max = test_list[0]
indexOfMax = 0
for i in range(1, len(test_list)):
if test_list[i] > max:
max = test_list[i]
indexOfMax = i
print(indexOfMax)
test_list = [1,5,10,19,55,30,55,99]
test_list.pop(5)
test_list.remove(19)
test_list.remove(55)
test_list.remove(55)
print(test_list)
test_list.remove(5)
test_list.remove(19)
test_list.remove(55)
print(test_list)
for n in range(1, 6, 1):
print((str(n)+ ' ')*5)
class A:
def __init__(self):
self.a = 1
self.__b = 1
def getY(self):
return self.__b
# def show(self):
# print(self.a, self.__b)
obj = A()
obj.a = 45
print(obj.a)
#print(obj.show()) |
6e9602dd9d4b8a88ed477bf2e4024f851c891565 | simonalford42/Kepner-sparse-nn | /x_net.py | 6,543 | 3.5 | 4 | from __future__ import division
import numpy as np
import fractions
def extended_mixed_radix_network(radix_lists):
"""
Creates an X-net sparse network topology from the input parameters using Ryan's
Extended Mixed-Radix method. See the documentation for a full
explanation of what is going on.
Inputs:
radix_lists - A list of lists of radices to be used for the [possibly extended]
mixed radix system. The number of entries is the number of layers in the
network W that is output.
Returns:
layers - A list of numpy arrays where the i'th entry is the weight matrix W_i
for the i'th layer.
info - A dict containing info about the layers with the following key/values:
shape: a tuple containing the number of neurons for each layer. NOTE:
this includes the input and output layers. as a result,
len(shape) = len(layers) + 1. That is, layers doesn't give the input weights.
For the EMR method, the number of neurons is the same for each layer.
paths: the number of possible paths between each input and output neuron.
sparsity: the sparsity of the network (fraction of entries which are zero)
connections_per_neuron: the average number of outgoing connections per neuron
note that sparsity =
connections_per_neuron * num_neurons / total_connections_possible
"""
num_layers = sum(len(radix_list) for radix_list in radix_lists)
# this is the number of neurons per layer.
num_neurons = np.prod(radix_lists[0])
# for all but last radix list, product of radices must equal num_neurons
if not np.all(
[num_neurons == np.prod(radix_list) for radix_list in radix_lists[:-1]]):
raise ValueError('Product of radices for each radix list must equal'
+ 'number of neurons from first radix list for all but last radix list')
# for last radix list, product of radices must divide num_neurons
if num_neurons % np.prod(radix_lists[-1]) != 0:
raise ValueError('Product of radices for last radix list must divide'
+ 'number of neurons from first radix list')
# the actual math part
# The N x N identity matrix, used for constructing permutation matrices
I = np.identity(num_neurons)
# calculate info
shape = tuple([num_neurons] * (num_layers + 1))
paths = np.prod([np.prod(radix_list) for radix_list in radix_lists[1:]])
flattened_radices = [radix for radix_list in radix_lists for radix in radix_list]
connections_per_neuron = np.average(flattened_radices)
total_neurons = np.sum(shape[:-1])
total_connections_possible = num_neurons * num_neurons * num_layers
sparsity_one = 1 - connections_per_neuron * total_neurons / total_connections_possible
layers = [] # the output list containing W_i's
# make layers
for radix_list in radix_lists:
place_value = 1
for radix in radix_list:
layer = np.sum(
[np.roll(I, -j * place_value, axis=1) for j in range(radix)], axis=0)
layers.append(layer)
place_value *= radix
# sparsity calculated manually (much slower, should be part of tests instead
# of in official method
sparsity_two = (sum(np.count_nonzero(layer==0) for layer in layers) /
sum(layer.size for layer in layers))
assert sparsity_one == sparsity_two
return layers, {'shape': shape, 'paths': paths, 'connections_per_neuron': connections_per_neuron, 'sparsity': sparsity_one}
def kronecker_emr_network(radix_lists, B):
"""
Creates a sparse network topology using the Kronecker/EMR method. First calls
extended_mixed_radix_network(radix_lists). This network is then expanded via
kronecker product to fill the fully connected structure defined by B.
Inputs:
radix_lists - A list of lists of radices to be used for the [possibly extended]
mixed radix system. The number of entries is the number of layers in the
network W that is output.
B - a list of integers giving the number of neurons per layer of the
superstructure into which the EMR network is being Kroneckered.
Returns:
layers - A list of numpy arrays where the i'th entry is the weight matrix W_i
for the i'th layer.
info - A dict containing info about the layers with the following key/values:
shape: a tuple containing the number of neurons for each layer. NOTE:
this includes the input and output layers. as a result,
len(shape) = len(layers) + 1. That is, layers doesn't give the input weights.
For the EMR method, the number of neurons is the same for each layer.
paths: the number of possible paths between each input and output neuron.
sparsity: the sparsity of the network (fraction of entries which are zero)
connections_per_neuron: the average number of outgoing connections per neuron
Note that
sparsity = onnections_per_neuron * num_neurons / total_connections_possible
"""
emr_layers, info = extended_mixed_radix_network(radix_lists)
num_layers = len(emr_layers)
emr_shape, emr_paths, emr_connections_per_neuron = info['shape'], info['paths'],\
info['connections_per_neuron']
shape = [emr_shape[i] * B[i] for i in range(len(emr_layers))]
# the first and last numbers in B do not add paths, but increase the
# number of input and output neurons.
paths = np.prod(B[1:-1])
# check valid input for B
if len(B) - 1 != num_layers:
raise ValueError('Incorrect lengths of N, B parameters')
# make the B graph to kronecker with emr_layers
B_layers = [np.ones((B[i], B[i+1])) for i in range(len(B)-1)]
expanded_layers = [np.kron(B_layer, emr_layer)
for (B_layer, emr_layer) in zip(B_layers, emr_layers)]
"""
# calculate info statistics
connections_per_neuron = (sum(shape[i]*connections_per_neuron*B[i+1]
for i in range(num_layers)) / sum(shape[:-1]))
total_neurons = np.sum(shape[:-1])
total_connections_possible = sum(shape[i]*shape[i+1] for i in range(num_layers))
sparsity_one = 1 - connections_per_neuron * total_neurons \
/ total_connections_possible
sparsity_two = (sum(np.count_nonzero(layer==0) for layer in expanded_layers) \
/ sum(layer.size for layer in expanded_layers))
assert sparsity_one == sparsity_two
"""
# return expanded_layers, {'shape': shape, 'paths': paths, 'connections_per_neuron': connections_per_neuron, 'sparsity': sparsity}
return expanded_layers, {}
if __name__ == '__main__':
radix_lists = [[2,2]]
B = [1,2,3]
# layers = extended_mixed_radix_network(radix_lists)
kron_network = kronecker_emr_network(radix_lists, B)
|
4f00650a3f19c044246359024d49c9a9377ea612 | NasNaz/PythonStdioGames | /barebones/bitmapmessage-barebones.py | 1,053 | 3.9375 | 4 | """Bitmap Message (barebones version)
by Al Sweigart al@inventwithpython.com
Displays a text message according to the provided bitmap image."""
import sys
bitmap = """
********
********
********
********
********
********
********
********
********
********************
********************
**************************
******************** **
******************** **
******************** **
*************************
********************
******************
"""
print('Bitmap Message, by Al Sweigart al@inventwithpython.com')
print('Enter the message to display with the bitmap.')
message = input('> ')
# Loop over each line in the multi-line bitmap:
for line in bitmap.splitlines():
# Loop over each character in the line:
for i in range(len(line)):
if line[i] == ' ':
# Print an empty space since there's a space in the bitmap:
print(' ', end='')
else:
# Print a character from the message:
print(message[i % len(message)], end='')
print() # Print a newline.
|
54ec75d554bea29993f9082ee3adfa29e5fd6e59 | akiran1234/referencedocs | /Python/08_Loops.py | 2,246 | 4.4375 | 4 | #################################################################################################################
# Loops are used to execute a block of code repeatedly.
# we have while loop and for loop for repetitive execution.
# The block is iterated based on condition, until it is true and exits when the condition fails.
#################################################################################################################
# While loop execute this in terminal
count=0
while (count<=5): # if we take a condition which never becomes false it will become infinite loop.
print("Executing while statement and iteration=",count)
count+=1
else:
print("Python supports else block for loops.") # else block will be executed after completing while loop iterations
print("Else block will be executed after completing while loop iterations")
print( " 1 **********************" )
#################################################################################################################
# For loop - execute this in terminal
# To traverse and print data structures like- list, tuple & set for loop is used.
# for loop supports only list, tuple and set.
# Python doesn't support traditional for loops with loop variable. Ex: C,C++ and Java.
list1=[1,2,4,'abc',34.45]
for x in list1:
print("Iteration in for loop,printing list values=",x)
print("printing in for loop")
print( " 2 **********************" )
#################################################################################################################
# for loop with tuple
tuple1=[1,2,4,'abc',34.45]
for y in tuple1:
print("Iteration in for loop,printing list values=",y)
print( " 3 **********************" )
#################################################################################################################
# for loop with Set
# Since Set is not based on indexing for loop will print items randomly in any order.
s1={10,20,30,'kiran','kumar',12.34}
for abc in s1:
print('Set iteration using for loop:',abc)
else:
print("for loop supports else block which will be executed at end after iterating for loop elements")
|
bbc3ac96f7764c7b84f7a3545800820ec9d3fc15 | tmondal/pythonProjects | /game/pong/new_football.py | 6,519 | 3.515625 | 4 | import pygame
import random,sys
import math
from pygame.locals import*
#----------------- COLOR DEFINING ---------------------
BLACK = (0 , 0 , 0)
WHITE = (255 , 255 , 255)
RED = (255 , 0 , 0)
BLUE =(0,0,255)
GREEN = (0 , 255 , 0)
#----------------- CLASS AND FUNCTION ---------------
class Player:
change_x = 0
change_y = 0
def __init__(self, (x, y),color):
self.x = x
self.y = y
self.color = color
self.thickness = 0
self.angle = 0
self.speed = 0
def display(self):
pygame.draw.rect(screen,self.color,(int(self.x),int(self.y),20,20))
def update(self):
self.x += self.change_x
self.y += self.change_y
def change_pos(self,x,y):
self.x += x
self.y += y
class Line:
def __init__(self,color,(x,y),width,height):
self.color = color
self.x= x
self.y = y
self.width = width
self.height = height
def display(self):
pygame.draw.rect(screen,self.color,(int(self.x),int(self.y),self.width,self.height))
class Oposit_player:
def __init__(self, (x, y), size):
self.x = x
self.y = y
self.size = size
self.color = (255,0,0)
self.thickness = 0
self.angle = 0
self.speed = 0
def display_user(self):
pygame.draw.circle(screen, self.color, (int(self.x),int(self.y)), self.size, self.thickness)
#----------------------- Functions ------------------------------
def main_oppo_move(p1,p2):
dx = p1.x - p2.x
dy = p1.y - p2.y
dist = math.hypot(dx, dy)
tangent = math.atan2(dy, dx)
angle = 0.5 * math.pi + tangent
angle1 = 2*tangent - p1.angle
(p1.angle) = (angle1)
p1.x -= 0.2*math.sin(angle)
p1.y += 0.2*math.cos(angle)
def Distance(p,b):
dx = p.x - b.x
dy = p.y - b.y
s = dx*dx + dy*dy
distance = math.sqrt(s)
return distance
##class wall(pygame.sprite.Sprite):
##
## def __init__(self,x,y,width,height):
##
## pygame.sprite.Sprite.__init__(self)
##
## self.image = pygame.Surface([width,height])
## self.image.fill(GREEN)
##
## self.rect = self.image.get_rect()
##
## self.rect.x = x
## self.rect.y = y
pygame.init()
screen_width = 1200
screen_height = 600
font = pygame.font.Font(None, 36)
screen = pygame.display.set_mode([screen_width, screen_height],0,32)
background = pygame.image.load("fground.jpg").convert()
clock = pygame.time.Clock()
#---------------------- LINE DRAWING -----------------------------
all_line =[]
line_1 = Line( WHITE,(40 , 20),1 , screen_height - 40)
line_2 = Line( WHITE,((screen_width / 2) , 20),1 , screen_height - 40)
line_3 = Line( WHITE,(screen_width - 40 , 20),1 , screen_height - 40)
line_4 = Line( WHITE,(40 , 20) , screen_width - 80 ,2)
line_5 = Line( WHITE,(40 , screen_height - 20) , screen_width - 80 ,2)
all_line.append(line_1)
all_line.append(line_2)
all_line.append(line_3)
all_line.append(line_4)
all_line.append(line_5)
#---------------------- PLAYER POSITIONING -----------------------
relative = screen_height / 2
x_d = screen_width / 4
y_d = relative / 2
all_player =[]
all_opposit_player =[]
player_1 = Player((20,relative),WHITE)
player_2 = Player((x_d,y_d),BLUE)
player_3 = Player((1.5*x_d,relative),BLUE)
player_4 = Player((x_d,relative + y_d),BLUE)
ball = Player((screen_width / 2, relative),BLACK)
all_player.append(player_1)
all_player.append(player_2)
all_player.append(player_3)
all_player.append(player_4)
opposit_1 = Player((screen_width - 40,relative),WHITE)
opposit_2 = Player((screen_width - x_d,y_d),BLUE)
opposit_3 = Player((screen_width - 1.5*x_d,relative),BLUE)
opposit_4 = Player((screen_width - x_d,relative + y_d),BLUE)
all_opposit_player.append(opposit_1)
all_opposit_player.append(opposit_2)
all_opposit_player.append(opposit_3)
all_opposit_player.append(opposit_4)
#--------------------- PLAYER SELECTION ---------------------------
#--------------------- MAIN GAME LOOP -----------------------------
def main():
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
## elif event.type == pygame.KEYDOWN:
## if event.key == pygame.K_s:
## ball_move(player_ball,oppo_player)
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
player.change_pos(0,-8)
if event.key == pygame.K_DOWN:
player.change_pos(0,8)
if event.key == pygame.K_RIGHT:
player.change_pos(8,0)
if event.key == pygame.K_LEFT:
player.change_pos(-8,0)
## elif event.type == pygame.KEYUP:
## if event.key == pygame.K_UP:
## player.change_pos(0,0)
## if event.key == pygame.K_DOWN:
## player.change_pos(0,0)
## if event.key == pygame.K_RIGHT:
## player.change_pos(0,0)
## if event.key == pygame.K_LEFT:
## player.change_pos(0,0)
screen.blit(background,(0,0))
for player in all_player:
player.display()
#-------------------- Player selection----------------------------
dist = []
for p in all_player:
d = Distance(p,ball)
dist.append(d)
min_dist = min(dist)
i = dist.index(min_dist)
player = all_player[i]
#------------------- Opposit player selection --------------------
distance = []
for p in all_opposit_player:
d1 = Distance(p,ball)
distance.append(d1)
min_dist = min(distance)
i = distance.index(min_dist)
opposit_player = all_opposit_player[i]
main_oppo_move(opposit_player,ball)
for p in all_opposit_player:
p.display()
for line in all_line:
line.display()
ball.display()
player.update()
clock.tick(60)
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
main()
|
3b69f98ee37e6127a3b893837613c51378b555c6 | ganasn/LPTHW | /ex47/LPTHW/ex38.py | 1,308 | 3.890625 | 4 | # Exercise 38 - Doing Things to Lists
ten_things = 'Apples Oranges Crows Phone Light Sugar'
print 'That doesn\'t add to 10'
stuff = ten_things.split(' ')
more_stuff = ['Day', 'Night', 'Song', 'Frisbee', 'Corn', 'Banana', 'Girl', 'Boy']
# Add more items to stuff from more_stuff until there are 10 items in stuff
#Stuff would initially have 6 - from ten_things
while len(stuff) != 10:
next_one = more_stuff.pop()
print 'Adding', next_one
# adding to the end of list <stuff>
stuff.append(next_one)
print 'There are %d items now' % len(stuff)
print 'Now it\'s done:', stuff
print 'More ops with <stuff> variable'
#get second item
print stuff[1]
#get last item
print stuff[-1]
#move first item off stuff. stuff doesn't have 10 items any longer
#this is the last item - LIFO - not the first item
print stuff.pop()
#trying pop(<ordinal>)
print stuff.pop(1)
#Adds stuff to a another string which is just ''
#That was obviously incorrect. This actually joins the items in stuff list with the string ''
#print ''.join(stuff)
print ' '.join(stuff)
#Adds elements 4 through 6 (or 5?) from stuff to a string that's '#'
#As expected, only 2 elements are considered - the last element is NOT considered
#From previous line, this would join elements 4 & 5 with a '#'
print '#'.join(stuff[3:5]) |
8568b80bb98c6cf00d785f02df7d52a348602e97 | cjc77/Recursions | /medianValues.py | 1,168 | 3.9375 | 4 | #! usr/bin/env python3
# Finds Median Value of input
import random, numpy, time
def if_even(x):
global first
if len(x) == 2:
return (x[0] + x[1]) / 2
if first:
first = False
return if_even(x[1:])
elif not first:
first = True
return if_even(x[:-1])
def if_odd(x):
global first
print(x)
if len(x) == 1:
return float(x[0])
if first:
first = False
return if_odd(x[1:])
elif not first:
first = True
return if_odd(x[:-1])
usr = int(input("How many digits?: "))
start, first = time.time(), True
L = [random.randrange(usr) for x in range(usr)]
L.sort()
if len(L) % 2 == 0:
print("OK", "My function:", if_even(L), "Numpy:",
numpy.median(numpy.array(L)), "Time:", time.time() - start,
sep='\n')
if if_even(L) != numpy.median(numpy.array(L)):
print("Error")
elif len(L) % 2 == 1:
print("OK", "My function:", if_odd(L), "Numpy:",
numpy.median(numpy.array(L)), "Time:", time.time() - start,
sep='\n')
if if_odd(L) != numpy.median(numpy.array(L)):
print("Error")
|
15d75bfd3c00d16070b41935297d4f9a6c8456d9 | hot-tangcong/test1 | /6.2.4.py | 539 | 3.75 | 4 | # 继承中的构造函数
class Animal():
def __init__(self):
print("Animal")
class Crawel(Animal):
def __init__(self):
print("Crawel")
class Dog(Crawel):
def __init__(self):
print("I am init in dog")
# 猫没有构造函数
class Cat(Crawel):
pass
# 实例化的时候,自动调用了Dog的构造函数
kk = Dog()
# 此时应该自动调用构造函数,因为Cat没有构造函数,所以查找父类的构造函数
# 在Crawel中查找到了构造函数,则停止向上查找
c = Cat() |
3183d31a1b6e5be2ff242a92242b394ea306347b | ksu-hmi/Baby-Child-Gender-Tracker | /GenderReveal.py | 2,055 | 3.8125 | 4 | #import libraries first
import statistics as s
#add constants next
Moms = {'Ronda Broome':'***','Betty White':'***','Susan Black':'***', 'Sharon Stone':'***', 'Mary Joseph':'***', 'Melissa Smith':'***'}
Babies = {'Paul Joseph':["Male"],
'Barbara Black':["Female"],
'Michelle Stone':["Binary"],
'Molly Smith':["Non-Binary"],
'Draymond White':["Male"],
'Raven Broome':["Female and loves both her mom and dad"]
}
#now define functions
def enterBaby():
nameToEnter = input('Baby name: ')
SexToEnter = input('Age of Baby: ')
if nameToEnter in Babies:
print('Adding age for' "," + nameToEnter)
Babies[nameToEnter]
print(str(nameToEnter)+ ',' ' is this gender:')
print(Babies[nameToEnter])
else:
print('Baby not found. Please check your spelling or call Mom ASAP!')
def removebaby():
nameToRemove = input('Who do you want to remove? ')
if nameToRemove in Babies:
print('Removing '+nameToRemove)
del Babies[nameToRemove]
print(Babies)
else:
print('Baby not found.')
def main():
print("User: " + login)
print("""
Welcome to our HMI 7540 Baby Gender Tracker. See instructions below!
[1] - Enter Baby Name
[2] - Remove Baby Name
[3] - Exit
""")
action = input('What would you like to do? (Enter a number) ')
if action == '1':
#print('1 selected')
enterBaby()
elif action == '2':
#print('2 selected')
removebaby()
elif action == '3':
#print('4 selected')
exit()
else:
print('Valid option not selected.') #need to cause it to reprompt
login = input('Name_of_Mother: ')
password = input('Password: ')
if login in Moms:
if Moms[login] == password:
print('Welcome,',login)
#now run the code
while True:
main()
else:
print('Invalid password.')
else:
print('Congrats. Expecting Mom!')
|
8594e973d1e5573312a10f2f0b8bf4dda2512c9a | gukiub/portifolio | /scripts python/Uri exercises/exercUri18.py | 594 | 3.640625 | 4 | numero = int(input())
if 0 < numero < 1000000:
print(numero)
x = numero // 100
print('{} nota(s) de R$ 100,00'.format(x))
y = numero % 100
z = y // 50
print('{} nota(s) de R$ 50,00'.format(z))
w = y % 50
q = w // 20
print('{} nota(s) de R$ 20,00'.format(q))
u = w % 20
i = u // 10
print('{} nota(s) de R$ 10,00'.format(i))
v = u % 10
n = v // 5
print('{} nota(s) de R$ 5,00'.format(n))
j = v % 5
h = j // 2
print('{} nota(s) de R$ 2,00'.format(h))
a = j % 2
b = a // 1
print('{} nota(s) de R$ 1,00'.format(b))
|
cfb59ec847ecac391de5b71a8bf1e67397996237 | MaryanneNjeri/pythonModules | /.history/duplicateleet_20200810095940.py | 293 | 3.6875 | 4 | def duplicate(nums):
newDict = {}
finalArr = []
for i in nums:
if i in newDict:
newDict[i] +=1
else:
newDict[i] = 1
for i in newDict:
if newDict[i] == 2:
finalArr.append(newDict[i])
return finalArr
duplicate([]) |
69b5d1263958d92d31c4cb6cb2cf6f5c1edcf5cb | alexlikova/Python-Basics-SoftUni | /8. Python Basics EXAMS/4. Programming Basics Online Exam - 9 and 10 March 2019/02. Football Results.py | 929 | 3.953125 | 4 | win, loss, equal = 0, 0, 0
for _ in range(3):
host, guest = input().split(':')
if host > guest:
win += 1
elif host < guest:
loss += 1
else:
equal += 1
print(f'Team won {win} games.\nTeam lost {loss} games.\nDrawn games: {equal}')
"""result_first_game, result_second_game, result_third_game = [input() for _ in range(3)]
win = 0
lose = 0
equal = 0
if result_first_game[0] > result_first_game[2]:
win += 1
elif result_first_game[0] < result_first_game[2]:
lose += 1
else:
equal += 1
if result_second_game[0] > result_second_game[2]:
win += 1
elif result_second_game[0] < result_second_game[2]:
lose += 1
else:
equal += 1
if result_third_game[0] > result_third_game[2]:
win += 1
elif result_third_game[0] < result_third_game[2]:
lose += 1
else:
equal += 1
print(f"Team won {win} games.\nTeam lost {lose} games.\n"
f"Drawn games: {equal}")""" |
4d749f10a92ab7b057c3641ca066689cd2bfc9e4 | skytreesea/do-it-python | /05/feasibility/basic_feasibility_suc.py | 1,715 | 3.5 | 4 | ##### 공기업 설립 시 타당성 조사를 위한 경상수지 비교 기본 프로그램 #######
#usecsv의 값을 저장하도록 함
import csv, os
def writecsv(filename, the_list):
with open(filename,'w',newline='') as f:
a=csv.writer(f, delimiter=',')
a.writerows(the_list)
# 현행방식과 공기업 방식의 인플레이션 인덱스 부여
# 물가상승률
price_index = .011
# 인건비 상승률
salary_increase = 0.0414
# 새 회사의 인건비 상승률
salary_increase_new_company = 0.0371
# 수입증가율
income_increase = 0
start_year = 2022
#현행방식
wage = int(input("[현행] 첫 해 총인건비 입력하세요(단위: 천원)"))
cost_operation = int(input("[현행] 첫 해 총운영비 입력하세요(단위: 천원)"))
#공단방식23
new_wage = int(input("[공기업(공단)] 첫 해 총인건비 입력하세요(단위: 천원)"))
new_cost_operation = int(input("[공기업(공단)] 첫 해 총운영비 입력하세요(단위: 천원)"))
list_of_initial_value = [wage, cost_operation, new_wage, new_cost_operation]
def inflator(intinial_value, increasing_ratio, num_years):
new_list =[]
for i in range(num_years):
new_list.append(round(intinial_value*(1+increasing_ratio)**i))
return new_list
result_list = []
result_list.append([str(i+ start_year)+'년' for i in range(5) ])
result_list.append(inflator(wage,salary_increase, 5))
result_list.append(inflator(cost_operation,price_index, 5))
result_list.append(inflator(new_wage,salary_increase_new_company, 5))
result_list.append(inflator(new_cost_operation,price_index, 5))
print(result_list)
os.chdir(r'저장하고 싶은 파일 경로 ')
writecsv('feasibility_basic.csv',result_list) |
df9e266196af37f7115709bb8da592558f9bf7f0 | kirill432111/python | /les1/массивы/4 массивы.py | 777 | 3.953125 | 4 | def quicksort(list, start, end):
if end - start > 1:
p = partition(list, start, end)
quicksort(list, start, p)
quicksort(list, p + 1, end)
def partition(list, start, end):
pivot = list[start]
i = start + 1
j = end - 1
while True:
while (i <= j and list[i] <= pivot):
i = i + 1
while (i <= j and list[j] >= pivot):
j = j - 1
if i <= j:
list[i], list[j] = list[j], list[i]
else:
list[start], list[j] = list[j], list[start]
return j
list = input('Введите числа: ').split()
list = [int(x) for x in list]
quicksort(list, 0, len(list))
print('Отсортированный список: ', end='')
print(list) |
db4cbc787f53f213d2679742aecaf3c9eadbe2de | vanshikasanghi/dv.pset | /0052 Longest Collatz Sequence /collatzseq.py | 515 | 4.1875 | 4 | number = 13 #to check for the series
counterfinal = 0
finalnum = 0
while number < 1000000 :
counter = 0
num = number #for the sequence, to check for each number
while num > 1 : #finding one sequence
if (num%2==0) :
num = num/2
counter = counter + 1
else :
num = (3*num)+1
counter = counter + 1
if (counter > counterfinal) : #checking for the longest sequence
counterfinal = counter
finalnum = number
number = number + 1
print("Longest Collatz Sequence starts with : ")
print(finalnum)
|
c90e94c1e6f60e0e890fc5134b8a60ed7d88beca | anthologion/psalter | /psalter.py | 1,596 | 3.796875 | 4 | from bible.bible import TomlBible
from datetime import datetime,timedelta
class Psalter(object):
def __init__(self):
self._bible = TomlBible()
def get_psalm(self, number):
return self._bible["Psalm %d" % int(number)]
def cycle_psalms_weekly(psalmlist, batch_size=1, weekday=None, start_day = 6):
"""
Get a chunck of psalms for a day from a list. Cycles based on the current
weekday. The cycle resets on start_day
@type psalmlist: List
@param psalmlist: A list of psalms.
@type batch_size: integer
@param batch_size: The number of psalms to include in a batch
@type weekday: integer
@param weekday: The day of the week to produce output for. If this is None
then use today.
@type start_day: integer
@param start_day: The day to restart the cycle on.
"""
if weekday is None:
today = datetime.today().weekday()
else:
today = weekday.weekday()
if today is start_day:
today = 0
else:
today = today%start_day
start_psalm = ((today*batch_size)%(len(psalmlist)))
end_psalm = start_psalm + batch_size
print today, start_psalm, end_psalm
if end_psalm > len(psalmlist):
return psalmlist[start_psalm:] + psalmlist[:(end_psalm-len(psalmlist))]
else:
return psalmlist[start_psalm:end_psalm]
if __name__ == "__main__":
base = datetime.today()
date_list = [base + timedelta(days=x) for x in range(0,11)]
for day in date_list:
print day
print cycle_psalms_weekly([121,134],1, day)
print Psalter().get_psalm(3)
|
09fda303f38d2cc9ad1f8da62b74d2b38310187e | sn1572/RentOrBuy | /RentOrBuy/loan_modified.py | 4,224 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 4 10:54:14 2018
@author: User68
"""
class time_func:
def __init__(self, function=None):
self.function = function
self.time = 0
def set_function(function):
self.function = function
def value(self):
val = self.function.iterate(self.time)
self.time += 1
return(val)
class const_rate:
def __init__(self, rate):
self.rate = rate
def iterate(self, time):
return(self.rate)
def loan_any_length(loan_amt, down_payment, payment, interest_rate, rent, housing_market_growth, investment_growth):
capital_gains = .15; property_tax = .0078
principle = loan_amt-down_payment
home_value = loan_amt
alternative = 0
time = 0
paid = 0
taxes = 0
while principle >0:
pay = payment.value()
ren = rent.value()
paid += pay + property_tax*home_value/12
taxes += property_tax*home_value/12
principle = (1+interest_rate.value())*principle-pay
home_value = (1+housing_market_growth.value())*home_value
alt_val = pay-ren
if time == 0:
alternative = down_payment+alt_val
assert (pay >= ren), "Housing payment must be greater than rent payment."
else:
alternative = (1+investment_growth.value())*alternative+alt_val
time += 1
print("Loan: "+str(loan_amt)+" Down payment: "+str(down_payment))
print("Duration: "+str(time)+" months.")
print("Total amount paid with down payment: "+str(paid+down_payment))
print("Buy home - Appreciation of home minus taxes paid: "+str(home_value-loan_amt-taxes))
print("Rent - Appreciated investments minus capital gains: "+str((1-capital_gains)*alternative))
if home_value-loan_amt >= alternative:
print("Conclusion: home loan is a better deal.")
else:
print("Renting is a better deal.")
def bank_loan_any_length(loan_amt, down_payment, payment, interest_rate, rent, housing_market_growth, investment_growth, term):
#capital_gains = .15; property_tax = .0078
capital_gains = .15; property_tax = 0
init_principle = (1+interest_rate.value()*12)**(term-1)*(loan_amt-down_payment)
principle = init_principle
home_value = loan_amt
alternative = 0
time = 0
paid = 0
taxes = 0
while principle >0:
if time > term*12:
print("Time has exceeded term.")
print(principle)
return(None)
pay = payment.value()
ren = rent.value()
paid += pay + property_tax*home_value/12
taxes += property_tax*home_value/12
principle -= pay
home_value = (1+housing_market_growth.value())*home_value
alt_val = pay-ren
if time == 0:
alternative = down_payment+alt_val
assert (pay >= ren), "Housing payment must be greater than rent payment."
else:
alternative = (1+investment_growth.value())*alternative+alt_val
time += 1
print("Loan: "+str(loan_amt)+" Down payment: "+str(down_payment)+" Monthly payment: "+str(pay))
print("Duration: "+str(time)+" months.")
print("Total amount paid with down payment: "+str(paid+down_payment))
print("Buy home - Appreciation of home minus taxes paid: "+str(home_value-init_principle-taxes))
print("Rent - Appreciated investments minus capital gains: "+str((1-capital_gains)*alternative))
if home_value-init_principle-taxes >= ((1-capital_gains)*alternative):
print("Conclusion: home loan is a better deal.")
else:
print("Renting is a better deal.")
if __name__ == '__main__':
loan_amt = 200000
down_payment = 50000
payment = time_func(const_rate(2000))
interest_rate = time_func(const_rate(.0425/12))
housing_market_growth = time_func(const_rate(.054/12))
investment_growth = time_func(const_rate(.054/12))
rent = time_func(const_rate(1250))
print(bank_loan_any_length(loan_amt, down_payment, payment, interest_rate, rent, housing_market_growth, investment_growth, term=15))
#print(loan_any_length(loan_amt, down_payment, payment, interest_rate, rent, housing_market_growth, investment_growth))
|
d160e0c603b72e3b6c9453057b0f9bfff6acc3fa | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/49e9e52336a447728d059a314eff958a.py | 603 | 3.578125 | 4 | # -*- coding: utf-8 -*-
def hey(message):
if isShouting(message):
return "Whoa, chill out!"
elif isQuestion(message):
return "Sure."
elif isSilent(message):
return "Fine. Be that way!"
else:
return "Whatever."
def isShouting(message):
capcount = 0
lowcount = 0
for c in message:
if c.isupper():
capcount += 1
elif c.islower():
lowcount += 1
return capcount > lowcount
def isQuestion(message):
return message.endswith("?")
def isSilent(message):
return (not message or message.isspace())
|
d3cc4915e52f1903af21b7a24afbfbb941be35b1 | swethatech/thinkpython | /chapter-1.py | 418 | 3.78125 | 4 | #help(chapter-1)
'''class interpreter:
def __init__(self):
"online help utility"
help(interpreter)
help('print')
#math
min =43.5
hr =min / 60
km_per_mile=1.61
km = 10
miles =km/km_per_mile
print("miles:",miles)
print("min:",min)
print("hr:",hr)
pace = min / miles
mph = miles / hr
print('Pace in minutes per mile:', pace)
print('Average speed in mph:', mph)'''
|
8b0e01f62abc3844574b18019b3a8f4d834357e4 | DanielMarquesz/AD1_FP | /quesato1.1.py | 1,369 | 4.46875 | 4 | '''
Faça um programa que leia strings da entrada padrão, até que a string vazia (“”) seja digitada.
Caso a primeira string lida seja vazia, escreva a mensagem “Nenhuma String Não Vazia Foi Lida!!!”. Caso contrário escreva:
(1) Qual a string que tem maior comprimento; caso haja empate escreva a primeira delas;
(2) Qual a string possui mais dígitos, isto é, contém caracter(es) na string “0123456789”.
Caso haja empate escreva a última delas. Caso nenhuma possua dígitos escreva: “Nenhuma String Contém Dígito!!!”
(3) Qual a quantidade de strings formadas apenas de vogais minúsculas e sem acento, isto é, contidas na string “aeiou”.
'''
def maiorPalavra(entrada):
palavraAtual = entrada
if len(palavraAtual) < len(entrada): # Verifica a maior string digitada
stringAtual = entrada
print('Primeira de Maior Comprimento: ',stringAtual)
stringAtual = 0
palavra = input() #lê a primeira palavra
if palavra == "": # Verifica se os valores são diferentes de Vazio
print("Nenhuma String Não Vazia Foi Lida!!!")
else:
while palavra != "":
palavraAtual = palavra
if len(palavraAtual) > len(palavra): # Verifica a maior string digitada
stringAtual = palavra
print('Primeira de Maior Comprimento: ',stringAtual)
palavra = input()
|
f8ebd30d3dc0eb5261080be8612c8bbcbe72d920 | 27abhi/maze-with-moveable-object | /maze.py | 2,906 | 4.21875 | 4 | # MAZE DESIGN & IMPLEMENTATION WITH KEYBOARD CONTROLLED MOVEABLE OBJECT (USING TURTLE FOR GRAPHICS):
#===================================================================================================
import numpy as np
import turtle
import random
window = turtle.Screen()
window.bgcolor('black')
window.screensize(600,600)
class Pen(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.shape('square')
self.color('white')
self.penup()
self.speed(0)
alex = turtle.Turtle()
alex.setpos(-216,288)
alex.right(90)
alex.color('yellow')
alex.penup()
alex.shape('circle')
walls=[]
#maze layout below can be manually modified:
layout = [
"XXX XXXXXXXXXXXXXXXXXXXX",
"XXX XXX XXXXXXXXXXX",
"XXX XXXXXXX XXXXXX",
"XXX XXXXXXXXXXX XXXXXX",
"XXX XXXXXX XX",
"XXXXXX XXXXXXXXX XXX XX",
"XXXXXX XXX XX",
"XXXXXXX XXXXXXXXXXXXX X",
"XXXXXXX XXXXXXXXXX X",
"XXXXXXX XX XXXXXXX X",
"XXX XX XXXXXXX XXX X",
"XX XXXXXX XXXX XXXXX",
"XX XXXXXXXXXX XX XXXXXXX",
"X XXXXXXX XXXXXXX",
"XX X XXXX XXXXXXXXX",
"XX XX XXX XXXX XXXXXXXXX",
"XX XX XX X XXXXX",
"XX XXX XXXXXXXXXXX XXXXX",
"XXXXXX XXXXXXXXXXX XXXXX",
"XXXXXX XXXXXXXXXX XXXXX",
"XXX XXX XXXXXXXXXX XXXXX",
"XXX XXXXX XXXXX",
"XXXXXXXXXXXXXXXXXX XXXXX",
]
#maze generating function:
def setup_maze(input_layout):
for y in range(len(input_layout)):
for x in range(len(input_layout[y])):
character = input_layout[y][x]
screen_x = -288 + (x * 24)
screen_y = 288 - (y * 24)
if character =="X":
pen.goto(screen_x, screen_y)
walls.append((screen_x, screen_y))
pen.stamp()
pen = Pen()
setup_maze(layout)
#keyboard binding definitions for moving the object:
def h1():
new_x_up = round(alex.xcor())
new_y_up = round(alex.ycor() + 24)
if(new_x_up, new_y_up) not in walls:
alex.goto(new_x_up, new_y_up)
def h2():
new_x_left = round(alex.xcor() - 24)
new_y_left = round(alex.ycor())
if(new_x_left, new_y_left) not in walls:
alex.goto(new_x_left, new_y_left)
def h3():
new_x_right = round(alex.xcor() + 24)
new_y_right = round(alex.ycor())
if(new_x_right, new_y_right) not in walls:
alex.goto(new_x_right, new_y_right)
def h4():
new_x_down = round(alex.xcor())
new_y_down = round(alex.ycor() - 24)
if(new_x_down, new_y_down) not in walls:
alex.goto(new_x_down, new_y_down)
window.onkey(h1, "Up")
window.onkey(h2, "Left")
window.onkey(h3, "Right")
window.onkey(h4, "Down")
window.listen()
turtle.mainloop()
while True:
pass
turtle.done()
|
3cefa87c74f1c70eca955aaef412efadd3d8a280 | Gaurav1921/Python3 | /Dictionaries.py | 2,402 | 4.09375 | 4 | """ dictionary is more of a mess unlike lists it is bag of values which don't stay in order and along with that in
dictionaries we also have to label when we add any value """
purse = dict()
purse["money"] = 12 # here money is the label and 12 is the value of that label
purse["candy"] = 3
purse["tissue"] = 75
print(purse) # in dictionaries values are stored inside the curly brackets (in lists we used square brackets)
print(purse["candy"]) # in dictionaries the index is the label while in lists it was the position as 0,1,...
purse["candy"] = purse["candy"] + 2
print(purse)
purse["candy"] = 8 # dictionaries are mutable like lists
print(purse)
""" here we see how many times that name has been shown on the screen/list """
counts = dict()
names = ["csev", "cwen", "csev", "zqian", "cwen"]
for name in names:
if name not in counts:
counts[name] = 1
else:
counts[name] = counts[name] + 1 # 'count[name]' = value of that variable
print(counts)
""" used to check whether the key is present or not """
names = ["csev", "cwen", "csev", "zqian", "cwen"]
if 'zqian' in counts:
x = counts['zqian']
else:
x = 0
z = counts.get('zqian', 0) # go in the counts dictionary lookup for the key name with the default value set to 0
print(z)
""" to get to do the above problem in a easier way we do use get function """
counts = dict()
names = ["csev", "cwen", "csev", "zqian", "cwen"] # in a file we can use split to create a list automatically
for name in names:
counts[name] = counts.get(name, 0) + 1
print(counts)
""" counting pattern """
counts = dict()
line = input("Enter some line:")
words = line.split()
print("Words: ", words)
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)
""" for loop in dictionaries """
counts = {"chuck": 1, "fred": 42, "jan": 100}
for key in counts:
print(key, counts[key])
""" Retrieving lists of keys and values with in-built functions """
jjj = {"chuck": 1, "fred": 42, "jan": 100}
print(list(jjj))
print(jjj.keys())
print(jjj.values())
print(jjj.items()) # gives us both keys and values in from of tuples '()'
""" to print the keys and values without the inbuilt function we use two iteration variables """
jjj = {"chuck": 1, "fred": 42, "jan": 100}
for aa, bb in jjj.items():
print(aa, bb)
|
50ee8d1d8d6aa65a92b95a403eb1da3fd927c76b | Dwyanepeng/leetcode | /findNumberOfLIS_673.py | 878 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : findNumberOfLIS_673.py
# Author: PengLei
# Date : 2019/5/29
'''给定一个未排序的整数数组,找到最长递增子序列的个数。
示例 1:
输入: [1,3,5,4,7]
输出: 2
解释: 有两个最长递增子序列,分别是 [1, 3, 4, 7] 和[1, 3, 5, 7]。
示例 2:
输入: [2,2,2,2,2]
输出: 5
解释: 最长递增子序列的长度是1,并且存在5个子序列的长度为1,因此输出5。
注意: 给定的数组长度不超过 2000 并且结果一定是32位有符号整数。'''
class Solution:
def findNumberOfLIS(self, nums):
max_L = [nums[0]]
len_nums = len(nums)
i = 0
while i < len_nums:
if nums[i] > max_L[-1]:
max_L.append(nums[i])
i += 1
return max_L
s = Solution()
print(s.findNumberOfLIS([1,3,5,4,7])) |
2946a8feeb638c4be4037d2c5e0398492259ca27 | dh-trier/worldcat | /create_publicationtable.py | 9,177 | 3.65625 | 4 | #!/usr/bin/env python3
"""
Script for creating a table with the number of publications per year for each novel in the collection.
Input: html files from worldcat downloaded by gethtmlsworldcat.py.
Output: csv-file
"""
from bs4 import BeautifulSoup as bs
import glob
import os
from os.path import join
import re
import pandas as pd
import logging
# === Parameters ===
#dir=""
#htmlpages = join(dir, "html", "*.html")
# === Functions ===
def read_html(file):
"""
Parsing with Beautiful Soup, see: https://www.crummy.com/software/BeautifulSoup/bs4/doc/
input: html file
output: parsed html
"""
with open(file, "r", encoding="utf8") as infile:
html = infile.read()
html = bs(html, "html.parser")
return html
def get_id(file):
"""
input: file
output: filename (in this case the id of the novel)
"""
base = os.path.basename(file)
id_ext = str(os.path.splitext(base)[0])
id = id_ext.split("_html")[0]
print(id)
return id, id_ext
def test_search_result(html, id):
"""
Prints warning if there are no search results in worldcat and writes warning into log file.
The warning contains the id and the search strings of the title and the author.
input: html file
output: log file
"""
text = "No results match your search"
try:
errors = html.find('div', {'class' : 'error-results'}).get_text()
errors = errors.strip()
search_string = re.search("ti:(.*?)au:(.*?)\'", errors).group()
title = re.sub(" au:(.*?)\'", "", search_string) # extracts search string for the title
title = re.sub("ti:", "", title)
title = re.sub(": ELTeC edition", "", title)
author = re.search("au:(.*?)\'", search_string).group() # extracts search string for the author
author = re.sub("au:", "", author)
author = re.sub("\'", "", author)
if errors.startswith(text):
print(id + ": No search result in worldcat! Please check the spelling of author and title (see log file)!")
logging.warning(id + ": No search result in worldcat! Search strings: title: '" + title + "', author: '" + author + "'")
except:
pass
def create_df_worldcat(html, settings_dict, id_ext):
"""
Takes a html file containing the search result in worldcat and creates a dataframe with hit number (corresponding to the html), hit language and publication year
If there isn't mentioned a year, it will be set to 0 in order to contribute to the total number of publications.
input: html file, settings_dict, id
output: dataframe
"""
df_worldcat = pd.DataFrame(columns=['number', 'itemLanguage', 'year'])
list = html.find_all('tr', {'class' : 'menuElem'}) # list with all hits (still marked up)
for item in list:
number = item.find('div', {'class' : 'item_number'}).get_text()
itemLang = item.find('span', {'class' : 'itemLanguage'}).get_text()
try:
year = item.find('span', {'class' : 'itemPublisher'}).get_text()
year = re.search("[0-9]+", year).group()
except:
year = "0"
print("No publication year found for item " + number + " in file " + str(id_ext))
logging.warning(str(id_ext) + ": No publication year found for item " + number + "!")
df_worldcat = df_worldcat.append({'number': number, 'itemLanguage': itemLang, 'year': year}, ignore_index=True)
#print(df_worldcat)
return(df_worldcat)
def test_lang(df_worldcat, settings_dict):
"""
Tests the language of each hit in html. If the language isn't the expected one, the number is stored in a list called skip.
input: html, settings_dict
output: list with numbers corresponding to hits with "wrong" language.
"""
item_lang = settings_dict["lang_hit"]
skip = []
for index, row in df_worldcat.iterrows():
if row['itemLanguage'] == item_lang:
pass
else:
skip.append(row['number']) # hit number is appended to skip list if language isn't the expected one
#print(skip)
return skip
def fill_publicationlist(df_worldcat, publist, skip):
"""
Adds the publication years of hits with the "right" language to a list.
If the extracted number hasn't got a value between 1840 an 2019, the year will be set to 0 in order to contribute to the total number of publications.
input: dataframe df_worldcat, publist (empty or already filled with publication years from first pages of the search result), skip (list with numbers corresponding to items with "wrong" language)
output: list with publication years of one novel
"""
for index, row in df_worldcat.iterrows():
if row['number'] not in skip:
year = row['year']
year = int(year)
if year not in range(1840, 2020): # if the publication year isn't a number between 1840 and 2020
year = 0
publist.append(year)
return publist
def create_dictionary():
"""
Returns a dictionary with keys from 1840 to 2019, each value is an empty dictionary.
"""
keys = [0]
for x in range(1840,2020): # creates a list with keys from 1840 to 2019 and 0 (for cases where there is no mentioned publication year)
keys.append(x)
pubdict = {key: {} for key in keys} # creates a dictionary with the keys from the list and sets empty dictionaries as values
return pubdict
def fill_dictionary(pubdict, publist, id):
"""
Writes the information from the publication list into the dictionary.
input: dictionary with years from 1840 to 1940 as keys and empty dictionaries as values; list with publication years; id of the novel
output: dictionary in which every year (1840 to 2019) is related to another dictionary containing the novel id (keys) and the number of publications in the specific year (values)
"""
for x in range(1840,2020): # adding a new dictionary entry to each key (year): id of the novel (key) and "0" (number of publications; value)
d = pubdict[x]
d[id] = 0
d = pubdict[0] # adding the dictionary for the year "0" (cases where there is no mentioned year)
d[id] = 0
for year in publist: # for each year in the list the corresponding number of publications is increased by 1
pubdict[year][id] = pubdict[year][id] + 1
return pubdict
def create_dataframe(pubdict):
"""
Changes the dictionary into a dataframe using pandas, see: https://pandas.pydata.org/.
input: dictionary
output: dataframe
"""
dataframe = pd.DataFrame.from_dict(pubdict, orient='index')
return dataframe
def add_sum(dataframe):
"""
Adds the total number of publications of each novel.
"""
dataframe.loc['Total']= dataframe.sum()
def save_csv(dataframe, lang):
"""
Saves the dataframe as csv file.
"""
dataframe.to_csv('{}_reprint_counts.csv'.format(lang))
# === Coordinating function ===
def main(settings_dict):
"""
Coordinates the creation of the publication table.
"""
print("--createpublicationtable")
htmlpages = settings_dict["html_folder"]
lang = settings_dict["lang"]
logging.basicConfig(filename='{}_publicationtable.log'.format(lang),level=logging.WARNING, format='%(asctime)s %(message)s')
publdict = create_dictionary()
publist = []
id_prev = ""
filenames = []
for file in glob.glob(htmlpages):
filenames.append(os.path.basename(file))
filenames.sort()
for file in filenames:
html = read_html(join(settings_dict["write_file"], file))
id, id_ext = get_id(file)
df_worldcat = create_df_worldcat(html, settings_dict, id_ext)
test_search_result(html, id)
skip = test_lang(df_worldcat, settings_dict)
if id == id_prev: # html file contains second, third, ... page of the search result
publist = fill_publicationlist(df_worldcat, publist, skip) # existing publist is appended
else: # html contains the first page of the search result
publist = [] # a new publist is created
publist = fill_publicationlist(df_worldcat, publist, skip)
fill_dictionary(publdict, publist, id)
id_prev = id
dataframe = create_dataframe(publdict)
add_sum(dataframe)
save_csv(dataframe, lang)
#main(dir, htmlpages)
|
386bc3d880111df7bf45cc5b7bdfefce5db389b6 | andreluismoreira/Codigos-em-Python | /tedDicionario.py | 1,844 | 3.96875 | 4 | def main():
listaDeClientes = []
while True:
clientesFiado = {"nome": None, "divida": None, "endereço": None}
opcao = input("*=*=* Escolha uma opção desejada *=*=* \n"
"1- Cadastro de clientes\n"
"2- Atualização de divida\n"
"3- Remoção de cliente\n"
"4- Busca por nome\n"
"5- Sair\n")
if opcao == "1":
nome = input("Digite o nome do liso: ")
clientesFiado['nome'] = nome
divida = input(f"Digite o prego do {clientesFiado['nome']}: ")
clientesFiado['divida'] = divida
endereco = input("Digite o endereço do liso: ")
clientesFiado['endereço'] = endereco
listaDeClientes.append(clientesFiado)
print(listaDeClientes)
elif opcao == "2":
nome = input("Digite o nome do liso: ")
divida1 = input(f"Digite o novo prego: ")
for i in listaDeClientes:
if nome in i.values():
i['divida'] = divida1
print(listaDeClientes)
elif opcao == "3":
nome = input("Digite o nome do liso: ")
for i in listaDeClientes:
if nome in i.values():
listaDeClientes.remove(i)
print("liso removido da lista de prego")
print(listaDeClientes)
elif opcao == "4":
nome = input("Digite o nome do liso: ")
for i in listaDeClientes:
if nome in i.values():
print(i)
else:
print("esse liso nao deve aqui")
elif opcao == "5":
break
else:
print("entrada invalida tente novamente")
main()
|
da9191f7877931c4d81c7f58c389880c2396458e | apryab/GeekBrains-HW-4 | /Task 2.py | 244 | 3.609375 | 4 | my_list = [0, 1, 5, 3, 4, 6, 1, 3, 10, 4, 6, 3, 10, 34, 23, 67]
print('Исходный список -', my_list)
new_list = [my_list[i] for i in range(1, len(my_list)) if my_list[i-1] < my_list[i]]
print('Новый список -', new_list)
|
ad24971ea30370d494fc8fde0464c65fecfcd7cb | CaJiFan/PF-coding-exercises | /U4) Funciones/Ejercicio 4 - L2/main.py | 808 | 3.9375 | 4 | #Terminado
#Usted trabaja en una tienda y le piden definir las funciones que se encuentran en el archivo "funciones.py" los datos de la tienda que le son proporcionados son una lista con los precios de los productos, lista de los nombres de los productos y una lista con los codigos de cada uno de los productos
from funciones import *
l_precios = [1,2.3,4.2,3,2]
l_productos = ['Cebolla', 'Papa', 'Queso', 'Pimiento', 'Pan']
l_codigos = ['001', '002', '003', '004', '005']
#defina una funcion que pueda ingresar un codigo y retorne el nombre del producto y el precio
l_bolsa = []
l_compras = ['001', '005', '003', '002']
producto,precio=producto('001', l_precios, l_productos, l_codigos)
print(producto, precio)
addProducto(l_compras, l_bolsa)
precioTotal(l_compras, l_precios , l_productos , l_codigos) |
782cd0f4aaf9ae7cc9b2a311aad0f1e8834a18a7 | comicxmz001/PythonPlayGround | /PythonGame/rock-scissors-paper.py | 1,993 | 4.28125 | 4 | # Rock-paper-scissors-lizard-Spock template
# The key idea of this program is to equate the strings
# "rock", "paper", "scissors" to numbers
# as follows:
#
# 0 - rock
# 1 - scissors
# 2 - paper
# helper functions
import random
def number_to_name(number):
# fill in your code below
# convert number to a name using if/elif/else
# don't forget to return the result!
if number == 0:
name = "rock"
elif number == 1:
name = "scissors"
elif number == 2:
name = "paper"
else :
print "No such choice!"
name = None
return name
def name_to_number(name):
# fill in your code below
# convert name to number using if/elif/else
# don't forget to return the result!
if name == "rock":
number = 0
elif name == "scissors":
number = 1
elif name == "paper":
number = 2
else:
print "No such choice!"
return number
def rps(name):
# fill in your code below
# convert name to player_number using name_to_number
# compute random guess for comp_number using random.randrange()
# compute difference of player_number and comp_number modulo five
# use if/elif/else to determine winner
# convert comp_number to name using number_to_name
# print results
player_choice = name
player_choice_num = name_to_number(name)
print "Player choose " , player_choice, "."
cmp_choice_num = random.randint(0, 2)
cmp_choice = number_to_name(cmp_choice_num)
print "Computer choose" , cmp_choice, "."
difference = player_choice_num - cmp_choice_num
#equals
if difference == 0:
print "The two sies draw!"
#player wins
elif difference == -1 or difference == 2:
print "Player wins!"
else:
print "Computer wins!"
return None
# test your code
rps("rock")
rps("paper")
rps("scissors")
# always remember to check your completed program against the grading rubric
|
29c88d4526ace19603dd42034ffb67498d8eefde | giabao2807/python-study-challenge | /python-oop/property-in-py/property.py | 1,288 | 3.953125 | 4 | class Person:
def __init__(self, fname: str = '', lname: str = '', age: int = 18):
self.__fname = fname
self.__lname = lname
self.__age = age
def set_age(self, age: int):
if age > 0:
self.__age = age
def get_age(self):
return self.__age
def get_lname(self):
return self.__lname
def set_lname(self, lname: str):
if lname.isalpha():
self.__lname = lname
def get_fname(self):
return self.__fname
def set_fname(self, fname: str):
if fname.isalpha():
self.__fname = fname
def get_name(self):
return f'{self.__fname} {self.__lname}'
#property in python property(getter,setter,deleter)
#deleter ít dùng dùng để gọi del
#nếu thiếu setter -> read-only
first_name = property(get_fname, set_fname)
last_name = property(get_lname, set_lname)
full_name = property(get_name)
age = property(get_age, set_age)
def print(self, format = True):
if not format:
print(self.name, self.age)
else:
print(f'{self.full_name}, {self.age} years old')
putin = Person()
putin.first_name = 'Putin'
putin.last_name = 'Vladimir'
putin.age = 66
print(putin.full_name, putin.age) |
b8dc6cb4c26ea53bd8559e1da76b8466da09f285 | totalgood/nlpia3 | /src/nlpia/book/examples/ch05u01_your_first_neuron.py | 860 | 3.5625 | 4 | # ch05m01_your_first_neuron.py
import numpy as np
from keras.layers import Dense, Activation
from keras.models import Sequential
# OR logic gate inputs and output.
# x_train is sample data (input features)
# y_train the expected outcome for example
x_train = np.array([[0, 0],
[0, 1],
[1, 0],
[1, 1]])
y_train = np.array([[0],
[1],
[1],
[1]])
model = Sequential()
model.add(Dense(1, input_dim=2))
model.add(Activation('sigmoid'))
model.compile('SGD', 'mse')
model.fit(x_train, y_train)
# Get stochastic gradient descent, though there are others
model = Sequential()
model.add(Dense(1, input_dim=2))
model.add(Activation('sigmoid'))
model.compile('sgd', 'mse')
model.fit(x=np.array(x_train), y=np.array(y_train), epochs=5000, batch_size=4)
|
8ea9d744b57d7c9586acabce0a4b419caf0c0caf | DemetriosP/lp2-exercicios | /lista_2/exercicio_2.py | 419 | 3.59375 | 4 | vendas_mensais = float(input("Informe o seu volume mensal de vendas: "))
if vendas_mensais <= 5000:
comissao = vendas_mensais * 0.02
elif 5000.01 <= vendas_mensais <= 10000:
comissao = vendas_mensais * 0.05
elif 10000.01 <= vendas_mensais <= 15000:
comissao = vendas_mensais * 0.07
else:
comissao = vendas_mensais * 0.09
print(f"A sua comissão referente a este mês é de {round(comissao,2)} reais")
|
1951bde090be799907b1d7b9446fb1cafa2ffbfa | RobertoBarrosoLuque/CTA-Health | /cta_data_wrangle.py | 3,771 | 3.59375 | 4 | """
Importing and filtering CTA metro stop data for use in our software
Hana Passen, Charmaine Runes, Roberto Barroso
"""
import numpy as np
import pandas as pd
import requests
import json
END_POINT = "https://data.cityofchicago.org/resource/8pix-ypme.json"
API_KEY = "sJyI5hpZy8dZHJBbMhrhdBkyi"
COLUMNS = ["map_id", "station_descriptive_name", "location"]
def import_clean_cta_data():
'''
Returns a dataframe with the name, location, and map_id for all CTA stops
Inputs:
- none (all default values in the cta module)
Returns:
- cta_df: (pandas dataframe) dataframe with lat, lon, map_id,
descriptive name, name, lines
'''
api_request = build_api_request()
stops_list = get_data(api_request)
cta_df = process_data(stops_list)
return cta_df
def build_api_request(endpoint=END_POINT, api=API_KEY, cols=COLUMNS):
'''
Returns the string needed to make the json request from the city data API
Inputs:
- end_point: (str) a string representing the html endpoint of data
- api: (str) a string representing the API authentication key
- cols: (lst) a list of the columns to select from data set
Returns:
- api_request: (str) a string properly formatted to request data
'''
api_request = END_POINT + "?"
api_request += "$$app_token={}".format(API_KEY)
api_request += "&$select={}".format(",".join(COLUMNS))
return api_request
def get_data(api_request):
'''
Returns a list of dictionaries, in which the keys are the columns we
indicated in our request and the values are the entries for those columns
Inputs:
- api_request: (str) a string representing the request for data
Returns:
- stops_list: (lst) a list of dictionaries, in form {column: entries...}
for each column of data requested
'''
data_json = requests.get(api_request)
stops_list = data_json.json()
return stops_list
def process_data(stops_list):
'''
Returns a pandas dataframe with cleaned and processed data from the api data
request
Inputs:
- stops_list: (lst) a list of dictionaries, in form {column: entries...}
for each column of data requested
Returns:
- stops_df: (pandas dataframe) a processed pandas dataframe
'''
processed_stops = {COLUMNS[0]: [], "descriptive_name": [], "latitude": [],
"longitude": []}
for entry in stops_list:
location = entry[COLUMNS[2]]
lat = float(location["latitude"])
lon = float(location["longitude"])
processed_stops[COLUMNS[0]].append(entry[COLUMNS[0]])
processed_stops["descriptive_name"].append(entry[COLUMNS[1]])
processed_stops["latitude"].append(lat)
processed_stops["longitude"].append(lon)
stops_df = pd.DataFrame(processed_stops)
stops_df.drop_duplicates(("latitude", "longitude"), inplace=True)
stops_df.index = range(len(stops_df))
stops_df["name"] = stops_df["descriptive_name"].str.extract(r"([^()]+)")
stops_df["name"] = stops_df["name"].str.strip()
#Handling corner case where name from scraper and API differ there are two
#situations in which this happens
blvd = stops_df["name"] == "South Boulevard"
stops_df.loc[blvd, "name"] = "South Blvd"
stops_df.loc[blvd, "descriptive_name"] = "South Blvd (Purple Line)"
conservatory = stops_df["name"] == "Conservatory"
stops_df.loc[conservatory, "name"] = "Conservatory-Central Park Drive"
stops_df.loc[conservatory,
"descriptive_name"] = "Conservatory-Central Park Drive (Green Line)"
stops_df_in_order = stops_df.reindex(sorted(stops_df.columns), axis=1)
return stops_df_in_order
|
9ad52f90ff84f228a205dd8891e5f201d3accb27 | dhaarmaa/python | /prueba2/caso_bencinera.py | 2,743 | 3.890625 | 4 | #Una bencinera ofrece distintos tipos de servicio que un cliente puede tomar que serían los siguientes:
# cargar combustible: bencina 900 el litro o diésel 600 el litro, puede cargar varios litros de un tipo de combustible.
# Otro servicio es el de limpieza donde la ficha de hidrolavadora puede costar 1500 por 2 minutos o 2500 por 3 minutos. Finalmente puede aspirar el vehículo zadquiriendo una ficha por 1200 pesos. Hay que señalar que cualquiera de estos servicios es opcional. Al finalizar arroje el detalle de todos los servicios adquiridos, total a cancelar, dinero a pagar y vuelto. Considere mensajes en caso de no seleccionar una opción válida.
import os
os.system('cls')
try:
print("BIENVENiDOS \n Valor de la combustible: \n 1)Bencina a 900 el litro \n 2)Diesel 600 el litro")
fuelType = int(input("ingrese su elección: "))
fuelQuantity = int(input("ingrese la cantidad que quiere: "))
if fuelType == 1:
fuel = "Bencina"
cost = 900
fuelCost = fuelQuantity*900
elif fuelType == 2:
fuel = "Diesel"
cost = 600
fuelCost = fuelQuantity * 600
else:
print("opción invalida")
print("limpieza desde ficha de hidrolavadora \n 1)2 minutos a 1500 \n 3 minutos a 2500 \n 3)ninguno")
cleaning = int(input("Ingrese su elección"))
if cleaning == 1:
typeCleaning = "2 minutos"
costCleaning = 1500
elif cleaning == 2:
typeCleaning = "3 minutos"
costCleaning = 2500
elif cleaning == 3:
typeCleaning = "ningun minuto"
costCleaning = 0
else:
print("respuesta invalida")
print("desea el servicio de aspirar su auto: \n 1) sí \n 2) No")
carAspire = int(input("ingrese su respuesta: "))
if carAspire == 1:
costAspire = 1200
aspire = "si"
elif carAspire == 2:
costAspire = 0
aspire = "no"
else:
print("respuesta invalida")
total = cost + costCleaning + costAspire
print(f"el total es {total}")
money = int(input("ingrese dinero"))
if money > total:
change = money-total
elif money == total:
change = 0
else:
print("ingrese un monto mayor al total")
print("***********RESUMEN DE COMPRA**************")
print(f" tipo de combustible: {fuel}")
print(f"litros: {fuelQuantity}")
print(f"costo: {cost}")
print(f"limpieza por {typeCleaning}")
print(f"costo: {costCleaning}")
print(f"aspirada de auto : {aspire}")
print(f"costo: {costAspire}")
print(f"total de venta: {total}")
print(f"dinero ingresado: {money}")
print(f"vuelto: {change}")
print("\n *****GRACIAS POR PREFERIRNOS*****")
except:
print("respuesta invalida")
|
0809f06706cb06d48dcc5cdca32635965ce3a962 | davecan/rotor-crypto | /MultiRotorDevice.py | 5,098 | 3.640625 | 4 | # Mimics a multi-rotor device such as the Enigma.
#
# When initialized it must be passed a key consisting of a list of rotors,
# and a same-sized list of speeds -- each speed index corresponds to that rotor index.
# Each rotor is rotated by its corresponding value from rotation_speeds.
# This allows rotors to move at varying speeds with each "keypress".
#
# NOTE: This is NOT a simulation of the Enigma itself.
# In this implementation the next rotor is rotated immediately after the previous rotor rotates.
# The Enigma rotation scheme worked differently.
#
# Obviously this would be susceptible to a ciphertext-only attack
class MultiRotorDevice:
__alphabet = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789. ')
__key = [] # key contains 1..n rotors
__speeds = []
__cur_rotor_idx = 0
__tracing = False
def __init__(self, key, rotation_speeds):
self.__key = [list(k) for k in key]
self.__speeds = rotation_speeds
if self.__tracing: self.__show_rotors()
def enable_tracing(self):
self.__tracing = True
def __show_rotors(self):
print('*'*10,'rotors','*'*10)
for rotor in self.__key:
print(''.join(rotor))
print('*'*10,'/rotors','*'*10)
def __rotate(self):
if self.__tracing: print('-'*10,'rotate....')
rotor = self.__current_rotor()
speed = self.__speeds[self.__cur_rotor_idx]
if self.__tracing: print('rotating rotor by %s: ' % speed, ''.join(rotor))
for i in range(0, speed):
rotor.append(rotor.pop(0)) # rotate left ("up")
if self.__tracing: self.__show_rotors()
def __current_rotor(self):
return self.__key[self.__cur_rotor_idx]
def __next_rotor(self):
self.__cur_rotor_idx = (self.__cur_rotor_idx + 1) % len(self.__key) # rotate list of rotors infinitely
return self.__current_rotor()
def encrypt(self, plaintext):
# normalize to only uppercase letters, trimmed non-embedded whitespace, removed other symbols
msg = plaintext.strip().upper()
msg = ''.join(e for e in msg if e.isalnum() or e in [' ', '.'])
if self.__tracing: print('\n\n','='*10,'encrypting...')
ciphertext = ''
for char in msg:
if self.__tracing: print('-'*10,'char -> %s' % char)
i = self.__alphabet.index(char)
rotor = self.__next_rotor()
if self.__tracing: print('rotor:', ''.join(rotor))
ciphertext += rotor[i]
if self.__tracing: print('ciphertext:', ciphertext)
self.__rotate()
return ciphertext
def decrypt(self, ciphertext):
if self.__tracing: print('\n\n','='*10,'decrypting...')
msg = ''
for char in ciphertext:
rotor = self.__next_rotor()
if self.__tracing: print('rotor:', ''.join(rotor))
i = rotor.index(char)
if self.__tracing: print('char at rotor position', i)
msg += self.__alphabet[i]
self.__rotate()
return msg
# generate a random set of rotors for the key each time
# realistically this key would have to be stored and reused by both sender and receiver
import random
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789. '
key = []
for i in range(0,6):
key.append(random.sample(alphabet, len(alphabet)))
speeds = [3,1,5,2,6,4]
alice = MultiRotorDevice(key, speeds)
p = "Attack location 8675309 at dawn. Do not engage enemy before then."
c = alice.encrypt(p)
print('plaintext: ',p)
print('ciphertext: ',c)
bob = MultiRotorDevice(key, speeds)
m = bob.decrypt(c)
print('bob sees:', m)
# SIMULATE ATTACKER
# knows 0 rotors, 0 speeds
key2 = [random.sample(alphabet,len(alphabet))]
eve = MultiRotorDevice(key2, [1])
print('eve 0 rotors 0 speeds:',eve.decrypt(c))
# knows first rotor, 0 speeds
key2 = [key[0]]
for i in range(0,5):
key2.append(random.sample(alphabet, len(alphabet)))
eve = MultiRotorDevice(key2, [1,1,1,1,1,1])
print('eve first rotor, 0 speeds:',eve.decrypt(c))
# knows first rotor, first speed
key2 = [key[0]]
for i in range(0,5):
key2.append(random.sample(alphabet, len(alphabet)))
eve = MultiRotorDevice(key2, [3,1,1,1,1,1])
print('eve first rotor, first speed:',eve.decrypt(c))
# knows rotors 1-2, speeds 1-2
key2 = [key[0], key[1]]
for i in range(0,4):
key2.append(random.sample(alphabet, len(alphabet)))
eve = MultiRotorDevice(key2, [3,1,1,1,1,1])
print('eve rotor 1-2, speed 1-2:',eve.decrypt(c))
# knows 5 rotors and 5 speeds
# This is the first point at which the cipher can be partially read
key2 = list(key)
key2[5] = random.sample(alphabet, len(alphabet))
eve = MultiRotorDevice(key2, [3,1,5,2,6,1])
print('eve 5 rotors and 5 speeds:',eve.decrypt(c))
# knows 6 rotors but only 5 speeds
# Much closer!
key2 = list(key)
eve = MultiRotorDevice(key2, [3,1,5,2,6,1])
print('eve 6 rotors and 5 speeds:',eve.decrypt(c))
# knows 5 rotors but all 6 speeds
key2 = list(key)
key2[5] = random.sample(alphabet, len(alphabet))
eve = MultiRotorDevice(key2, speeds)
print('eve 5 rotors and 6 speeds:',eve.decrypt(c)) |
72be94a6b75263d4446cb71d205bd5d7358dd9e5 | fitrialif/CoDeepNEAT | /src/NEAT/Mutagen.py | 11,121 | 3.59375 | 4 | import math
import random
from enum import Enum
class ValueType(Enum):
"""discrete mutagens mutate between a set of options"""
DISCRETE = 0
"""whole/continuous numbers mutate a numerical value inside of a range"""
WHOLE_NUMBERS = 1
CONTINUOUS = 2
class Mutagen:
"""this class represents any mutatable parameter used by cdn.
generally speaking mutagens represent gene attributes
a submutagen is a mutagen which only applies to a specific discrete option of the parent mutagen
where layer_type is a mutagen, convolutional_window_size is a submutagen of layertype for the value convulutional_layer
"""
def __init__(self, *discreet_options, name="", current_value=-1, start_range=None, end_range=None,
value_type=ValueType.DISCRETE, sub_mutagens: dict = None, discreet_value=None, mutation_chance=None,
print_when_mutating=False, distance_weighting=0, inherit_as_discrete=False):
"""defaults to discrete values. can hold whole numbers/ real numbers in a range"""
self.value_type = value_type
self.end_range = end_range
self.start_range = None
self.print_when_mutating = print_when_mutating
self.name = name
self.age = 0
self.distance_weighting = distance_weighting
# some whole number values such as species number should not be interpolated during inheritance,
# as this does not make sense
self.inherit_as_discrete = inherit_as_discrete
if len(discreet_options) > 0:
self.possible_values = discreet_options
self.current_value_id = current_value
elif not (start_range is None) and not (end_range is None):
if start_range > current_value or self.end_range < current_value:
print("warning: setting current value (", current_value, ") of a mutagen to outside the range(",
start_range, ":", self.end_range, ")")
self.start_range = start_range
self.current_value = current_value
else:
print("error in initialising mutagen. "
"value must either be discreet and provided with options. or numerical values with a provided range")
self.sub_values = sub_mutagens #maps value:{sub_mutagen_name:submutagen}
if value_type == ValueType.DISCRETE:
self.set_value(discreet_value)
if mutation_chance is None:
if value_type == ValueType.DISCRETE:
self.mutation_chance = 0.05
if value_type == ValueType.WHOLE_NUMBERS:
self.mutation_chance = 0.1
if value_type == ValueType.CONTINUOUS:
self.mutation_chance = 0.2
else:
self.mutation_chance = mutation_chance
value = property(lambda self: self.get_value())
def inherit(self, other):
"""used by the mutagen breeding extension
sets this mutagens values and subvalues closer to the values and subvalues of other
this is the interpolation of this node towards other
"""
if self.value_type != other.value_type:
raise Exception("cannot breed mutagens of differing types:", self.value_type, other.value_type)
if self.value_type == ValueType.DISCRETE or self.inherit_as_discrete:
"""chance to take others value"""
if random.random() < 0.35:
self.set_value(other.get_value())
# print(self.name, "inheritting discrete value",other.get_value())
else:
"""new value interpolated from old value - skewed slightly towards self against other"""
my_value = self.get_value()
other_value = other.get_value()
new_value = my_value + 0.35 * (other_value - my_value)
if self.value_type == ValueType.WHOLE_NUMBERS:
new_value += random.random() * 0.2 - 0.1 # to make it equally likely to round up/down from x.5
self.set_value(int(round(new_value)))
else:
self.set_value(new_value)
if not (self.sub_values is None):
for val in self.sub_values.keys():
my_subs = self.sub_values[val]
if val == self.get_value():
for sub_mut_name in my_subs.keys():
if val in other.sub_values:
other_subs = other.sub_values[val]
my_subs[sub_mut_name].inherit(other_subs[sub_mut_name])
def __call__(self):
return self.get_value()
def mutate(self, magnitude=1):
"""varies this mutagens values and subvalues
:returns whether or not this mutagen mutated"""
old_value = self()
self.mutate_sub_mutagens()
if self.print_when_mutating:
# print("trying to mutate mutagen",self.name,"mutation chance:",self.mutation_chance)
pass
self.age += 1
if random.random() < self.mutation_chance * magnitude:
if self.value_type == ValueType.DISCRETE:
new_current_value_id = random.randint(0, len(self.possible_values) - 1)
if new_current_value_id == self.current_value_id:
new_current_value_id = (self.current_value_id + 1) % len(self.possible_values)
self.current_value_id = new_current_value_id
if self.value_type == ValueType.WHOLE_NUMBERS:
if random.random() < 0.25:
"""random reset"""
new_current_value = random.randint(self.start_range, self.end_range)
else:
deviation_fraction = math.pow(random.random(), 4) * (1 if random.random() < 0.5 else -1) * magnitude
new_current_value = self.current_value + int(
deviation_fraction * (self.end_range - self.start_range))
if new_current_value == self.current_value:
new_current_value = self.current_value + (1 if random.random() < 0.5 else -1)
new_current_value = max(self.start_range, min(self.end_range - 1, new_current_value))
self.current_value = new_current_value
if self.value_type == ValueType.CONTINUOUS:
if random.random() < 0.25:
"""random reset"""
new_current_value = random.uniform(self.start_range, self.end_range)
deviation_fraction = -1
else:
deviation_fraction = math.pow(random.random(), 4) * (1 if random.random() < 0.5 else -1) * magnitude
new_current_value = self.current_value + deviation_fraction * (self.end_range - self.start_range)
new_current_value = max(self.start_range, min(self.end_range, new_current_value))
if self.print_when_mutating:
print("altering continuous number from", old_value, "to", new_current_value, "using dev frac=",
deviation_fraction, "range: [", self.start_range, ",", self.end_range, ")")
self.current_value = new_current_value
if self.print_when_mutating and old_value != self():
print("mutated gene from", old_value, "to", self(), "range: ", self.start_range, ", ", self.end_range)
return not old_value == self()
def mutate_sub_mutagens(self):
"""part of the recursive mutation"""
if not (self.sub_values is None):
for val in self.sub_values.keys():
subs = self.sub_values[val]
if val == self.get_value():
for sub_mut in subs.values():
sub_mut.mutate()
def get_value(self):
"""returns the number value, or the option at curent_value_id
depending on numerical or discreet mutagen respectively"""
if self.value_type == ValueType.DISCRETE:
return self.possible_values[self.current_value_id]
else:
return self.current_value
def get_sub_value(self, sub_value_name, value=None, return_mutagen=False):
"""returns the submutagen or its value given its name"""
if value is None:
mutagen = self.sub_values[self.get_value()]
else:
mutagen = self.sub_values[value][sub_value_name]
if sub_value_name in mutagen:
mutagen = mutagen[sub_value_name]
else:
return None
if return_mutagen:
return mutagen
else:
return mutagen.get_value()
def get_sub_values(self):
if not (self.sub_values is None):
if self.get_value() in self.sub_values:
return self.sub_values[self.get_value()]
def get_all_sub_values(self):
sub_values = []
if self.sub_values is None:
return sub_values
for val in self.sub_values.keys():
if val != self.get_value():
continue
subs = self.sub_values[val]
for sub_mut in subs.values():
if sub_mut.value_type == ValueType.DISCRETE:
sub_values.extend(sub_mut.get_all_sub_values())
continue
sub_values.append(sub_mut.get_value())
return sub_values
def __repr__(self):
return str(self.value_type) + ' ' + str(self.start_range) + ' ' + str(self.end_range)
def distance_to(self, other):
"""used for attribute distance.
calculates the distance or similarity between self and an other mutagen of the same kind
"""
if self.value_type == ValueType.DISCRETE:
dist = 0
if self() != other():
dist = self.distance_weighting
else:
dist = self.distance_weighting * abs(self() - other()) / (self.end_range - self.start_range)
if self.sub_values is None:
return dist
for sub_mutagen_group in self.sub_values.keys():
self_subs = self.sub_values[sub_mutagen_group]
other_subs = other.sub_values[sub_mutagen_group]
for sub_mut_key in self_subs.keys():
dist += self_subs[sub_mut_key].distance_to(other_subs[sub_mut_key])
return dist
def set_value(self, value):
"""sets current_value=value, or current_value_id = index(value)
depending on numerical or discreet mutagen respectively"""
if self.value_type == ValueType.DISCRETE:
if value is None and None not in self.possible_values:
self.current_value_id = 0
else:
self.current_value_id = self.possible_values.index(value)
else:
self.current_value = value
def set_sub_value(self, sub_value_name, sub_value, value=None):
if value is None:
self.sub_values[self.get_value()][sub_value_name].set_value(sub_value)
else:
self.sub_values[value][sub_value_name].set_value(sub_value)
|
42df47d4e842cceeac7fa7df7c3a618e1c21d817 | zigaen/Python_Vaje | /OOP/OOP.py | 3,810 | 3.890625 | 4 | import json
class Player():
def __init__(self, first_name, last_name, height_cm, weight_kg):
self.first_name = first_name
self.last_name = last_name
self.height_cm = height_cm
self.weight_kg = weight_kg
def weight_to_lbs(self):
pounds = self.weight_kg * 2.20462262
return pounds
class BasketballPlayer(Player):
def __init__(self, first_name, last_name, height_cm, weight_kg, points, rebounds, assists):
super().__init__(first_name=first_name, last_name=last_name, height_cm=height_cm, weight_kg=weight_kg)
self.points = points
self.rebounds = rebounds
self.assists = assists
class FootballPlayer(Player):
def __init__(self, first_name, last_name, height_cm, weight_kg, goals, yellow_cards, red_cards):
super().__init__(first_name=first_name, last_name=last_name, height_cm=height_cm, weight_kg=weight_kg)
self.goals = goals
self.yellow_cards = yellow_cards
self.red_cards = red_cards
answer_game = input("Add player forr football(f) or. basketball (b)? : ")
if answer_game == "b":
while True:
answer = input("Let's add a player to the list. Would you like to do that? (y/n): ")
answer = answer.lower()
if answer == "n":
print("Ok, bye!")
elif answer == "y":
myPlayer = BasketballPlayer(
first_name= input("Type first name of the player: "),
last_name= input("Type last name of the player: "),
height_cm= input("Player height: "),
weight_kg= input("Player weight: "),
points= input("The number of points: "),
rebounds= input("The number of rebounds: "),
assists= input("The number of assists: ")
)
print(f"{myPlayer.first_name} {myPlayer.last_name} Will be stored in to database!")
myPlayer = myPlayer.__dict__
with open("player_list_basketball.txt", "r") as player_file:
player_list = json.loads(player_file.read())
print("Added player is: " + str(myPlayer))
player_list.append(myPlayer)
with open("player_list_basketball.txt", "w") as player_file:
player_file.write(json.dumps(player_list))
continue
else:
print("enter the rigt letter (y/n)")
break
elif answer_game == "f":
while True:
answer = input("Let's add a player to the list. Would you like to do that? (y/n): ")
answer = answer.lower()
if answer == "n":
print("Ok, bye!")
elif answer == "y":
myPlayer = FootballPlayer(
first_name=input("Type first name of the player: "),
last_name=input("Type last name of the player: "),
height_cm=input("Player height: "),
weight_kg=input("Player weight: "),
goals=input("The number of goals: "),
yellow_cards=input("The number of yellow cards: "),
red_cards=input("The number of red cards: ")
)
print(f"{myPlayer.first_name} {myPlayer.last_name} Will be stored in to database!")
myPlayer = myPlayer.__dict__
with open("player_list_football.txt", "r") as player_file:
player_list = json.loads(player_file.read())
print("Added player is: " + str(myPlayer))
player_list.append(myPlayer)
with open("player_list_football.txt", "w") as player_file:
player_file.write(json.dumps(player_list))
continue
else:
print("enter the rigt letter (y/n)")
break
else:
print("You must choose between b/f! ")
|
80bf414423eadf6cf72ab85e26c59ce39a23ec53 | manojpandey/Algorithms | /misc/sieve_of_eratosthenes.py | 873 | 4.15625 | 4 | """
Implementation of Sieve of Eratosthenes algorithm to generate all the primes upto N.
Reference : https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
Algorithm :
* We have a list of numbers from 1 to N.
* Initially, all the numbers are marked as primes.
* We go to every prime number in the list (<= N ^ 1/2) and mark all the multiples of this prime number which are bigger than the number itself as non-primes.
"""
from math import sqrt,ceil
def calculate_primes(n):
bool_array = [True] * (n+1)
bool_array[0] = False
bool_array[1] = False
upper_bound = ceil(sqrt(n))
for i in range(2,upper_bound):
if bool_array[i]:
for j in range(i*i,n+1,i):
bool_array[j] = False
prime_array = [i for i in range(n+1) if bool_array[i]]
return prime_array
if __name__ == "__main__":
print(calculate_primes(50))
|
9af3b70b77243bf6c8cca2ebceabdea2297eeb37 | HFMarco/quantum_py | /clase_03/ejerc_05.py | 99 | 3.5 | 4 |
x=0
while x <= 1000:
x += 1
if x%2 != 0:
continue
else:
print(x)
|
dab26d9a946f76154568536859bed195f157e8b6 | ml4ai/tomcat | /human_experiments/lab_software/tomcat-baseline-tasks/tasks/ping_pong_task/utils/ball.py | 2,124 | 3.65625 | 4 | from math import copysign
from random import randint
from typing import Optional
import pygame
from common import COLOR_FOREGROUND
from .constants import WINDOW_HEIGHT, WINDOW_WIDTH
class Ball(pygame.sprite.Sprite):
"""
Ball pygame sprite updated by the server
"""
def __init__(self,
ball_size: int,
ball_x_speed: int = 0):
# Set up pygame sprite
super().__init__()
self.image = pygame.Surface((ball_size, ball_size))
self.image.fill((0, 0, 0))
self.mask = pygame.mask.from_surface(self.image)
pygame.draw.rect(self.image, COLOR_FOREGROUND, (0, 0, ball_size, ball_size))
self._ball_size = ball_size
self._ball_x_speed = ball_x_speed
self.rect = self.image.get_rect()
self.rect.x = int((WINDOW_WIDTH + ball_size) / 2)
self.rect.y = int((WINDOW_HEIGHT + ball_size) / 2)
# Initialize ball velocity
self.velocity = [ball_x_speed, randint(-ball_x_speed, ball_x_speed)]
def update(self):
"""
Update position of the ball
"""
self.rect.x += int(self.velocity[0])
self.rect.y += int(self.velocity[1])
def bounce(self, velocity_y: Optional[int] = None):
"""
Bounce the ball when it hits players' wall or paddle
"""
# Move the ball the other direction
self.velocity[0] = -self.velocity[0]
# If the y velocity is set by user
if velocity_y is not None:
assert isinstance(velocity_y, int)
self.velocity[1] = velocity_y
# Randomly generate y velocity, following its previous trajectory
else:
velocity_y_sign = copysign(1, self.velocity[1])
self.velocity[1] = velocity_y_sign * randint(4, self._ball_x_speed)
def reset_center(self):
self.rect.x = int((WINDOW_WIDTH + self._ball_size) / 2)
self.rect.y = int((WINDOW_HEIGHT + self._ball_size) / 2)
# Re-initialize ball velocity
self.velocity = [self._ball_x_speed, randint(-self._ball_x_speed, self._ball_x_speed)]
|
5cbcf60de89dc518b7f6b4b6a6ceacc3dddeb52c | simonfong6/ECE-143-Team-6 | /data_analysis/utils.py | 7,587 | 3.796875 | 4 | #!/usr/bin/env python3
"""
Functions that help with loading and filtering the data.
"""
import json
import pandas as pd
DATA_FILE_NAME = '../data_fetching/sadscore_data.json'
def dumps(dict_):
"""
Converts dictionaries to indented JSON for readability.
Args:
dict_ (dict): The dictionary to be JSON encoded.
Returns:
str: JSON encoded dictionary.
"""
string = json.dumps(dict_, indent=4, sort_keys=True)
return string
def print_dict(dict_):
"""
Prints a dictionary in readable format.
Args:
dict_ (dict): The dictionary to be JSON encoded.
"""
print(dumps(dict_))
class QuizResponse:
"""
Wraps each individual response dictionary so that it is easier to access.
Attributes:
data (dict): The raw quiz response data.
timestamp (float): The timestamp of when the data was recorded.
total_score (int): The total score of this response.
responses (dict): Just the quiz question and value recorded.
"""
def __init__(self, resp_data):
self.data = resp_data
self.timestamp = resp_data['timestamp_secs']
self.total_score = resp_data['total_score']
self.responses = QuizResponse.filter_questions(resp_data['responses'])
def __repr__(self):
return 'QuizResponse(\n' + dumps(self.responses) + '\n)'
@staticmethod
def filter_questions(responses):
"""
Extract only the value of each response disregarding other details.
Args:
responses (dict(dict)): Responses for each question.
Returns:
dict(question->value): A dictionary that maps from question to
response value.
Example:
data = {
"above_platinum": {
"name": "above_platinum",
"score": 0,
"value": false
}
}
-> {
"above_platinum": false
}
"""
new_questions = {}
for key, question in responses.items():
new_questions[key] = question['value']
return new_questions
def load_data():
"""
Loads the JSON data as a dictionary.
Returns:
list(dict): The data a dictionary.
"""
with open(DATA_FILE_NAME) as input_file:
data = json.load(input_file)
return data
def filter(data):
"""
Runs through all the data, creates QuizResponse objects, and puts them in a
list.
Args:
data (list(dict)): The nested dictionaries to be converted.
Returns:
list(QuizResponse): Each response as a QuizResponse object.
"""
filtered = []
for response in data:
# There is one dictionary that just stores the count of responses.
if 'responses' not in response:
continue
qr = QuizResponse(response)
filtered.append(qr)
return filtered
def create_dataframe(data):
"""
Create a DataFrame from our data for easier manipulation.
Args:
data (list(dict): The quiz responses.
Returns:
pandas.DataFrame: The quiz responses as a DataFrame.
"""
df = pd.DataFrame(data)
return df
def load_data_dataframe():
"""
Loads data as dataframe.
Returns:
pandas.DataFrame: The data loaded as dataframe.
"""
data = load_data()
data = filter(data)
# Just use the list of responses for each QuizReponse object.
responses = []
for response in data:
response_dict = response.responses
response_dict['timestamp'] = response.timestamp
response_dict['total_score'] = response.total_score
responses.append(response)
just_list = [ r.responses for r in data]
df = create_dataframe(just_list)
# Columns to convert to numeric types.
numeric_columns = [
'foreign_langauges_fluent',
'foreign_langauges_nonfluent',
'height_cm',
'instruments',
'iq_score',
'attractiveness'
]
# Fix strings to numeric values.
for column in numeric_columns:
df[column] = pd.to_numeric(df[column])
# Convert tattoos column to numeric and fill NaN with 0's.
column = 'tattoos'
df[column] = pd.to_numeric(df[column])
df[column].fillna(0)
return df
def turn_off_scientific_notation():
"""
Turns off scienctific notation in Pandas when displaying dataframes.
"""
pd.set_option('display.float_format', lambda x: '%.3f' % x)
def drop_outliers(df, column_name, min_val, max_val):
"""
Drops outliers based on range, inclusive.
Args:
df (pandas.DataFrame): The data to filter.
column_name (str): The column name to filter on.
min_val (int): The minimum value allowed in this category.
max_val (int): The maximum value allowed in this category.
Returns:
pandas.DataFrame: The same dataframe, but with outliers removed.
"""
# Find the outliers.
max_outliers = df[df[column_name] > max_val]
min_outliers = df[df[column_name] < min_val]
outliers = pd.concat([max_outliers,min_outliers])
# Drop the outliers.
df = df[df[column_name] <= max_val]
df = df[df[column_name] >= min_val]
return df, outliers
def drop_all_outliers(df):
"""
Drops all outliers.
Args:
df (pandas.DataFrame): The data to filter out outliers from.
Returns:
pandas.DataFrame: The same data without outliers.
"""
# Keep heights between 4ft and 8ft.
df, outliers_height = drop_outliers(df, 'height_cm', 121, 250)
# Drop Instruments outliers.
df, outliers_instruments = drop_outliers(df, 'instruments', 0, 20)
# Drop IQ Score outliers.
df, outliers_iq_score = drop_outliers(df, 'iq_score', 0, 200)
# Drop fluent languages outliers.
df, outliers_foreign_langauges_fluent = drop_outliers(
df,
'foreign_langauges_fluent',
0,
20)
# Drop non-fluent languages outliers.
df, outliers_foreign_langauges_nonfluent = drop_outliers(
df,
'foreign_langauges_nonfluent',
0,
20)
# Drop non-fluent languages outliers.
df, outliers_tattoos = drop_outliers(
df,
'tattoos',
0,
20)
# Combine outliers
outliers = pd.concat(
[
outliers_height,
outliers_instruments,
outliers_iq_score,
outliers_foreign_langauges_fluent,
outliers_foreign_langauges_nonfluent,
outliers_tattoos
])
return df, outliers
def drop_total_score_outliers(df):
return drop_outliers(
df,
'total_score',
-1000,
1000)
def main():
df = load_data_dataframe()
turn_off_scientific_notation()
df, outliers = drop_all_outliers(df)
sums = df.sum()
count = df.shape[0]
averages = sums / count
if __name__ == '__main__':
main() |
f67994dbf2aea73909ab144af1aa1cb6f2717d20 | 1012378819/2020kingstar | /src/fishC/magic_func.py | 2,208 | 3.53125 | 4 | # -*- coding:utf-8 -*-
'''
Created on 2019年12月22日
@author: pei.lu
'''
class CapStr(str):
def __new__(cls,string):
string=string.upper()
return str.__new__(cls,string)
a=CapStr("this is new knowledge")
print(a)
class C:
def __init__(self):
print('我是 构造方法,对我的实例化时,我被执行')
def __del__(self):
print('我是 析构方法,对我的引用为0时,我被执行')
c1=C() # 为啥结果会直接输出析构方法?
# c2=c1
# c3=c2
# del c3
# del c2
# del c1
class new_int(int):
def __add__(self,other):
return int.__sub__(self,other) # 实际进行减法
def __sub__(self,other):
return int.__add__(self,other) # 实际进行加法
a=new_int(3)
b=new_int(5)
print(a+b)
print(a-b)
print('===============')
def checkIndex(key):
if not isinstance(key,(int,)):raise TypeError
if key<0:raise IndexError
class ArithmeticSequence:
def __init__(self,start=0,step=1):
self.start=start # 保存开始值
self.step=step # 保存步长
self.changed={} # 没有项被修改
def __getitem__(self, key): # 返回所给键对应的值
checkIndex(key)
try: return self.changed[key] # 修改了吗?
except KeyError: # 否则。。。
return self.start+key*self.step # 。。。计算值
def __setitem__(self, key, value): # 按一定的方式存储和key相关的value
checkIndex(key)
self.changed[key]=value # 保存更改后的值
s=ArithmeticSequence(1,2)
print(s[4])
s[4]=2
print(s.changed)
print(s[4])
print(s[5])
# print(s["four"]) #TypeError
# print(s[-23]) #IndexError
# del s[4] #AttributeError,没有实现__delitem__方法
class CounterList(list): # 继承list类
def __init__(self,*args):
super(CounterList,self).__init__(*args)
self.counter=0 # 新计数属性
def __getitem__(self, index):
self.counter+=1
return super(CounterList,self).__getitem__(index)
c1=CounterList(range(10))
print(c1)
c1.reverse()
print(c1)
del c1[3:6]
print(c1)
print(c1.counter)
print(c1[4]+c1[2])
print(c1.counter)
|
7b1f0dab3bc87d652a6c77d7d5004d5a3cf4a559 | willwearing/cs-guided-project-graphs-ii | /src/find_all_paths_in_binary_tree.py | 2,229 | 4.09375 | 4 | #
# Binary trees are already defined with this interface:
# class Tree(object):
# def __init__(self, x):
# self.value = x
# self.left = None
# self.right = None
def treePaths(root):
'''
Input: the root of the tree to traverse
Output: list of strings where a single string
represents a single path through the tree
Since we are looking to enumerate all of the paths,
a depth-first traversal would work well for this.
Let's implement our DFT recursively.
What are our base cases?
1. When we encounter a leaf node, we're done building
up the current path. Add the current path to our
answer list (reformat the path as a string)
How do we get closer to a base case?
1. Add the current node's value to the current path that
we're building up, and then recursively traverse down to
the node's children.
Every time we pass control back up the recursion stack,
we need to pop the latest value from the current path
that we're building up
'''
result = []
dft(root, [], result)
return result
# Define a new recursive function with the signature
# we need since the original function doesn't have
# the signature we need
def dft(node, current_path, result):
# base case
# if the current node is None
if not node:
return
# turn the node value into a string
# before appending it to the current path
current_path.append(f'{node.value}')
# when the current node is a leaf
if is_leaf(node):
# after adding the current node's value to the path list
# take the current path and add it to our result list
# append a snapshot of the current path at this
# point in time to the result list
result.append("->".join(current_path[:]))
# otherwise, add the current node's value to the path list
# make further recursive calls to this node's children
dft(node.left, current_path, result)
dft(node.right, current_path, result)
# pop the last element from the current path
current_path.pop()
def is_leaf(node):
return node.left is None and node.right is None |
f56658523c9b0101fac5881f984814c15e204e7f | VeisaGit/python-practice | /Cows and Bulls game/server.py | 1,465 | 3.515625 | 4 | import random
import re
number = str(random.randint(1000, 9999))
# print('загаданное число ', number)
try_counter = 0
def inst_number():
global user_number, try_counter
try_counter += 1
user_number = input("Введите четырехзначное число: ")
if re.search(r'\D', user_number):
print("Ошибка! Нужно ввести цифры. Начните заново.")
elif len(user_number) > 4:
print("Ошибка! Вы ввели слишком много цифр, нужно ввести 4. Начните заново.")
elif len(user_number) < 4:
print("Ошибка! Вы ввели слишком мало цифр, нужно ввести 4. Начните заново.")
else:
return list(user_number)
def check_number():
if inst_number():
cows = []
bulls = []
for i, j in zip(number, user_number):
if i == j:
bulls.append(1)
else:
if j in number:
cows.append(1)
while sum(bulls) < 4:
print("Коровы:{} Быки: {}".format(sum(cows), sum(bulls)))
check_number()
break
else:
print("Вы отгадали число! Коровы:{} Быки: {}".format(sum(cows), sum(bulls)))
print("Количество затраченных попыток - ", try_counter)
|
ea9084b8b4da109d9d364e0c7fc44f961e8ceedc | emmagordon/python-bee | /group/reverse_words_in_a_string.py | 602 | 4.28125 | 4 | #!/usr/bin/env python
"""Write a function, f, which takes a string as input and reverses the
order of the words within it.
The character order within the words should remain unchanged.
Any punctuation should be removed.
>>> f('')
''
>>> f('Hello')
'Hello'
>>> f('Hello EuroPython!')
'EuroPython Hello'
>>> f('The cat sat on the mat.')
'mat the on sat cat The'
>>> f('So? much, punctuation:')
'punctuation much So'
>>> f('a santa lived as a devil at nasa')
'nasa at devil a as lived santa a'
"""
import doctest
# TODO: REPLACE ME WITH YOUR SOLUTION
if __name__ == "__main__":
doctest.testmod()
|
796ec04401995d4438e00427767e9ad1bf66ecb3 | sreekripa/core2 | /while.py | 190 | 3.828125 | 4 | # c=0
# while c<10:
# print(c)
# c+=1
# i=0
# while i<6:
# i+=1
# if i==3:
# continue
# print(i)
i=0
while i<10:
print(i)
if i==3:
break
i+=1
|
87154d5f986ad6864ee5f9d27da8811ac574e34b | akashmallik/python | /basic/loops/while.py | 620 | 4.34375 | 4 | """
Python has two primitive loop commands:
>> while loops
>> for loops
"""
# The while Loop
i = 1
while i < 5:
print(i)
i += 1
print('\n')
# Break
"""
With the break statement we can stop the loop even if the while condition is true.
"""
i = 1
while i < 5:
print(i)
if i == 3:
break
i += 1
# Continue
"""
With the continue statement we can stop the current iteration, and continue with the next.
"""
x = 20
while x < 25:
print(x)
x += 1
if x == 22:
continue
# The else statement
x = 1
while x < 3:
print(x)
x += 1
else:
print("No more data found...")
|
2fc1f347d54f6c003cae85965680a64b1a2c4131 | AnelMengdigali/Calculation-Checker | /calculation.py | 901 | 4 | 4 | import random
def askforanswer( nrcorrect, nr1, nr2 ):
while True:
inputstring = input( "question {}: please calculate {} times {} ". format( nrcorrect, nr1, nr2 ) )
try:
answer = int( inputstring )
return answer
except ValueError:
print("Please, try again! You entered invalid input:\n")
def exam():
nrcorrect = 1;
upperbound = 20;
while nrcorrect<6:
nr1 = random.randrange( upperbound )
nr2 = random.randrange( upperbound )
correct = nr1 * nr2
answer = askforanswer( nrcorrect, nr1, nr2 )
if answer == correct:
nrcorrect = nrcorrect+1
print( "You are right!" )
else:
print( "Wrong!" )
print( "The right answer is {}:". format( correct ) )
nrcorrect = 1
print( "Exam is over." )
|
a8b6d79a611d5f4c9f37af3bd51f7dbca99110bb | leet23/python_kurs | /01_typy_zmienne/zadanie3.py | 347 | 3.59375 | 4 | # zadanie 3
quote = "Honesty is the first chapter in the book of wisdom."
print(quote)
print(len(quote)) #1
print(quote[-7:-1]) #2
print(quote[0:25]) #3
print(quote[0:len(quote)//2]) #3
print(quote[-1]) #4
print(quote[len(quote)//2 : : 3]) #5
print(quote[ : : 2]) #6
print(quote[ : : -1]) #7
print(quote.replace("wisdom", "friendship")) #8
print() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.