blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
52f3999f1065af63d7942742b5313d82829ce2b3 | GaganDureja/Algorithm-practice | /Balancing scale.py | 262 | 3.515625 | 4 | #Link: https://edabit.com/challenge/xPmfKHShmuKL5Qf9u
def scale_tip(lst):
left = sum(lst[:lst.index('I')])
right = sum(lst[lst.index('I')+1:])
return 'balanced' if left==right else 'left' if left>right else 'right'
print(scale_tip([0, 0, "I", 1, 1])) |
bd5772753947ecc410181a53ba174f28563aea27 | GaganDureja/Algorithm-practice | /merge_sort.py | 264 | 3.9375 | 4 | # This problem was asked by Google.
# Given k sorted singly linked lists, write a function to merge all the lists into one sorted singly linked list.
def sort_merge(lst):
return sorted(sum(lst,[]))
lst = [[1,5,8],[0,2,6]]
print(sort_merge(lst))
|
af0b61fb0ec5eed544bd7d47e2e6ddd5c43604e3 | GaganDureja/Algorithm-practice | /climbing competition.py | 554 | 3.703125 | 4 | #Link: https://edabit.com/challenge/Q7oecYfjkq7tHwPoA
def climb(stamina, obstacles):
count = 0
x = 1
while True:
try:
prev = obstacles[x-1]
now = obstacles[x]
except IndexError:
return count
if prev==now:
count+=1
x+=1
elif prev>now and stamina>=int((prev-now)+0.999):
stamina-=int((prev-now)+0.999)
count+=1
x+=1
elif prev<now and stamina>=int((now-prev)+0.999)*2:
stamina-=int((now-prev)+0.999)*2
count+=1
x+=1
else:
return count
print(climb(11,[0.3, 2, 2.8, 3, 3, 0.8, 3.2,2,0])) |
7d3e7f1c6ae4cc055b7fd0c4abcc2bdf0df5082f | GaganDureja/Algorithm-practice | /Big sorting.py | 289 | 3.828125 | 4 |
#Link: https://www.hackerrank.com/challenges/big-sorting/problem
n = int(input().strip())
unsorted = []
unsorted_i = 0
for unsorted_i in range(n):
unsorted_t = str(input().strip())
unsorted.append(unsorted_t)
unsorted.sort(key= lambda x:(len(x),x))
for i in unsorted:
print(i) |
13f403466c54ae0edd72fa95a867cc7d234ae206 | GaganDureja/Algorithm-practice | /budget items.py | 347 | 3.578125 | 4 | Link: https://edabit.com/challenge/9ZAk3EEoQ9YPGGYhA
def items_purchase(store, wallet):
lst = []
for x in store:
price = int((store[x][1:]).replace(',',''))
if price<= int(wallet[1:]):
lst.append(x)
return lst if lst else 'Nothing'
print(items_purchase({"Water": "$1", "Bread": "$3", "TV": "$1,000","Fertilizer": "$20"}, "$300"))
|
25f7bd2da375d36fce8e9febbc03651943a8c4d2 | GaganDureja/Algorithm-practice | /Amateur Hour.py | 636 | 3.734375 | 4 | #Link: https://edabit.com/challenge/6BXmvwJ5SGjby3x9Z
def convet24(txt):
if txt[-2:]=='AM' and txt[:2]=='12':
return 0
elif txt[-2:]=='PM' and txt[:2]!='12':
return int(txt.split(':')[0])+12
else:
return int(txt.split(':')[0])
def hours_passed(time1, time2):
return 'no time passed' if time1==time2 else '%s hours' %(convet24(time2)- convet24(time1))
print(hours_passed("3:00 AM", "9:00 AM"))
print(hours_passed("1:00 AM", "3:00 PM"))
print(hours_passed("1:00 AM", "12:00 PM"))
print(hours_passed("1:00 PM", "12:00 AM"))
print(hours_passed("1:00 PM", "1:00 PM"))
print(hours_passed("12:00 AM", "11:00 PM")) |
ac42e69bac982862edcbed8567653688ee07f186 | GaganDureja/Algorithm-practice | /Vending Machine.py | 1,686 | 4.25 | 4 | # Link: https://edabit.com/challenge/dKLJ4uvssAJwRDtCo
# Your task is to create a function that simulates a vending machine.
# Given an amount of money (in cents ¢ to make it simpler) and a product_number,
#the vending machine should output the correct product name and give back the correct amount of change.
# The coins used for the change are the following: [500, 200, 100, 50, 20, 10]
# The return value is a dictionary with 2 properties:
# product: the product name that the user selected.
# change: an array of coins (can be empty, must be sorted in descending order).
def vending_machine(products, money, product_number):
if product_number not in range(1,10):
return 'Enter a valid product number'
if money < products[product_number-1]['price']:
return 'Not enough money for this product'
lst = [500,200,100,50,20,10]
count = 0
money-= products[product_number-1]['price']
change = []
while money!=0:
if money-lst[count]>=0:
money-=lst[count]
change.append(lst[count])
else:
count+=1
return {'product':products[product_number-1]['name'], 'change': change}
# Products available
products = [
{ 'number': 1, 'price': 100, 'name': 'Orange juice' },
{ 'number': 2, 'price': 200, 'name': 'Soda' },
{ 'number': 3, 'price': 150, 'name': 'Chocolate snack' },
{ 'number': 4, 'price': 250, 'name': 'Cookies' },
{ 'number': 5, 'price': 180, 'name': 'Gummy bears' },
{ 'number': 6, 'price': 500, 'name': 'Condoms' },
{ 'number': 7, 'price': 120, 'name': 'Crackers' },
{ 'number': 8, 'price': 220, 'name': 'Potato chips' },
{ 'number': 9, 'price': 80, 'name': 'Small snack' }
]
print(vending_machine(products, 500, 8)) |
bdd4c91465121a0b9d6692f2ace3a71e37ac9e24 | GaganDureja/Algorithm-practice | /bin_consecutive.py | 395 | 3.75 | 4 | # This problem was asked by Stripe.
# Given an integer n, return the length of the longest consecutive run of
# 1s in its binary representation.
# For example, given 156, you should return 3.
def bin_consecutive(n):
lst = []
count = 0
for x in bin(n):
if x=='1':
count+=1
else:
lst.append(count)
count=0
return max(lst)
print(bin_consecutive(156)) |
211c1129fbe5965c1e1c8c8981231c68bcb43421 | tangjiaxing669/magedu_worker | /work_3.py | 170 | 3.890625 | 4 | #!/usr/bin/env python
rep_list = [1, 3, 2, 4, 3, 2, 5, 5, 7]
list_temp = []
for i in rep_list:
if i not in list_temp:
list_temp.append(i)
print(list_temp)
|
935ccb971b74f78ee14b5d0079f46c2f2ba00e28 | xinbingzhe/Tianchidata_taobaorec | /count_term_match.py | 168 | 3.515625 | 4 | def count_term_match(test_term,match_term):
count = 0
for tt in test_term:
if tt!='':
count = count + match_term.count(tt)
return count
|
6a18a4213fe1f83c4e110bc0cbda1b4aa85f53dd | Andrej300/tdd_fizzbuzz | /src/fizzbuzz.py | 288 | 3.84375 | 4 | def fizzbuzz(number):
if number == 3:
return "fizz"
elif number == 5:
return "buzz"
elif number == 15:
return "fizzbuzz"
elif number == 4:
return "4"
elif number % 15 == 0:
return "fizzbuzz"
# THE FUNCTION CREATED SUCCESFULLY |
d69edfd1a15a4ac77d29c0392dd1ea8db3d55352 | Tallequalle/Code_wars | /Perimeter.py | 415 | 3.984375 | 4 | #The function perimeter has for parameter n where n + 1 is the number of squares (they are numbered from 0 to n) and returns the total perimeter of all the squares.
def fib(n):
if n == 0:
return 0
elif n in (1,2):
return 1
else:
return fib(n - 1) + fib(n - 2)
def perimeter(n):
sum = 0
for i in range(n + 2):
sum += fib(i)
return 4 * sum
perimeter(30)
|
cfc8a7e2d9bd3de03f4a654826838aacdec32586 | Tallequalle/Code_wars | /Task23.py | 771 | 3.859375 | 4 | #In mathematics, a Diophantine equation is a polynomial equation, usually with two or more unknowns, such that only the integer solutions are sought or studied.
#In this kata we want to find all integers x, y (x >= 0, y >= 0) solutions of a diophantine equation of the form:
#x2 - 4 * y2 = n
#(where the unknowns are x and y, and n is a given positive number) in decreasing order of the positive xi.
#If there is no solution return [] or "[]" or "". (See "RUN SAMPLE TESTS" for examples of returns).
def sol_equa(n):
# your code
lst = []
for x in range(n,0,-1):
y = 0
while x**2 - 4 * (y**2) > 0 :
answer = (x - 2*y) * (x + 2*y)
if answer == n:
lst.append([x,y])
y += 1
return lst
|
47f8c6b8f6c8b01f0bc66d998fdd4c039bf91572 | Tallequalle/Code_wars | /Task15.py | 728 | 4.125 | 4 | #A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence "The quick brown fox jumps over the lazy dog" is a pangram, because it uses the letters A-Z at least once (case is irrelevant).
#Given a string, detect whether or not it is a pangram. Return True if it is, False if not. Ignore numbers and punctuation.
import string
def is_pangram(s):
s = s.lower()
alphabet = ['q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m']
for i in alphabet:
if i in s:
continue
else:
return False
return True
pangram = "The quick, Brown fox jumps over the lazy dog!"
is_pangram(pangram)
|
f07319d009817401342e4c7691d90c2a1c5121bd | Tallequalle/Code_wars | /Task9.py | 301 | 3.59375 | 4 | def order(sentence):
# code here
dict = {}
lst = []
for i in sentence.split():
for j in range(len(sentence.split()) + 1):
if str(j) in i:
dict[j] = i
for i in range(1,len(sentence.split()) + 1):
lst.append(dict[i])
return ' '.join(lst)
order("is2 Thi1s T4est 3a")
|
bc0f1c5b564e30b27364dd3dce13b62e493affa2 | Deepdesh/data-prework | /snail-and-well.py | 5,845 | 4.3125 | 4 | #!/usr/bin/env python
# coding: utf-8
# <img src="https://bit.ly/2VnXWr2" width="100" align="left">
# # The Snail and the Well
#
# A snail falls at the bottom of a 125 cm well. Each day the snail rises 30 cm. But at night, while sleeping, slides 20 cm because the walls are wet. How many days does it take for the snail to escape the well?
#
# **Hint**: The snail gets out of the well when it surpasses the 125cm of height.
#
# ## Tools
#
# 1. Loop: **while**
# 2. Conditional statements: **if-else**
# 3. Function: **print()**
#
# ## Tasks
#
# #### 1. Assign the challenge data to variables with representative names: `well_height`, `daily_distance`, `nightly_distance` and `snail_position`.
# In[2]:
#assigning data to variables with representative names. DD
#distance from top of well to the bottom of well
well_height = 125
#distance snail climbs up each day
daily_distance = 30
#distance snail slips each night due to wet surface
nightly_distance = 20
#snail is at the bottom on the first day
snail_position = 0
# #### 2. Create a variable `days` to keep count of the days that pass until the snail escapes the well.
#
# In[3]:
days = 1 #considering first day as day 1 when snaily embarks on the climb
# #### 3. Find the solution to the challenge using the variables defined above.
# In[4]:
#print("Snaily at rock bottom.")
distance_difference = daily_distance - nightly_distance
snail_position += distance_difference
while snail_position < well_height:
snail_position += distance_difference
days = days + 1
#print("Snaily still climbing...")
#print("Snaily climbed and is out in ", days,"!!!")
# #### 4. Print the solution.
# In[5]:
if snail_position < well_height:
print("Snaily still climbing...")
elif snail_position == well_height:
print("Snaily almost there")
else:
print("Snaily made it to the top on the ", days,"th day!!!")
# ## Bonus
# The distance traveled by the snail each day is now defined by a list.
# ```
# advance_cm = [30, 21, 33, 77, 44, 45, 23, 45, 12, 34, 55]
# ```
# On the first day, the snail rises 30cm but during the night it slides 20cm. On the second day, the snail rises 21cm but during the night it slides 20cm, and so on.
#
# #### 1. How many days does it take for the snail to escape the well?
# Follow the same guidelines as in the previous challenge.
#
# **Hint**: Remember that the snail gets out of the well when it surpasses the 125cm of height.
# In[6]:
advance_cm = [30,21,33,77,44,45,23,45,12,34,55]
days = 0
climb_acc = 0
well_height_a = well_height + 1
#while (i < len(advance_cm)):
for i in advance_cm:
climb_acc += i - 20
left_acc = 125 - climb_acc
days = days + 1
#i += 1
#while climb_acc < well_height_a:
#print("Still climbing!",left_acc,"cm more to go!")
if climb_acc < well_height:
print("Still climbing!",left_acc,"cm more to go!")
elif climb_acc > well_height:
print("Snaily out of the well!!", climb_acc," cm climbed in", days, "days")
#while climb_acc < well_height_a:
#print("Done and dusted!", climb_acc," cm climbed in", days, "days")
else:
print("Snaily has already escaped, and on this", days, "th day he just kept moving")
#print("test", days, climb_acc)
# #### 2. What is its maximum displacement in one day? And its minimum? Calculate the displacement using only the travel distance of the days used to get out of the well.
# **Hint**: Remember that displacement means the total distance risen taking into account that the snail slides at night.
# In[7]:
displacement_acc_list = []
#distance travelled is total (irrespective of direction), displacement is the shortest distance traveled.
#assuming here that the question and hint means displacement = advance_cm - slide_cm
for i in advance_cm:
displacement_per_day = i-20
displacement_acc_list.append(displacement_per_day)
print(displacement_acc_list) #displacement list printing
list_only_in_well = displacement_acc_list[:6]
list_only_in_well
print("Maximum displacement: ",max(list_only_in_well))
print("Minimum displacement: ",min(list_only_in_well))
# #### 3. What is its average progress? Take into account the snail slides at night.
# In[8]:
#Assumption: Progess is gain in terms of old_position vs new_postion,displacement and/or left_to_climb
#since we have been dealing with displacement, proceeding with average progress in terms of displacement as it also accounts for sliding at night
average_progress_during_well = sum(list_only_in_well)/len(list_only_in_well)
average_progress_overall = sum(displacement_acc_list)/len(displacement_acc_list)
print("Average progress while climbing up the well: ", average_progress_during_well)
print("Average progress overall: ", average_progress_overall)
# #### 4. What is the standard deviation of its displacement? Take into account the snail slides at night.
# In[9]:
import math
#for the population list (including distance traveled by snaily after the great escape)
list_1 = []
for i in displacement_acc_list:
diff_mean_obs = i - average_progress_overall
diff_mean_obs_sq = diff_mean_obs**2
list_1.append(diff_mean_obs_sq)
sum_1 = sum(list_1)
div_obs_no = sum_1/len(list_1)
stdev_1 = math.sqrt(div_obs_no)
#for the observations (before snaily's great escape)
list_2 = []
for i in list_only_in_well:
diff_mean_obs_dw = i - average_progress_during_well
diff_mean_obs_sq_dw = diff_mean_obs_dw**2
list_2.append(diff_mean_obs_sq_dw)
sum_2 = sum(list_2)
div_obs_no_dw = sum_2/len(list_2)
stdev_2 = math.sqrt(div_obs_no_dw)
# In[10]:
print("standard deviation of displacement (population): ",stdev_1)
print("standard deviation of displacement (only observations during well): ",stdev_2)
# In[ ]:
|
d4732957153731bb76ae6d2881fb68ce5c52441c | Serendipity0618/python-practice | /zero_number_end2.py | 351 | 4.03125 | 4 | def factorial(n) :
product = 1
while n > 0:
product = product * n
n = n - 1
return product
n = input("Please input x:")
product = factorial(int(n))
print(product)
str = list(str(product))
#print(str)
i = -1
counter = 0
while int(str[i]) == 0:
counter = counter + 1
i = i - 1
print(counter)
|
a739fe164438f5caf866c2aa2a580e76cabb01cd | gciotto/learning-python | /part6/exercise3/mylistsub.py | 1,584 | 3.625 | 4 | from exercise2.listwrapper import Mylist
class MylistSub (Mylist):
number_of_calls = 0
def __init__ (self, data = []):
MylistSub.number_of_calls += 1
Mylist.__init__(self, data)
def __add__ (self, other):
MylistSub.number_of_calls += 1
if type (other) == MylistSub:
return MylistSub(self.data + other.data)
return MylistSub(Mylist.__add__(self, other))
def __mul__ (self, other):
MylistSub.number_of_calls += 1
return MylistSub(Mylist.__mul__(self, other))
def __getitem__ (self, index):
MylistSub.number_of_calls += 1
return Mylist.__getitem__(self, index)
def __len__ (self):
MylistSub.number_of_calls += 1
return Mylist.__len__(self)
def __getslice__ (self, start, end):
MylistSub.number_of_calls += 1
return Mylist.__getslice__(self, start, end)
def append (self, data):
MylistSub.number_of_calls += 1
Mylist.append(self, data)
def __repr__ (self):
MylistSub.number_of_calls += 1
return Mylist.__repr__(self)
def getNumberOfCalls ():
return MylistSub.number_of_calls
getNumberOfCalls = staticmethod (getNumberOfCalls)
if __name__ == '__main__':
x = MylistSub ([1, 2, 3])
print (x + [2, 3, 5])
print ((x * 8), (x * 8)[4])
print ((x * 8)[4:7])
print (x + MylistSub([111, 88, 99]))
print (MylistSub (MylistSub ([2, 3 , 99])))
print (MylistSub.getNumberOfCalls()) |
4cff39203e317f4b8081b0f30b32a7d357a75db1 | gciotto/learning-python | /part6/exercise2/listwrapper.py | 1,022 | 3.859375 | 4 | class Mylist():
def __init__ (self, data = []):
self.data = []
for item in data:
self.data.append(item)
def __add__ (self, other):
if type (other) == Mylist :
return Mylist(self.data + other.data)
return Mylist(self.data + other)
def __mul__ (self, other):
return Mylist(self.data * other)
def __getitem__ (self, index):
return self.data[index]
def __len__ (self):
return len (self.data)
def __getslice__ (self, start, end):
return Mylist(self.data [start:end])
def append (self, data):
self.data.append(data)
def __repr__ (self):
return "%s" % self.data
if __name__ == '__main__':
x = Mylist ([1, 2, 4])
print (x + [2, 3, 5])
print ((x * 8), (x * 8)[4])
print ((x * 8)[4:7])
print (x + Mylist([111, 88, 99]))
print (Mylist (Mylist ([2, 3 , 99])))
|
091718f2cf95ce96ff8d3aa2704068d25e650121 | wsargeant/aoc2020 | /day_1.py | 1,383 | 4.34375 | 4 | def read_integers(filename):
""" Returns list of numbers from file containing list of numbers separated by new lines
"""
infile = open(filename, "r")
number_list = []
while True:
num = infile.readline()
if len(num) == 0:
break
if "\n" in num:
num = num[:-1]
number_list.append(int(num))
return(number_list)
def sum_2020(filename):
"""Returns two numbers from number list in filename which sum to 2020 and their product
"""
number_list = read_integers(filename)
target = 2020
for num1 in number_list:
num2 = target - num1
if num2 in number_list and num2 != num1:
break
return num1, num2, num1*num2
def sum_2020_by_3(filename):
"""Returns three numbers from number list in filename which sum to 2020 and their product
"""
number_list = read_integers(filename)
#reversed_number_list = number_list.copy()
#reversed_number_list.reverse()
target = 2020
for i in range(len(number_list)):
num1 = number_list[i]
for j in range(i,len(number_list)):
num2 = number_list[j]
num3 = target - num1 - num2
if num3 >= 0 and num3 in number_list:
return num1, num2, num3, num1*num2*num3
return False
print(sum_2020("day_1.txt"))
print(sum_2020_by_3("day_1.txt")) |
0e5c146079914aa6bab5f783d98c0dc0bcdeb6f5 | hungdoan888/algo_expert | /rightSiblingTree.py | 1,770 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 13 17:43:39 2021
@author: hungd
"""
# This is the class of the input root. Do not edit it.
class BinaryTree:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def insert(self, values, i=0):
if i >= len(values):
return
queue = [self]
while len(queue) > 0:
current = queue.pop(0)
if current.left is None:
current.left = BinaryTree(values[i])
break
queue.append(current.left)
if current.right is None:
current.right = BinaryTree(values[i])
break
queue.append(current.right)
self.insert(values, i + 1)
return self
def rightSiblingTree(root):
# Write your code here.
rightSiblingTreeHelper(root, None, True)
return root
def rightSiblingTreeHelper(node, parent, leftNode):
# Write your code here.
if node.left is not None:
rightSiblingTreeHelper(node.left, node, True)
rightNode = node.right
if parent is None:
node.right = None
elif leftNode:
node.right = parent.right
else:
if parent.right is not None:
node.right = parent.right.left
else:
node.right = None
if rightNode is not None:
rightSiblingTreeHelper(rightNode, node, False)
root = BinaryTree(1).insert([2, 3, 4, 5, 6, 7, 8, 9])
root.left.right.right = BinaryTree(10)
root.right.left.left = BinaryTree(11)
root.right.right.left = BinaryTree(12)
root.right.right.right = BinaryTree(13)
root.right.left.left.left = BinaryTree(14)
node = rightSiblingTree(root) |
4a39a20896255a548630d1b25d2811a034788e4f | hungdoan888/algo_expert | /reverseWordsInString.py | 534 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 2 20:32:31 2021
@author: hungd
"""
def reverseWordsInString(string):
# Write your code here.
newString = ""
prevI = len(string)
hasSpaces = False
for i in reversed(range(len(string))):
if string[i] == " ":
newString += string[i:prevI]
prevI = i
hasSpaces = True
return newString[1:] + " " + string[:prevI] if hasSpaces else string
string = "AlgoExpert is the best!"
reverseWordsInString(string) |
60222725d3f34393d03e644196e94bb59250a24d | hungdoan888/algo_expert | /ThreeNumberSum2.py | 633 | 4.03125 | 4 | def threeNumberSum(array, targetSum):
threeNumberList = list()
array.sort()
for i in range(len(array) - 2):
low = i + 1
high = len(array) - 1
while low < high:
if array[i] + array[low] + array[high] == targetSum:
threeNumberList.append([array[i], array[low], array[high]])
low = low + 1
elif array[i] + array[low] + array[high] < targetSum:
low = low + 1
else:
high = high - 1
return threeNumberList
array = [12, 3, 1, 2, -6, 5, -8, 6]
targetSum = 0
print(threeNumberSum(array, targetSum))
|
446a02bb4cb33ebf28bb3d527d89b4ce476eb7cc | hungdoan888/algo_expert | /diskStacking.py | 1,156 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 16 10:58:33 2020
@author: hungd
"""
def diskStacking(disks):
# Write your code here.
disks.sort(key=lambda disk:disk[2])
heights = [[0, []] for _ in range(len(disks))]
for i in range(len(disks)):
maxHeight = disks[i][2]
maxHeightJ = None
for j in reversed(range(i)):
if disks[j][0] < disks[i][0] and \
disks[j][1] < disks[i][1] and \
disks[j][2] < disks[i][2]:
height = disks[i][2] + heights[j][0]
if height > maxHeight:
maxHeight = height
maxHeightJ = j
heights[i][0] = maxHeight
if maxHeightJ is not None:
heights[i][1] = heights[maxHeightJ][1] + [disks[i]]
else:
heights[i][1] = [disks[i]]
maxHeight = 0
for i in range(len(heights)):
if heights[i][0] > maxHeight:
maxHeightArray = heights[i][1]
maxHeight = heights[i][0]
return maxHeightArray
disks = [[2, 1, 2], [3, 2, 3], [2, 2, 8], [2, 3, 4], [1, 3, 1], [4, 4, 5]]
diskStacking(disks) |
32b1a830efb26d7a935de27dd6940c96823a73aa | hungdoan888/algo_expert | /removeIslands.py | 1,345 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 26 16:50:44 2020
@author: hungd
"""
def removeIslands(matrix):
# Write your code here.
visited = [[0 for j in range(len(matrix[0]))] for i in range(len(matrix))]
i = 0
for j in range(len(matrix[0])):
matrixTraverse(matrix, visited, i, j)
i = len(matrix) - 1
for j in range(len(matrix[0])):
matrixTraverse(matrix, visited, i, j)
j = 0
for i in range(1, len(matrix)-1):
matrixTraverse(matrix, visited, i, j)
j = len(matrix[0]) - 1
for i in range(1, len(matrix)-1):
matrixTraverse(matrix, visited, i, j)
return visited
def matrixTraverse(matrix, visited, i, j):
if i < 0 or i >= len(matrix):
return
if j < 0 or j >= len(matrix[0]):
return
if visited[i][j] == 1:
return
if matrix[i][j] == 0:
return
visited[i][j] = 1
matrixTraverse(matrix, visited, i-1, j) # Up
matrixTraverse(matrix, visited, i+1, j) # Down
matrixTraverse(matrix, visited, i, j-1) # Left
matrixTraverse(matrix, visited, i, j+1) # Right
matrix = [
[1, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 1, 1],
[0, 0, 1, 0, 1, 0],
[1, 1, 0, 0, 1, 0],
[1, 0, 1, 1, 0, 0],
[1, 0, 0, 0, 0, 1]
]
removeIslands(matrix) |
f4497789caa2482b7590e11a57107076154d497b | hungdoan888/algo_expert | /sudoku.py | 4,958 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 2 21:05:15 2021
@author: hungd
"""
def solveSudoku(board):
# Write your code here.
board_truth = [list(x) for x in board]
i = 0
while i < 9:
j = 0
while j < 9:
if board_truth[i][j] != 0:
j += 1
continue
# insert value and check if it is ok
OkToInsert = insertValidValue(board, 1, i, j)
# if it is not possible, backtrack
if not OkToInsert:
i, j = backtrack(board, board_truth, i, j)
j += 1
i += 1
return board
def backtrack(board, board_truth, row, col):
board[row][col] = 0
if col == 0:
col = 9
else:
row += 1
for i in reversed(range(row)):
for j in reversed(range(col)):
if board_truth[i][j] != 0:
continue
OkToInsert = insertValidValue(board, board[i][j] + 1, i, j)
# if it is not possible, backtrack
if not OkToInsert:
board[i][j] = 0
else:
return i, j
col = 9
# Valid Value
def insertValidValue(board, start, i, j):
for value in range(start, 10):
board[i][j] = value
if isValidInRow(board, i, j) and isValidInCol(board, i, j) and isValidInGrid(board, i, j):
return True
return False
# Valid Row checker
def isValidInRow(board, row, col):
for j in range(9):
if col == j:
continue
if board[row][col] == board[row][j]:
return False
return True
# Valid column checker
def isValidInCol(board, row, col):
for i in range(9):
if row == i:
continue
if board[row][col] == board[i][col]:
return False
return True
# Valid Grid Checker
def isValidInGrid(board, row, col):
# Grid 1
if row < 3 and col < 3:
for i in range(3):
for j in range(3):
if row == i and col == j:
continue
if board[row][col] == board[i][j]:
return False
# Grid 2
elif row < 3 and (col >= 3 and col < 6):
for i in range(3):
for j in range(3, 6):
if row == i and col == j:
continue
if board[row][col] == board[i][j]:
return False
# Grid 3
elif row < 3 and col >= 6:
for i in range(3):
for j in range(6, 9):
if row == i and col == j:
continue
if board[row][col] == board[i][j]:
return False
# Grid 4
elif (row >= 3 and row < 6) and col < 3:
for i in range(3, 6):
for j in range(3):
if row == i and col == j:
continue
if board[row][col] == board[i][j]:
return False
# Grid 5
elif (row >= 3 and row < 6) and (col >= 3 and col < 6):
for i in range(3, 6):
for j in range(3, 6):
if row == i and col == j:
continue
if board[row][col] == board[i][j]:
return False
# Grid 6
elif (row >= 3 and row < 6) and col >= 6:
for i in range(3, 6):
for j in range(6, 9):
if row == i and col == j:
continue
if board[row][col] == board[i][j]:
return False
# Grid 7
elif row >= 6 and col < 3:
for i in range(6, 9):
for j in range(3):
if row == i and col == j:
continue
if board[row][col] == board[i][j]:
return False
# Grid 8
elif row >= 6 and (col >= 3 and col < 6):
for i in range(6, 9):
for j in range(3, 6):
if row == i and col == j:
continue
if board[row][col] == board[i][j]:
return False
# Grid 9
else:
for i in range(6, 9):
for j in range(6, 9):
if row == i and col == j:
continue
if board[row][col] == board[i][j]:
return False
return True
board = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, 7, 0, 4, 0, 2, 6, 0],
[0, 0, 1, 0, 5, 0, 9, 3, 0],
[9, 0, 4, 0, 6, 0, 0, 0, 5],
[0, 7, 0, 3, 0, 0, 0, 1, 2],
[1, 2, 0, 0, 0, 7, 4, 0, 0],
[0, 4, 9, 2, 0, 6, 0, 0, 7]
]
solveSudoku(board) |
efd35c7698960a4088f61397ee23fde3defb21ee | hungdoan888/algo_expert | /suffixTrieConstruction.py | 1,209 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 24 13:23:31 2020
@author: hungd
"""
# Do not edit the class below except for the
# populateSuffixTrieFrom and contains methods.
# Feel free to add new properties and methods
# to the class.
class SuffixTrie:
def __init__(self, string):
self.root = {}
self.endSymbol = "*"
self.populateSuffixTrieFrom(string)
def populateSuffixTrieFrom(self, string):
# Write your code here.
for i in range(len(string)):
self.populateSuffixTrieFromHelper(string, i)
def populateSuffixTrieFromHelper(self, string, i):
node = self.root
for j in range(i, len(string)):
if string[j] not in node:
node[string[j]] = {}
node = node[string[j]]
node[self.endSymbol] = True
def contains(self, string):
# Write your code here.
node = self.root
for i in range(len(string)):
if string[i] not in node:
return False
node = node[string[i]]
if self.endSymbol not in node:
return False
else:
return True
string = "abcdba"
x = SuffixTrie(string) |
ae60f245873fbd99e43f2abfa82f4c5dc1075066 | hungdoan888/algo_expert | /matchingCalendars.py | 3,253 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 7 20:43:15 2021
@author: hungd
"""
def calendarMatching(calendar1, dailyBounds1, calendar2, dailyBounds2, meetingDuration):
# Write your code here.
calendar1 = putDailyBoundsinCalendar(dailyBounds1, calendar1)
calendar2 = putDailyBoundsinCalendar(dailyBounds2, calendar2)
calendar = mergeCalendars(calendar1, calendar2)
possibleTimes = getPossibleMeetingTimes(calendar, meetingDuration)
return possibleTimes
def convertTimeToMinutes(time):
timeArray = time.split(":")
minutes = int(timeArray[0]) * 60 + int(timeArray[1])
return minutes
def getPossibleMeetingTimes(calendar, duration):
possibleTimes = []
for i in range(1, len(calendar)):
meeting1End = convertTimeToMinutes(calendar[i - 1][1])
meeting2Start = convertTimeToMinutes(calendar[i][0])
if meeting1End >= meeting2Start:
continue
if meeting2Start - meeting1End >= duration:
possibleTimes.append([calendar[i - 1][1], calendar[i][0]])
return possibleTimes
def mergeCalendars(calendar1, calendar2):
idx1 = 0
idx2 = 0
calendar = []
while idx1 < len(calendar1) or idx2 < len(calendar2):
if idx1 >= len(calendar1):
calendar.append(calendar2[idx2])
idx2 += 1
elif idx2 >= len(calendar2):
calendar.append(calendar1[idx1])
idx1 += 1
else:
calendar1StartTime = convertTimeToMinutes(calendar1[idx1][0])
calendar2StartTime = convertTimeToMinutes(calendar2[idx2][0])
if calendar1StartTime == calendar2StartTime:
calendar1StopTime = convertTimeToMinutes(calendar1[idx1][1])
calendar2StopTime = convertTimeToMinutes(calendar2[idx2][1])
if calendar1StopTime <= calendar2StopTime:
calendar.append(calendar1[idx1])
idx1 += 1
else:
calendar.append(calendar2[idx2])
idx2 += 1
elif calendar1StartTime < calendar2StartTime:
calendar.append(calendar1[idx1])
idx1 += 1
else:
calendar.append(calendar2[idx2])
idx2 += 1
# Ensuring end times come after end times
for i in range(1, len(calendar)):
presentStop = convertTimeToMinutes(calendar[i][1])
pastStop = convertTimeToMinutes(calendar[i - 1][1])
if pastStop > presentStop:
calendar[i][1] = calendar[i - 1][1]
return calendar
def putDailyBoundsinCalendar(dailyBounds, calendar):
beforeWork = ["0:00", dailyBounds[0]]
afterWork = [dailyBounds[1], "24:00"]
calendar.insert(0, beforeWork)
calendar.append(afterWork)
return calendar
calendar1 = [
["10:00", "10:30"],
["10:45", "11:15"],
["11:30", "13:00"],
["14:15", "16:00"],
["16:00", "18:00"]
]
dailyBounds1 = ["9:30", "20:00"]
calendar2 = [
["10:00", "11:00"],
["12:30", "13:30"],
["14:30", "15:00"],
["16:00", "17:00"]
]
dailyBounds2 = ["9:00", "18:30"]
meetingDuration = 15
calendarMatching(calendar1, dailyBounds1, calendar2, dailyBounds2, meetingDuration)
|
cdbb3a25cc828a42d79c7a60eadda96c4523024a | hungdoan888/algo_expert | /continuousMedian.py | 5,256 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 24 19:23:04 2020
@author: hungd
"""
#%% Max Heap Class
class MaxHeap:
def __init__(self, array):
# Do not edit the line below.
self.heap = array
self.heap = self.buildHeap()
def buildHeap(self):
array = self.heap
# Write your code here.
lastParentIdx = max((len(array) - 2) // 2, 0)
for i in reversed(range(lastParentIdx + 1)):
self.siftDown(i)
return array
def siftDown(self, parentIdx):
array = self.heap
# Write your code here.
lastParentIdx = (len(array) - 2) // 2
if parentIdx > lastParentIdx:
return
childOneIdx = 2 * parentIdx + 1
childTwoIdx = min(2 * parentIdx + 2, len(array) - 1)
if array[childOneIdx] >= array[childTwoIdx]:
childIdx = childOneIdx
else:
childIdx = childTwoIdx
if array[childIdx] <= array[parentIdx]:
return
self.swap(childIdx, parentIdx)
return self.siftDown(childIdx)
def siftUp(self, childIdx):
# Write your code here.
array = self.heap
if childIdx == 0:
return
parentIdx = (childIdx - 1) // 2
if array[childIdx] <= array[parentIdx]:
return
self.swap(childIdx, parentIdx)
return self.siftUp(parentIdx)
def peek(self):
array = self.heap
# Write your code here.
return array[0]
def remove(self):
array = self.heap
# Write your code here.
self.swap(0, len(array) - 1)
value2remove = array.pop()
self.siftDown(0)
return value2remove
def insert(self, value):
array = self.heap
# Write your code here.
array.append(value)
childIdx = len(array) - 1
self.siftUp(childIdx)
def swap(self, i, j):
array = self.heap
array[i], array[j] = array[j], array[i]
#%% Min Heap Class
class MinHeap:
def __init__(self, array):
# Do not edit the line below.
self.heap = array
self.heap = self.buildHeap()
def buildHeap(self):
array = self.heap
# Write your code here.
lastParentIdx = max((len(array) - 2) // 2, 0)
for i in reversed(range(lastParentIdx + 1)):
self.siftDown(i)
return array
def siftDown(self, parentIdx):
array = self.heap
# Write your code here.
lastParentIdx = (len(array) - 2) // 2
if parentIdx > lastParentIdx:
return
childOneIdx = 2 * parentIdx + 1
childTwoIdx = min(2 * parentIdx + 2, len(array) - 1)
if array[childOneIdx] <= array[childTwoIdx]:
childIdx = childOneIdx
else:
childIdx = childTwoIdx
if array[childIdx] >= array[parentIdx]:
return
self.swap(childIdx, parentIdx)
return self.siftDown(childIdx)
def siftUp(self, childIdx):
# Write your code here.
array = self.heap
if childIdx == 0:
return
parentIdx = (childIdx - 1) // 2
if array[childIdx] >= array[parentIdx]:
return
self.swap(childIdx, parentIdx)
return self.siftUp(parentIdx)
def peek(self):
array = self.heap
# Write your code here.
return array[0]
def remove(self):
array = self.heap
# Write your code here.
self.swap(0, len(array) - 1)
value2remove = array.pop()
self.siftDown(0)
return value2remove
def insert(self, value):
array = self.heap
# Write your code here.
array.append(value)
childIdx = len(array) - 1
self.siftUp(childIdx)
def swap(self, i, j):
array = self.heap
array[i], array[j] = array[j], array[i]
#%% Continuous Median
class ContinuousMedianHandler:
def __init__(self):
# Write your code here.
self.median = None
self.x = MaxHeap([])
self.y = MinHeap([])
def insert(self, number):
# Write your code here.
x = self.x
y = self.y
if not x.heap:
x.insert(number)
elif not y.heap:
if number <= x.peek():
y.insert(x.remove())
x.insert(number)
else:
y.insert(number)
elif number <= x.peek():
x.insert(number)
else:
y.insert(number)
if len(x.heap) > len(y.heap) + 1:
y.insert(x.remove())
elif len(x.heap) + 1 < len(y.heap):
x.insert(y.remove())
if (len(x.heap) + len(y.heap)) % 2 == 0:
self.median = (x.peek() + y.peek()) / 2
else:
if len(x.heap) > len(y.heap):
self.median = x.peek()
else:
self.median = y.peek()
print(x.heap, y.heap, self.median)
def getMedian(self):
return self.median
array = [48, 12, 24, 7, 8, -5, 24, 391, 24, 56, 2, 6, 8, 41]
z = ContinuousMedianHandler()
|
40b5bb8e27346b778a7c396ca92c28d16e3d57ef | hungdoan888/algo_expert | /cycleInGraph.py | 870 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 21 20:41:01 2021
@author: hungd
"""
def cycleInGraph(edges):
# Write your code here.
visited = {}
for i in range(len(edges)):
containsCycle = cycleInGraphHelper(i, edges, visited, {})
if containsCycle:
return True
return False
def cycleInGraphHelper(node, edges, visited, visiting):
print(node, visited, visiting)
if node in visiting:
return True
if node in visited:
return False
visited[node] = True
visiting[node] = True
for i in range(len(edges[node])):
containsCycle = cycleInGraphHelper(edges[node][i], edges, visited, dict.copy(visiting))
if containsCycle:
return True
return False
edges = [[1, 3], [2, 3, 4], [0], [], [2, 5], []]
cycleInGraph(edges) |
f07b0f5817a383e1ce6166b0c315579983e7d120 | patrick330602/stochastic-mab | /prog1_random_selection.py | 3,010 | 4.09375 | 4 | # This is the first program to simulate the multi-arm bandit
# Let say we only use RANDOM POLICY: each round, just randomly pick an arm
# Each arm has outcome 0 or 1, with probability 1 being the winning probability (Bernoulli distribution)
# Created by John C.S. Lui Date: April 10, 2020
import numpy as np
from scipy.stats import bernoulli # import bernoulli
import matplotlib.pyplot as plt
Num_of_Arms = 4 # number of arms
# input parameters
winning_parameters = np.array([0.2, 0.3, 0.85, 0.9], dtype=float)
max_prob = 0.9 # record the highest probability of winning for all arms
optimal_arm = 3 # index for the optimal arm
T = 1000 # number of rounds to simulate
total_iteration = 200 # number of iterations to the MAB simulation
reward_round_iteration = np.zeros((T), dtype=int) # reward in each round average by # of iteration
# Go through T rounds, each round we need to select an arm
for iteration_count in range(total_iteration):
for round in range(T):
select_arm = np.random.randint(Num_of_Arms, size=1) # randomly select an arm
# generate reward for the selected arm
reward = bernoulli.rvs(winning_parameters[select_arm])
if reward == 1 :
reward_round_iteration[round] += 1
# compute average reward for each round
average_reward_in_each_round = np.zeros (T, dtype=float)
for round in range(T):
average_reward_in_each_round[round] = float(reward_round_iteration[round])/float(total_iteration)
# Let generate X and Y data points to plot it out
cumulative_optimal_reward = 0.0
cumulative_reward = 0.0
X = np.zeros (T, dtype=int)
Y = np.zeros (T, dtype=float)
for round in range(T):
X[round] = round
cumulative_optimal_reward += max_prob
cumulative_reward += average_reward_in_each_round[round]
Y[round] = cumulative_optimal_reward - cumulative_reward
print('After ',T,'rounds, regret is: ', cumulative_optimal_reward - cumulative_reward)
#f = plt.figure()
#plt.plot(X, Y, color = 'red', ms = 5, label='linear regret')
#plt.ylim(ymin = 0)
#plt.xlabel('round number')
#plt.ylabel('regret')
#plt.title('Regret for Random Arm Selection policy')
#plt.legend()
#plt.grid(True)
#plt.xlim(0, T)
#plt.savefig("prog1_figure.png")
#plt.show()
fig, axs = plt.subplots(2) # get two figures, top is regret, bottom is average reward in each round
fig.suptitle('Performance of Random Arm Selection')
fig.subplots_adjust(hspace=0.5)
axs[0].plot(X,Y, color = 'red', label='Regret of RSP')
axs[0].set(xlabel='round number', ylabel='Regret')
axs[0].grid(True)
axs[0].legend(loc='upper left')
axs[0].set_xlim(0,T)
axs[0].set_ylim(0,1.1*(cumulative_optimal_reward - cumulative_reward))
axs[1].plot(X, average_reward_in_each_round, color = 'black', label='average reward')
axs[1].set(xlabel='round number', ylabel='Average Reward per round')
axs[1].grid(True)
axs[1].legend(loc='upper left')
axs[1].set_xlim(0,T)
axs[1].set_ylim(0,1.0)
plt.savefig("prog1_figure.png")
plt.show()
|
370fc45b3df47accb59bb98ae9b11a56f9bd5511 | willxie/action-conditional-video-prediction-with-motion-equivariance-regularizer | /scripts/format_image_file_names.py | 773 | 3.65625 | 4 | import sys
import os
def is_int(s):
try:
int(s)
return True
except ValueError:
return False
def main():
""" Put enough prepending 0 padding according to the README """
if len(sys.argv) != 2:
print("Usage: target_dir")
exit()
root_dir = os.getcwd()
target_dir = root_dir + "/" + sys.argv[1]
for input_file in os.listdir(target_dir):
filename, file_extension = os.path.splitext(input_file)
if is_int(filename):
new_filename = "{num:05d}".format(num=int(filename))
os.rename(target_dir + input_file, target_dir + new_filename+file_extension)
else:
print(input_file + " does not have an number filename")
if __name__ == "__main__":
main()
|
6ce809c0589f2e3993d4b3c5d495805d0400545e | SurajKB11/Python_Tkinter_Module_1 | /new1.py | 579 | 3.578125 | 4 | from Tkinter import *
from PIL import ImageTk,Image
root=Tk()
root.title("Hello World")
root.iconbitmap("@/home/suraj/Desktop/INTERNSHIP/index.xbm")
def open():
global image
top=Toplevel()
image=ImageTk.PhotoImage(Image.open("/home/suraj/Desktop/INTERNSHIP/index.jpeg"))
l=Label(top,image=image)
l.pack()
#declaring image as global is important for some reason or we won't get the image in the second window
Button(top,text="close this window",command=top.destroy).pack()
Button(root,text="open second window",command=open).pack()
root.mainloop()
|
ed32d42d353918892d9fcecc947baec861be76d7 | phani111/Pythonex1 | /inheritance.py | 647 | 3.890625 | 4 | class Parent():
def __init__(self,last_name,eye_color):
print("parent construcot called")
self.last_name = last_name
self.eye_color = eye_color
def show_info(self):
print("Last Name - "+self.last_name)
print("Eye Color - "+self.eye_color)
class Child(Parent):
def __init__(self,last_name,eye_color,number_of_toys):
print("Child Constructor Called")
Parent.__init__(self,last_name,eye_color)
self.number_of_toys = number_of_toys
#billy_cyrus = Parent("Cyrus","blue")
#billy_cyrus.show_info()
milley_cyrus = Child("Cyrus","Blue",5)
milley_cyrus.show_info()
|
08e800c3cdcbfaa6f37a0aa98863a39d8260242c | AsiakN/flexi-Learn | /sets.py | 1,880 | 4.34375 | 4 | # A set is an unordered collection with no duplicates
# Basic use of sets include membership testing and eliminating duplicates in lists
# Sets can also implement mathematical operations like union, intersection etc
# You can create a set using set() or curly braces. You can only create an empty set using the set() method
# Another type of set exists called frozenset. Frozenset is immutable but set is mutable
basket = {'Apple', 'Banana', 'Avocado', 'pineapple', 'Apple', 'Orange'}
print(sorted(basket))
a = set('abracadabra')
b = set('alacazam')
print(a.intersection(b))
print(a | b) # The " | " operator means or. It sums elements in both sets. Union operation
print(a & b) # The " &" operator means and . It finds the elements in both a and b. Intersection operation
print(a ^ b) # The " ^ " operator means not. Finds the elements in one set but not in the other set. Symmetric difference
print(a.isdisjoint(b))
print(b.issubset(a))
# SET COMPREHENSIONS
s = {x for x in 'abracadabra' if x not in 'abc'}
print(s)
# METHODS IN SETS
# 1. UNION
#SYNTAX
# setA.union(setB)
# 2. INTERSECTION
# SYNTAX
# setA.intersection(setB)
# 3. DIFFERENCE
# SYNTAX
# setA.difference(setB)
# 4. SYMMETRIC DIFFERENCE
# SYNTAX
# setA.symmetric_difference(SetB)
# 5. DISJOINT
# SYNTAX
# setA.isdisjoint(setB)
# Returns true or false value
# 6. SUBSET
# SYNTAX
# setA.issubset(setB)
# Returns true or false value
# 7. SUPERSET
# SYNTAX
# setA.issuperset(setB)
# Returns true or false value
# 8. PROPER SUBSET/SUPERSET
# MODIFYING SETS
# 1. set.add(element)
# 2. set.remove(element)
# 3. Set.discard(element)
# 4. set.pop()
# 5. set.clear()
numbers = { 24, 67, 89,90, 78,78, 24 }
print(sum(numbers))
print(len(numbers)) |
7db7e72cd3e60a357f3acbffea2f833fd3c8dc2a | Fasermaler/Quick-Q | /vision/price_calculator.py | 2,413 | 3.71875 | 4 | '''
This class calculates the total price of the drinks
Author: Fasermaler
March 2019
'''
class price_calculator:
# initialize with the price list
def __init__(self, price_list):
self.set_price_list(price_list)
self.drinks_list = []
self.total_price = 0.0
self.old_ids = None
# subroutine to set the price list
def set_price_list(self, price_list):
self.price_list = price_list
self.pure_prices = {}
for i in price_list.values():
self.pure_prices[i[0]] = i[1]
print(self.pure_prices)
# calculates the total price and return a list of drinks in id order
# returns a list of drinks and the total price
def calculate_price(self, ids):
# reset the drinks list and total price
self.drinks_list = []
self.total_price = 0.0
self.old_ids = ids
#print(ids)
for i in range(len(ids)):
# get the ID
id_1 = ids[i][0]
#print(id_1)
try:
drink = self.price_list[str(id_1)][0]
self.total_price += self.price_list[str(id_1)][1]
self.drinks_list.append(drink)
except:
self.drinks_list.append(None)
# round the price
self.total_price = round(self.total_price, 2)
# adds more items to the drinks list and total price
# also returns the new id list with the new ids added
def add_item(self, ids):
for i in range(len(ids)):
# get the ID
id_1 = ids[i]
drink = self.price_list[str(id_1)][0]
self.total_price += self.price_list[str(id_1)][1]
self.drinks_list.append(drink)
# round the price
self.total_price = round(self.total_price, 2)
# Extend the ID list
self.old_ids.extend(ids)
# reset the prices, drinks list and ids
def reset_all(self):
self.drinks_list = []
self.total_price = 0.0
self.old_ids = None
## test code ##
# Define the price list
# prices = price_calculator({'66': ('bandung', 4.4), '69': ('lemon tea', 5.5)})
# prices.calculate_price([66,66,69,69,69,66])
# print("Drinks list: " + str(prices.drinks_list))
# print("Total Price: " + str(prices.total_price))
# # Add some drinks
# print("Adding some items")
# prices.add_item([66,69])
# print("Drinks list: " + str(prices.drinks_list))
# print("Total Price: " + str(prices.total_price))
# print("Total IDS: " + str(prices.old_ids))
# # Reset all
# print("Resetting All")
# prices.reset_all()
# print("Drinks list: " + str(prices.drinks_list))
# print("Total Price: " + str(prices.total_price))
# print("Total IDS: " + str(prices.old_ids)) |
fa2d68d2cf5d4602e62a783ece922fad17e2df04 | parulsethi86/project-test | /test2.py | 197 | 3.890625 | 4 | import sys as s
x = int(s.argv[1])
y = int(s.argv[2])
z = int(s.argv[3])
if x>y:
if x>z:
print("x is largest")
elif y>z:
print("y is largest")
else:
print("z is largest")
|
ec1ae83ac468971c4984f71912cb9d4404b846cb | ChrisLeeSlacker/Gauss | /Without Timer.py | 867 | 3.96875 | 4 | """
Gauss:
50 pairs of numbers that added up to 100: 1 + 99, 2 + 98, 3 + 97, and so on, until 49 + 51.
Since 50 × 100 is 5,000, when you add that middle 50, the sum of all the numbers from 0 to 100 is 5,050.
"""
while True:
total = 0
try:
num = int(input('Type in the number you want to add up to: '))
for times in range(num+1):
total = total + times
new_total = total + times
print(f'Total: {new_total} = {total} + {times}')
print(total)
except ValueError:
print('Only accepts integers!')
except TypeError:
print('Only accepts integers!')
"""Loop for picking another number"""
finally:
choice = input('Want to do for another number?:\n<Any Key> Yes | <X> Exit\n')
if choice.lower() in {'x'}:
break
else:
continue
|
a23f46def2ea89c2a9eaf5b73a02341033cadcce | safakeskin/ITU-UndergraduateCourses | /AI-BLG435E/Homeworks/hw1/Classes/PrioQueue.py | 792 | 3.796875 | 4 | from Classes import Queue
class PrioQueue(Queue.Queue):
def __init__( self, prio_queue=[], heuristic=None ):
Queue.Queue.__init__(self, prio_queue)
if heuristic is None:
self.sorter = None
else:
self.sorter = heuristic
def enqueue(self, elem):
self.queue.append(elem)
def dequeue(self):
if self.is_empty():
print("All elements are dequeued before.")
return None
if self.sorter is not None:
self.queue = self.sorter( self.queue )
fst = self.queue[0]
self.queue = self.queue[1:]
return fst
def is_empty(self):
return True if len(self.queue) == 0 else False
def get_queue(self):
return self.queue |
38139c531a162b657b27d7ca21721cbe265663b7 | Barleyfield/Language_Practice | /Python/Others/Pr181210/Code09_12(asterisk_single).py | 427 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 11 00:06:35 2018
@author: Isaac
*para
매개변수의 개수를 지정하지 않고 전달
"""
def para_func(*para) :
result = 0
for num in para :
result += num
return result
hap = 0
hap = para_func(10,20)
print("매개변수 10, 20 합 : %d" % hap)
hap = para_func(10,20,30,40,50,60)
print("매개변수 10, 20, 30, 40, 50, 60 합 : %d" % hap)
|
86f6e5557848284320743778855e04492df6e5d1 | Barleyfield/Language_Practice | /Python/Others/Pr181210/Code08_03(Parentheses).py | 323 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 10 21:23:10 2018
@author: Isaac
Parentheses
문자열 앞뒤로 괄호 붙이기
"""
ss = input("입력 : ")
print("출력 : ", end='')
if (ss.startswith('(') == False) :
print("(", end="")
print(ss, end="")
if (ss.endswith(')') == False) :
print(")", end="")
|
328d2837ac6d8df632e83f83bdbe70096a1bfa12 | Barleyfield/Language_Practice | /Python/Others/Pr180920/Code05_10.py | 238 | 3.71875 | 4 | import random
numbers = []
for num in range(0,10) :
numbers.append(random.randrange(0,10))
print("생성된 리스트 : ", numbers)
for i in range(0,10) :
if i not in numbers :
print(i,"는 리스트에 없어요.")
|
8a2ef0964755bab3aa0728c14bf8441fbd0b9971 | Barleyfield/Language_Practice | /Python/Others/Pr181121/Code09_13(lotto).py | 579 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 21 20:01:05 2018
@author: Isaac
Lotto
"""
import random
def getNumber() :
return random.randrange(1,46)
# 전역 변수 선언 부분
lotto = []
num = 0
if __name__ == "__main__" :
print("로또 추첨 시작~\n")
while(True) :
num = getNumber()
if (lotto.count(num) == 0) :
lotto.append(num)
if (len(lotto)>6) :
break
print("추첨된 로또 번호 : ", end="")
lotto.sort()
for i in range(0,6) :
print("%d " % lotto[i], end="")
|
31d0bfabe282edfeb9837de43863c3930877e298 | Barleyfield/Language_Practice | /Python/Others/Pr181021/Code07_05.py | 780 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 21 01:35:07 2018
@author: Isaac
"""
myList = [30,10,20]
print("현재 리스트 : %s" % myList)
myList.append(40)
print("append(40) 후의 리스트 : %s" % myList)
print("pop()으로 추출한 값 : %s " % myList.pop())
print("pop() 후의 리스트 : %s" % myList)
myList.sort()
print("sort() 후의 리스트 : %s" % myList)
myList.reverse()
print("reverse() 후의 리스트 : %s" % myList)
print("20값의 위치 : %d" % myList.index(20))
myList.insert(2,222)
print("insert(2,222) 후의 리스트 : %s" % myList)
myList.remove(222)
print("remove(222) 후의 리스트 : %s" % myList)
myList.extend([77,88,77])
print("extend[77,88,77]) 후의 리스트 : %s" % myList)
print("77값의 개수 : %d" % myList.count(77)) |
37c1747fe02916114e8c544739b816f9de7b00a1 | Barleyfield/Language_Practice | /Python/Others/Pr181121/Code09_Lambda_map.py | 714 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 21 20:23:14 2018
@author: Isaac
Lambda와 map을 알아보자
"""
myList = [1,2,3,4,5]
add10 = lambda num : num + 10
myList = list(map(add10, myList))
print(map(add10,myList)) # map 함수를 직접적으로 출력하면 덧셈은 수행되지만 그 결과가 저장된 장소를 출력.
# 예 : <map object at 0x000002ABCB2D93C8>
print(list(map(add10,myList)))
print(myList)
# 더 간결하게!
myList2 = [6,7,8,9,10]
myList2 = list(map(lambda num : num+10, myList2))
print(myList2)
# 두 리스트 더하기
list1 = [1,2,3,4]
list2 = [10,20,30,40]
hapList = list(map(lambda n1,n2 : n1+n2, list1, list2))
print(hapList) |
b57a35c5d3b1a40c9b79cbbec7c7fa8045e76dc6 | Barleyfield/Language_Practice | /Python/Others/etc/a2.py | 95 | 3.578125 | 4 | a=int(input("첫 번째 값? "))
b=int(input("두 번째 값? "))
c = int(a) + int(b)
print(c)
|
fe14c4912950ed8ca6bbb77eabc57ce776a1a095 | Barleyfield/Language_Practice | /Python/Others/Pr181121/HW09_Substring.py | 1,089 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
142694 윤이삭 Substring 함수 만들기
<실행예>
Enter the first string: asdf
Enter the second string: vfrtgasdfnhy
asdf is a substring of vfrtgasdfnhy
Enter the first string: 깊은바다
Enter the second string: 파란하늘은 깊은바다와 같다
깊은바다 is a substring of 파란하늘은 깊은바다와 같다
"""
def Substring(subst,st) :
if(st.find(subst) == -1) :
print("%s에 해당하는 문자열이 없습니다." % subst)
else :
start_loc = st.find(subst) # Start Location. 부분문자열의 시작 위치
print("%s is a substring of %s" % (subst,st)) # 0번째부터 계산하기 때문에 몇 번째인가를 반환하려면 1 더해주기
print("부분문자열의 위치는 %d번째부터 %d번째까지입니다." % ( (start_loc+1), (start_loc+1+len(subst)) ))
if __name__ == "__main__" :
substring = input("Enter the first string : ")
string = input("Enter the second string : ")
Substring(substring,string)
|
35659b0510b851aecb0bdfa04419244b7711ca03 | Barleyfield/Language_Practice | /Python/Others/Pr181211/Count_to_1_Recursive.py | 290 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 11 01:06:21 2018
@author: Isaac
Count to 1 - Recursive
1까지 세는 재귀함수
"""
def count(num) :
if (num >= 1) :
print(num, end=' ')
count(num - 1)
else :
print()
return
count(10)
count(20)
|
797022e9f7bb3655f643fbbd9cbb8266100c1fe8 | KaranPhadnisNaik/leetcode | /0009.PalindromeNumber.py | 870 | 3.625 | 4 | class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
# no palindrome if negative
# no palindrome if more than 32 bit int
if x >= 2**31-1 or x<0:
return False
# number wont have leading zeros so cant end in zero, unless the entire number is zero
if x%10 ==0 and x != 0:
return False
new=0
while new <= x:
if new == x: # works for even lenth of number
return True
new = new*10 + x%10
x /= 10
# if the newly formed number is larger than 32 bit int you fail
if new >= 2**31-1:
return False
# since newly formed number is greater than x,
# floor division by 10 would give it same # of digits as x
return (new/10 == x)
|
58c9c0e25a17fbbcfa00813c4824e33373daf78b | KaranPhadnisNaik/leetcode | /0101.SymetricTree.py | 849 | 3.984375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
#empty root is symetric
if not root:
return True
return self.findSymetry(root.left, root.right)
def findSymetry(self, left,right):
# check if left OR right are missing return none but if both are there and both are none
# return true,
if left == None or right == None:
return left == right
if (left.val == right.val):
return self.findSymetry(left.left, right.right) & self.findSymetry(left.right,right.left)
else:
return False
|
a70af6521851155c91bf0bddf720cc3fad1d1814 | jongman/theyearlyprophet | /code/sieve.py | 189 | 3.890625 | 4 | #!/usr/bin/python
def sieve(n=2):
yield n
for next in sieve(n+1):
if next % n > 0:
yield next
for _, prime in zip(range(100), sieve()):
print prime,
print
|
1b2fac0ed9821ebbea90e8f3492fec2cf057a9c8 | jgibbons94/cse251-course | /week14/assignment/assignment.py | 15,164 | 3.8125 | 4 | """
Course: CSE 251
Lesson Week: 14
File: assignment.py
Author: Jesse Gibbons
Purpose: Assignment 13 - Family Search
Instructions:
Depth First Search
https://www.youtube.com/watch?v=9RHO6jU--GU
Breadth First Search
https://www.youtube.com/watch?v=86g8jAQug04
Describe how to sped up part 1
Organize families with list comprehensions and fetch them all concurrently.
Prioritize fetching parents before children so we can
recurse to fetch the parent families concurrently with
requests to fetch the children.
Before change:
total_time : 102.31911579999996
People and families / second : 3.8702445472070837
After changes:
total_time : 4.1270161000011285
People and families / second : 88.44162250782114
Describe how to sped up part 2
Since part 2 does nothing, it cannot be faster.
It also doesn't work as expected, so I can only make it slower.
Breadth-first search is done one level at a time. It can be
accomplished as follows:
If the given list is not empty:
get every element in the list, and put all the results in a new list.
recurse with the new list.
10% Bonus to speed up part 2
Use a 5-semaphore to control the number of simultaneous requests.
Within semaphore block, call code to request.
Outside semaphore block, do all other processing.
"""
import time
import threading
import multiprocessing as mp
from multiprocessing.pool import ThreadPool
import json
import random
import requests
# Include cse 251 common Python files - Dont change
import os, sys
sys.path.append('../../code')
from cse251 import *
TOP_API_URL = 'http://127.0.0.1:8123'
# ----------------------------------------------------------------------------
class Person:
def __init__(self, data):
super().__init__()
self.id = data['id']
self.name = data['name']
self.parents = data['parent_id']
self.family = data['family_id']
self.birth = data['birth']
def __str__(self):
output = f'id : {self.id}\n'
output += f'name : {self.name}\n'
output += f'birth : {self.birth}\n'
output += f'parent id : {self.parents}\n'
output += f'family id : {self.family}\n'
return output
# ----------------------------------------------------------------------------
class Family:
def __init__(self, id, data):
super().__init__()
self.id = data['id']
self.husband = data['husband_id']
self.wife = data['wife_id']
self.children = data['children']
def children_count(self):
return len(self.children)
def __str__(self):
output = f'id : {self.id}\n'
output += f'husband : {self.husband}\n'
output += f'wife : {self.wife}\n'
for id in self.children:
output += f' Child : {id}\n'
return output
# -----------------------------------------------------------------------------
class Tree:
def __init__(self, start_family_id):
super().__init__()
self.people = {}
self.families = {}
self.start_family_id = start_family_id
def add_person(self, person):
if self.does_person_exist(person.id):
print(f'ERROR: Person with ID = {person.id} Already exists in the tree')
else:
self.people[person.id] = person
def add_family(self, family):
if self.does_family_exist(family.id):
print(f'ERROR: Family with ID = {family.id} Already exists in the tree')
else:
self.families[family.id] = family
def get_person(self, id):
if id in self.people:
return self.people[id]
else:
return None
def get_family(self, id):
if id in self.families:
return self.families[id]
else:
return None
def get_person_count(self):
return len(self.people)
def get_family_count(self):
return len(self.families)
def does_person_exist(self, id):
return id in self.people
def does_family_exist(self, id):
return id in self.families
def display(self, log):
log.write('Tree Display')
for family_id in self.families:
fam = self.families[family_id]
log.write(f'Family id: {family_id}')
# Husband
husband = self.get_person(fam.husband)
if husband == None:
log.write(f' Husband: None')
else:
log.write(f' Husband: {husband.name}, {husband.birth}')
# wife
wife = self.get_person(fam.wife)
if wife == None:
log.write(f' Wife: None')
else:
log.write(f' Wife: {wife.name}, {wife.birth}')
# Parents of Husband
if husband == None:
log.write(f' Husband Parents: None')
else:
parent_fam_id = husband.parents
if parent_fam_id in self.families:
parent_fam = self.get_family(parent_fam_id)
father = self.get_person(parent_fam.husband)
mother = self.get_person(parent_fam.wife)
log.write(f' Husband Parents: {father.name} and {mother.name}')
else:
log.write(f' Husband Parents: None')
# Parents of Wife
if wife == None:
log.write(f' Wife Parents: None')
else:
parent_fam_id = wife.parents
if parent_fam_id in self.families:
parent_fam = self.get_family(parent_fam_id)
father = self.get_person(parent_fam.husband)
mother = self.get_person(parent_fam.wife)
log.write(f' Wife Parents: {father.name} and {mother.name}')
else:
log.write(f' Wife Parents: None')
# children
output = []
for index, child_id in enumerate(fam.children):
person = self.people[child_id]
output.append(f'{person.name}')
out_str = str(output).replace("'", '', 100)
log.write(f' Children: {out_str[1:-1]}')
def _test_number_connected_to_start(self):
# start with first family, how many connected to that family
inds_seen = set()
def _recurive(family_id):
nonlocal inds_seen
if family_id in self.families:
# count people in this family
fam = self.families[family_id]
husband = self.get_person(fam.husband)
if husband != None:
if husband.id not in inds_seen:
inds_seen.add(husband.id)
_recurive(husband.parents)
wife = self.get_person(fam.wife)
if wife != None:
if wife.id not in inds_seen:
inds_seen.add(wife.id)
_recurive(wife.parents)
for child_id in fam.children:
if child_id not in inds_seen:
inds_seen.add(child_id)
_recurive(self.start_family_id)
return len(inds_seen)
def _count_generations(self, family_id):
max_gen = -1
def _recurive_gen(id, gen):
nonlocal max_gen
if id in self.families:
if max_gen < gen:
max_gen = gen
fam = self.families[id]
husband = self.get_person(fam.husband)
if husband != None:
_recurive_gen(husband.parents, gen + 1)
wife = self.get_person(fam.wife)
if wife != None:
_recurive_gen(wife.parents, gen + 1)
_recurive_gen(family_id, 0)
return max_gen + 1
def __str__(self):
out = '\nTree Stats:\n'
out += f'Number of people : {len(self.people)}\n'
out += f'Number of families : {len(self.families)}\n'
out += f'Max generations : {self._count_generations(self.start_family_id)}\n'
out += f'People connected to starting family : {self._test_number_connected_to_start()}\n'
return out
# ----------------------------------------------------------------------------
# Do not change
class Request_thread(threading.Thread):
def __init__(self, url):
# Call the Thread class's init function
threading.Thread.__init__(self)
self.url = url
self.response = {}
def run(self):
response = requests.get(self.url)
# Check the status code to see if the request succeeded.
if response.status_code == 200:
self.response = response.json()
else:
print('RESPONSE = ', response.status_code)
# -----------------------------------------------------------------------------
# Change this function to speed it up
def depth_fs_pedigree(family_id, tree):
if family_id == None:
return
print(f'Retrieving Family: {family_id}')
req_family = Request_thread(f'{TOP_API_URL}/family/{family_id}')
req_family.start()
req_family.join()
new_family = Family(family_id, req_family.response)
tree.add_family(new_family)
# Get husband details
husband_id, wife_id, children_ids = new_family.husband, new_family.wife, [c for c in new_family.children if not tree.does_person_exist(c)]
print(f' Retrieving Husband : {husband_id}')
print(f' Retrieving Wife : {wife_id}')
print(f' Retrieving children: {str(children_ids)[1:-1]}')
req_parents = [Request_thread(f'{TOP_API_URL}/person/{id}') for id in [husband_id, wife_id]]
[t.start() for t in req_parents]
[t.join() for t in req_parents]
parents = [Person(r.response) for r in req_parents]
family_threads = [threading.Thread(target=depth_fs_pedigree, args=(p.parents, tree)) for p in parents if p is not None]
req_children = [Request_thread(f'{TOP_API_URL}/person/{id}') for id in children_ids]
[t.start() for t in req_children]
[tree.add_person(person) for person in parents]
[thread.start() for thread in family_threads]
[t.join() for t in req_children]
for person in req_children:
if person is not None:
tree.add_person(Person(person.response))
[thread.join() for thread in family_threads]
# -----------------------------------------------------------------------------
# You should not change this function
def part1(log, start_id, generations):
tree = Tree(start_id)
req = Request_thread(f'{TOP_API_URL}/start/{generations}')
req.start()
req.join()
log.start_timer('Depth-First')
depth_fs_pedigree(start_id, tree)
total_time = log.stop_timer()
req = Request_thread(f'{TOP_API_URL}/end')
req.start()
req.join()
tree.display(log)
log.write(tree)
log.write(f'total_time : {total_time}')
log.write(f'People and families / second : {(tree.get_person_count() + tree.get_family_count()) / total_time}')
log.write('')
# -----------------------------------------------------------------------------
def breadth_fs_pedigree(start_id, tree):
# - implement breadth first retrieval
# - Limit number of concurrent connections to the FS server to 5
# This video might help understand BFS
# https://www.youtube.com/watch?v=86g8jAQug04
req_sem = threading.Semaphore(5)
#tree_lock = threading.Lock()
#Used internally.
def get_family(family_id):
"""
Fetches the family from id.
Add family to tree.
Put parents in current_parent_id_list
put children in current_child_id_list
"""
req_family = Request_thread(f'{TOP_API_URL}/family/{family_id}')
with req_sem:
#We are in a helper thread, so fetch without making a new thread.
req_family.run()
new_family = Family(family_id, req_family.response)
#with tree_lock:
tree.add_family(new_family)
parents_ids = [new_family.husband, new_family.wife]
current_parent_id_list.extend(parents_ids)
children_ids = [c for c in new_family.children if not tree.does_person_exist(c)]
current_child_id_list.extend(children_ids)
def get_parent(id):
"""
Fetch the person of the given id.
Append the result's parents' family id to next_family_id_list
Return the result person
"""
req_person = Request_thread(f'{TOP_API_URL}/person/{id}')
with req_sem:
req_person.run()
new_person = Person(req_person.response)
if new_person != None:
#with tree_lock:
tree.add_person(new_person)
return new_person.parents
def get_child(id):
"""
Fetch the person of the given id.
Return the result person.
"""
get_parent(id)
current_family_id_list = [start_id]
next_family_id_list = []
while len(current_family_id_list) != 0:
current_parent_id_list = []
current_child_id_list = []
with ThreadPool(10) as pool:
# get family and collect parents, children
pool.map(get_family, current_family_id_list)
print("got all the family pool")
print(f"parents: {current_parent_id_list}")
print(f"children: {current_child_id_list}")
# get parents and collect people, next generation family ids
next_family_id_list = pool.map(get_parent, current_parent_id_list)
print(f"next family id list: {next_family_id_list}")
# get children and collect people
pool.map(get_child, current_child_id_list)
current_family_id_list = [id for id in next_family_id_list if id is not None]
next_family_id_list = []
# -----------------------------------------------------------------------------
# You should not change this function
def part2(log, start_id, generations):
tree = Tree(start_id)
req = Request_thread(f'{TOP_API_URL}/start/{generations}')
req.start()
req.join()
log.start_timer('Breadth-First')
breadth_fs_pedigree(start_id, tree)
total_time = log.stop_timer()
req = Request_thread(f'{TOP_API_URL}/end')
req.start()
req.join()
tree.display(log)
log.write(tree)
log.write(f'total_time : {total_time}')
log.write(f'People / second : {tree.get_person_count() / total_time}')
log.write('')
# -----------------------------------------------------------------------------
def main():
log = Log(show_terminal=True, filename_log='assignment.log')
# starting family
req = Request_thread(TOP_API_URL)
req.start()
req.join()
print(f'Starting Family id: {req.response["start_family_id"]}')
start_id = req.response['start_family_id']
part1(log, start_id, 6)
part2(log, start_id, 6)
if __name__ == '__main__':
main()
|
330e62b9b6ff037ff06d0e9a1dc6aa3a930095f0 | Alfred-Mountfield/CodingChallenges | /scripts/buy_and_sell_stocks.py | 881 | 4.15625 | 4 | """
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design
an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
"""
def max_profit(nums: list):
if not nums:
return 0
profit = price = 0
for num in reversed(nums):
price = max(num, price)
profit = max(profit, price - num)
return profit
if __name__ == "__main__":
print(f"[7, 1, 5, 3, 6, 4]: {max_profit([7, 1, 5, 3, 6, 4])}")
print(f"[7, 6, 4, 3, 1]: {max_profit([7, 6, 4, 3, 1])}")
print(f"[7, 1, 5, 3, 6, 4]: {max_profit([7, 1, 5, 3, 6, 4])}")
print(f"[7, 5, 3, 2, 1]: {max_profit([7, 5, 3, 2, 1])}")
print(f"[7, 4, 10, 2, 6, 11]: {max_profit([7, 4, 10, 2, 6, 11])}")
|
076395d0095a59681c423b8cdde74a077c237c73 | lkloh/unittest_mocking_example | /decorators/decorator_and_function_have_args.py | 303 | 3.578125 | 4 |
def decorator(lower, upper):
def outer_wrapper(func):
def inner_wrapper(func_arg):
print('before')
val = func(func_arg)
assert lower <= val
assert val <= upper
print('after')
return inner_wrapper
return outer_wrapper
@decorator(1, 100)
def func(arg):
return arg * 7
func(8)
|
fe226864772bca16c89cd1cbc61c5ac8de8ace0d | sansrit/Python_DataScience-AI | /Python_for_dataScience&AI/5.Numpy_2d.py | 1,055 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 8 19:31:58 2020
@author: Sansrit
"""
import numpy as np
import matplotlib.pyplot as plt
a = [[11, 12, 13], [21, 22, 23], [31, 32, 33]]
#converting the list into numpy array
A = np.array(a)
print(A)
print(A.ndim) #shows dimension
print(A.shape) #shows the 3x3 dimensions
print(A.size) #shows the total no of elemens
print(A[1,1]) #accessing matrix
# Access the element on the first row and first and second columns
print(A[0][0:2])
# Access the element on the first and second rows and third column
print(A[0:2, 2])
X = np.array([[1, 0], [0, 1]])
Y = np.array([[2, 1], [1, 2]])
Z = X + Y
print(Z)
# Create a matrix A
A = np.array([[0, 1, 1], [1, 0, 1]])
# Create a matrix B
B = np.array([[1, 1], [1, 1], [-1, 1]])
#MATRIX MULTIPLICATIONS
Z = np.dot(A,B)
print(Z)
# Calculate the sine of Z
print(np.sin(Z))
# Create a matrix C
C = np.array([[1,1],[2,2],[3,3]])
# Get the transposed of C
print(C.T)
print(C.ndim)
|
30c27943793dba87e387e4b28b80ec84bd39c436 | jshk1205/pythonPractice | /3058.py | 252 | 3.5625 | 4 | for _ in range(0, int(input())):
num_list = list(map(int, input().split()))
even_list = []
for i in range(0, len(num_list)):
if num_list[i] % 2 ==0:
even_list.append(num_list[i])
print(sum(even_list), min(even_list)) |
31e62b29dfd8817625758e5dc23696a681c7be11 | jshk1205/pythonPractice | /2751.py | 124 | 3.65625 | 4 | n = int(input())
num=[]
for i in range(0, n):
lis = int(input())
num.append(lis)
for j in sorted(num):
print(j) |
b740b3d5aa623c3f4ef7bea2d8fbc31f81f70661 | jshk1205/pythonPractice | /4458.py | 248 | 3.9375 | 4 | for _ in range(0, int(input())):
text = list(str(input()))
first = text.pop(0)
if first.isupper() == False:
first=first.upper()
print(first ,end='')
for i in range(0, len(text)):
print(text[i],end='')
print() |
f19c4d80aba45cc4d3f4234b775a793bb7dd31b2 | jshk1205/pythonPractice | /5063.py | 255 | 3.625 | 4 | n = int(input())
for i in range(0, n):
r, e, c = list(map(int, input().split()))
price = e - c
if r < price:
print('advertise')
elif r == price:
print('does not matter')
elif r > price:
print('do not advertise') |
677ede23da8af655dab170eb2a9e436ba8cf39c8 | jshk1205/pythonPractice | /2747.py | 122 | 3.828125 | 4 | n = int(input())
num1, num2 = 0, 1
for i in range(0,n):
next = num1 + num2
num1 = num2
num2 = next
print(num1) |
d894aee10b45799712ec60aaaa27b765eb87cf52 | jshk1205/pythonPractice | /2693.py | 131 | 3.609375 | 4 | t = int(input())
for _ in range(0, t):
numA_list = list(map(int,input().split()))
numA_list.sort()
print(numA_list[-3]) |
330485bc5d73e332debe14d8eef82040810f48b3 | beckitrue/python-kali | /cameras.py | 3,549 | 3.75 | 4 | # We want to map the camera MAC to IP using data collected from Wireshark
# Wireshark filter is: ip.dst == 255.255.255.255 and udp.port == 8848
# Port 8848 UDP is used by MESSOA IP cameras as a heartbeat. Every few
# seconds they send a small comma separated string:
# $MessoaIPCamera,ipaddress,subnetmask,macaddress,port
# Input
# takes output from Wireshark file saved as plain text and parses it
# for IP to MAC mapping
# file was Export Packet Dissections as Plain Text
# Output
# CSV: MAC, IP
# --------------------
import re
import os
import sys
import csv
def create_list(line_num, data_line):
"gets data information to write record to a file"
# INPUT
# data line number i.e. 0010, 0020, 0030, 0040
# information to append to record
# we're using a dictionary data structure to avoid duplicate records
# and we'll use the MAC as the key in the key:value pair
global record
global macpat
global ippat
global cameras
if line_num == "0010":
# this is a new data record of a camera
# start new string record of the camera details
record = data_line
else:
# append to the string
record = record + data_line
if line_num == "0030":
# This is the last data line with information we need -
# find the MAC so we can see if this is a duplicate device -
# if not, add it to our list of devices and map its IP to it
# look for mac address in record
mac = macpat.search(record)
if mac:
mac_add = mac.group(0)
# find the IP address in the record
ip = ippat.search(record)
ip_add = ip.group(0)
# see if the MAC address is already in our list of devices
# add it if not
if mac_add not in cameras:
cameras[mac_add] = ip_add
return
# open pcap text file and parrse it to get the data we need
# look for the lines with the data
# data lines start with 4 digits followed by a space and then up to 16 hex pairs
# there are never more tha 5 lines of data in these messages:
# 0000, 0010, 0020, 0030, 0040
# line 0000 always has the string "$MessoaIPCamera," so might as well skip it
# line 0040 always has the TCP/UDP port, so might as well skip that too
p = re.compile(r'(00[1-3]0)\s+')
# pattern for MAC
macpat = re.compile(r'([0-9a-fA-F]{2}:?){6}')
# pattern for IPv4
ippat = re.compile(r'([0-9]{1,3}\.?){4}')
# initialize record string to an empty string
record = ""
# initialize cameras dictionary to an empty dictionary
cameras = dict()
# open the file to read with the pcap in plain text
with open(input("Enter file to read: "),'r') as f:
line = f.readline()
while line:
# look for data lines
m = p.match(line)
# parse data lines to get the information we want
if m:
# remove trailing \n from all data lines
data_line = re.sub(r'\n',"",line)
# remove hex data
data_line = re.sub(r'(00[1-4]0)\s+((\w){2}(\s?))+',"",data_line)
# remove all spaces in the line
data_line = data_line.replace(" ", "")
# sent line number and parsed data to add to list
create_list(m.group(1), data_line)
line = f.readline()
# write device list to a CSV file
with open(input("Enter filename to write: "),'w') as csvfile:
devices = csv.writer(csvfile)
# add header row
devices.writerow(["MAC", "IP"])
for key, val in cameras.items():
devices.writerow([key, val])
|
a82299e881d28c5b3672509104f7e1398288876c | KatsuhiroMorishita/machine_leaning_samples | /keras_Image_classification/fine_tuning/image_preprocessing.py | 25,692 | 3.5 | 4 | # purpose: 画像の前処理用モジュール
# main()では、画像の読み込みと保存を行います。
# author: Katsuhiro MORISHITA 森下功啓
# created: 2018-08-20
# lisence: MIT. If you use this program in your study, you should write shaji in your paper.
from matplotlib import pylab as plt
from PIL import Image
from skimage.transform import rotate # scipyのrotateは推奨されていない@2018-08ので、skimageを使う。こっちの方が使い勝手が良い
from skimage.transform import resize
import numpy as np
import pickle
import pandas as pd
import sys
import os
def read_name_dict(fname, skiprows=[], key_valule=[0, 1], delimiter=","):
""" ファイル名とクラスIDなどが入ったファイルから、特定の列を辞書に加工して返す
fname: str, ファイル名
skiprows: list<int>, 読み飛ばす行番号を格納したリスト
key_valule: list<int>, keyとvalueのそれぞれの列番号を格納したリスト
"""
df = pd.read_csv(fname, delimiter, header=None, skiprows=skiprows)
name_dict = {}
for i in range(len(df)):
name_dict[df.iloc[i, key_valule[0]]] = df.iloc[i, key_valule[1]]
return name_dict
def read_image(param):
""" 指定されたフォルダ内の画像をリストとして返す
読み込みはディレクトリ単位で行う。
param: dict, 計算に必要なパラメータを収めた辞書
"""
dir_name = param["dir_name"] # dir_name: str, フォルダ名、又はフォルダへのパス
data_format = param["data_format"] # data_format: str, データ構造を指定
size = param["size"] # size: tuple<int, int>, 読み込んだ画像のリサイズ後のサイズ。 width, heightの順。
mode = param["mode"] # mode: str, 読み込んだ後の画像の変換モード
resize_filter = param["resize_filter"] # resize_filter: int, Image.NEARESTなど、リサイズに使うフィルターの種類。処理速度が早いやつは粗い
image_list = [] # 読み込んだ画像データを格納するlist
name_list = [] # 読み込んだファイルのファイル名
files = os.listdir(dir_name) # ディレクトリ内部のファイル一覧を取得
print("--dir--: ", dir_name)
print("--files (head 20)--", files[:20])
for file in files:
root, ext = os.path.splitext(file) # 拡張子を取得
if ext != ".jpg" and ext != ".bmp" and ext != ".png":
continue
fname = os.path.basename(file)
if fname[0] == ".": # Macが自動的に生成するファイルを除外
continue
path = os.path.join(dir_name, file) # ディレクトリ名とファイル名を結合して、パスを作成
image = Image.open(path) # 画像の読み込み
if "preprocess_each_image_func" in param: # 必要なら前処理
func = param["preprocess_each_image_func"]
image = func(image, param)
if image is None:
print(path, "-- preprocessing function returned None object.")
continue
image = image.resize(size, resample=resize_filter) # 画像のリサイズ
image = image.convert(mode) # 画像のモード変換。 mode=="LA":透過チャンネルも考慮して、グレースケール化, mode=="RGB":Aを無視
image = np.array(image) # ndarray型の多次元配列に変換
image = image.astype(np.float16) # 型の変換(整数型のままだと、0-1にスケーリングシた際に、0や1になるのでfloatに変換)
if image.ndim == 2: # グレースケール画像だと2次元のはずなので、チャンネルの次元を増やす
image = image[:, :, np.newaxis]
if data_format == "channels_first":
image = image.transpose(2, 0, 1) # 配列を変換し、[[Redの配列],[Greenの配列],[Blueの配列]] のような形にする。
image_list.append(image) # 出来上がった配列をimage_listに追加
name_list.append(file)
return image_list, name_list
def split(arr1, arr2, rate, names=None):
""" 引数で受け取ったlistをrateの割合でランダムに抽出・分割する(副作用に注意)
基本的には、学習データと検証データに分けることを想定している。
arr1, arr2: list<ndarray or list or int>, 画像や整数が入ったリストを期待している
rate: float, 抽出率。0.0~1.0
names: list<str>, 画像のファイル名を想定している。別に番号でもいいと思う。
"""
if len(arr1) != len(arr2):
raise ValueError("length of arr1 and arr2 is not equal.")
arr1_1, arr2_1 = list(arr1), list(arr2) # arr1, arr2を代入すると、副作用覚悟で使用メモリを少し減らす。副作用が嫌いなら、→ list(arr1), list(arr2) を代入
arr1_2, arr2_2 = [], [] # 抽出したものを格納する
names_copy = list(names)
times = int(rate * len(arr1_1))
pop_list = []
for _ in range(times):
i = np.random.randint(0, len(arr1_1)) # 乱数で抽出する要素番号を作成
arr1_2.append(arr1_1.pop(i))
arr2_2.append(arr2_1.pop(i))
if names is not None:
pop_list.append(names_copy.pop(i))
if names is None:
return np.array(arr1_1), np.array(arr2_1), np.array(arr1_2), np.array(arr2_2)
else:
return np.array(arr1_1), np.array(arr2_1), np.array(arr1_2), np.array(arr2_2), pop_list
# 関数の動作テスト
"""
a = [1,2,3,4,5,6,7,8,9,10]
b = [11,12,13,14,15,16,17,18,19,20]
print(split(a, b, 0.2))
exit()
"""
def to_categorical(array_1d):
""" 整数で表現されたカテゴリを、ニューラルネットワークの出力層のユニットに合わせてベクトルに変換する
kerasが無くても動作した方が良い気がして、自前で実装した。
array_1d: ndarray or list, 1次元配列で整数が格納されていることを期待している
"""
_max = np.max(array_1d)
ans = []
for val in array_1d:
vector = [0] * (_max + 1)
vector[val] = 1. # mixupを考えると、浮動小数点が良い
ans.append(vector)
return np.array(ans)
def one_hotencoding(data=[]):
""" one-hotencodingを行う
(2018-08-12: クラスの数の割にクラス毎のサンプル数が少ないことが原因でdata内の各要素におけるクラスIDの欠落が生じないように、ロジックを書き換えた)
data: list<ndarray>, 1次元のndarrayを格納したリスト
"""
fusion = [] # 一旦、全部結合させる
for mem in data:
fusion += list(mem)
fusion_onehot = to_categorical(fusion) # 全部を一緒にしてからone-hotencoding
ans = [] # fusion_onehotを個々に切り出す
s = 0
for length in [len(mem) for mem in data]:
ans.append(fusion_onehot[s:s + length])
s += length
return ans
def read_images1(param):
""" 辞書で指定されたフォルダ内にある画像を読み込んで、リストとして返す
クラス毎にフォルダ名又はフォルダへのパスを格納した辞書が、param内に"dir_names_dict"をキーとして保存されていることを期待している。
フォルダ名がそのままクラス名でも、この関数で処理すること。
param: dict, 計算に必要なパラメータを収めた辞書
"""
dir_names_dict = param["dir_names_dict"] # dict<str:list<str>>, クラス毎にフォルダ名又はフォルダへのパスを格納した辞書。例:{"A":["dir_A1", "dir_A2"], "B":["dir_B"]}
x, y = [], [] # 読み込んだ画像データと正解ラベル(整数)を格納するリスト
file_names = [] # 読み込んだ画像のファイル名のリスト
size_dict = {} # データの数をクラス毎に格納する辞書
class_name_list = sorted(dir_names_dict.keys()) # この時点ではstr。ソートすることで、local_id(プログラム中で割り振るクラス番号)とクラス名がずれない
label_dict = {i:class_name_list[i] for i in range(len(class_name_list))} # local_idからクラス名を引くための辞書。ここでのlocal_idはこの学習内で通用するローカルなID。(予測段階で役に立つ)
label_dict_inv = {class_name_list[i]:i for i in range(len(class_name_list))} # 逆に、クラス名から番号を引く辞書
output_dim = len(label_dict) # 出力層に必要なユニット数(出力の次元数)
label_dict[len(label_dict)] = "ND" # 分類不能に備えて、NDを追加
for class_name in class_name_list: # 貰った辞書内のクラス数だけループを回す
for dir_name in dir_names_dict[class_name]: # クラス毎に、フォルダ名が格納されたリストから1つずつフォルダ名を取り出してループ
param["dir_name"] = dir_name # 読み込み先のディレクトリを指定
imgs, _file_names = read_image(param) # 画像の読み込み
if len(imgs) == 0:
continue
local_id = label_dict_inv[class_name] # local_idはint型
label_local = [local_id] * len(imgs) # フォルダ内の画像は全て同じクラスに属するものとして処理
x += imgs
y += label_local
file_names += _file_names
if local_id in size_dict: # クラス毎にその数をカウント
size_dict[local_id] += len(imgs)
else:
size_dict[local_id] = len(imgs)
# クラスごとの重みの計算と、重みの辞書の作成(教師データ数の偏りを是正する)
size_keys = sorted(size_dict.keys())
size_list = [size_dict[k] for k in size_keys]
print("size_dict: ", size_dict)
print("size list: ", size_list)
weights = np.array(size_list)
weights = np.max(weights) / weights
weights_dict = {i:weights[i] for i in size_keys}
return x, y, weights_dict, label_dict, output_dim, file_names
def read_images2(param):
""" リストで指定されたフォルダ内にある画像を読み込んで、リストとして返す
ファイル名とクラス名(整数か文字列)を紐づけた辞書が、param内に"name_dict"をキーとして保存されていることを期待している。
param: dict, 計算に必要なパラメータを収めた辞書
"""
dir_names_list = param["dir_names_list"] # list<str>, フォルダ名又はフォルダへのパスを格納したリスト
name_dict = param["name_dict"] # dict<key: str, value: int or str>, ファイル名をクラスIDに変換する辞書
x, y = [], [] # 読み込んだ画像データと正解ラベル(整数)を格納するリスト
file_names = []
size_dict = {} # データの数をクラス毎に格納する辞書
class_name_list = sorted(list(set(name_dict.values()))) # この時点ではintかstrのどちらか。ソートすることで、local_id(プログラム中で割り振るクラス番号)とクラス名がずれない
label_dict = {i:class_name_list[i] for i in range(len(class_name_list))} # local_idからクラス名を引くための辞書。ここでのlocal_idはこの学習内で通用するローカルなID。(予測段階で役に立つ)
label_dict_inv = {class_name_list[i]:i for i in range(len(class_name_list))} # 逆に、クラス名から番号を引く辞書
output_dim = len(label_dict) # 出力層に必要なユニット数(出力の次元数)
label_dict[len(label_dict)] = "ND" # 分類不能に備えて、NDを追加
for dir_name in dir_names_list: # 貰ったフォルダ名の数だけループを回す
param["dir_name"] = dir_name # 読み込み先のディレクトリを指定
imgs, _file_names = read_image(param) # 画像の読み込み
if len(imgs) == 0:
continue
label_raw = [name_dict[name] for name in _file_names] # ファイル名からラベルのリスト(クラス名のlist)を作る
label_local = [label_dict_inv[raw_id] for raw_id in label_raw] # 学習に使うlocal_idに置換
print("--label--", label_local[:20])
x += imgs
y += label_local
file_names += _file_names
for local_id in label_local: # クラス毎にその数をカウント
if local_id in size_dict:
size_dict[local_id] += 1
else:
size_dict[local_id] = 1
# クラスごとの重みの計算と、重みの辞書の作成(教師データ数の偏りを是正する)
size_keys = sorted(size_dict.keys())
size_list = [size_dict[k] for k in size_keys]
print("size_dict: ", size_dict)
print("size list: ", size_list)
weights = np.array(size_list)
weights = np.max(weights) / weights
weights_dict = {i:weights[i] for i in size_keys}
return x, y, weights_dict, label_dict, output_dim, file_names
def preprocessing1(imgs):
""" 画像の前処理
必要なら呼び出して下さい。
(処理時間が長い・・・)
imgs: ndarray or list<ndarray>, 画像が複数入っている多次元配列
"""
image_list = []
for img in imgs:
_img = img.astype(np.float32) # float16のままではnp.mean()がオーバーフローする
img2 = (_img - np.mean(_img)) / np.std(_img) / 4 + 0.5 # 平均0.5, 標準偏差を0.25にする
img2[img2 > 0.98] = 0.98 # 0-1からはみ出た部分が存在するとImageDataGeneratorに怒られるので、調整
img2[img2 < 0.0] = 0.0
img2 = img2.astype(np.float16)
image_list.append(img2)
return np.array(image_list)
def preprocessing2(imgs):
""" 画像の前処理
必要なら呼び出して下さい。
imgs: ndarray, 画像が複数入っている多次元配列
"""
return imgs / 256 # 255で割ると、numpyの関数処理後に1.0を超える事があり、エラーが出る・・・
## ImageDataGenerator start ################################################
def random_crop(image, width_ratio=1.0):
""" 一部を切り出す
ref: https://www.kumilog.net/entry/numpy-data-augmentation
"""
h, w, _ = image.shape # 元のサイズに戻すために、サイズを覚えておく
r = 0.7 * np.random.random() + 0.3
h_crop = int(h * r) # 切り取るサイズ
w_crop = int(w * r * width_ratio)
# 画像のtop, leftを決める
top = np.random.randint(0, h - h_crop)
left = np.random.randint(0, w - w_crop)
# top, leftにcropサイズを足して、bottomとrightを決める
bottom = top + h_crop
right = left + w_crop
# 決めたtop, bottom, left, rightを使って画像を抜き出す
img = image[top:bottom, left:right, :]
img = resize(img, (h, w))
return img
def random_erasing(image, s=(0.02, 0.4), r=(0.3, 3)):
""" ランダムに一部にマスクをかける
ref: https://www.kumilog.net/entry/numpy-data-augmentation
"""
# マスクする画素値をランダムで決める
mask_value = np.random.randint(0, 256)
h, w, _ = image.shape
# マスクのサイズを元画像のs(0.02~0.4)倍の範囲からランダムに決める
mask_area = np.random.randint(h * w * s[0], h * w * s[1])
# マスクのアスペクト比をr(0.3~3)の範囲からランダムに決める
mask_aspect_ratio = np.random.rand() * r[1] + r[0]
# マスクのサイズとアスペクト比からマスクの高さと幅を決める
# 算出した高さと幅(のどちらか)が元画像より大きくなることがあるので修正する
mask_height = int(np.sqrt(mask_area / mask_aspect_ratio))
if mask_height > h - 1:
mask_height = h - 1
mask_width = int(mask_aspect_ratio * mask_height)
if mask_width > w - 1:
mask_width = w - 1
top = np.random.randint(0, h - mask_height)
left = np.random.randint(0, w - mask_width)
bottom = top + mask_height
right = left + mask_width
image[top:bottom, left:right, :].fill(mask_value)
return image
# kerasのImageDataGeneratorと同じような使い方ができる様にした
class MyImageDataGenerator:
def __init__(self, rotation_range=0, zoom_range=0, horizontal_flip=False, vertical_flip=False, width_shift_range=0.0, height_shift_range=0.0,
crop=False, random_erasing=False, mixup=0.0, return_type="ndarray", shape=(100, 100)):
"""
shape: tuple<int, int>, 最終的に出力する画像のサイズ。height, widthの順で格納すること
"""
self.rotation_range = rotation_range
self.zoom_range = zoom_range
self.horizontal_flip = horizontal_flip
self.vertical_flip = vertical_flip
self.width_shift_range = width_shift_range
self.height_shift_range = height_shift_range
self.crop = crop
self.random_erasing = random_erasing
self.mixup = mixup
self.return_type = return_type
self.shape = shape
def flow(self, x, y, save_to_dir=None, save_format=None, batch_size=10, shuffle=True):
"""
x: ndarray, 0-1.0に正規化された画像が複数入っていることを想定
y: ndarray, 0. or 1.を成分とするベクトルを格納した配列(2次元配列)。正解ラベルを想定
shape: tuple<int, int>, 最終的に出力する画像のサイズ。height, widthの順で格納すること
"""
address_map = np.arange(0, len(x)) # アクセス先のインデックスを管理する配列
if shuffle:
np.random.shuffle(address_map) # アクセス先をシャッフル
def get_img(index):
""" 指定された画像のシャローコピーを返す
高速化優先で、コピーは作らない
"""
i = address_map[index]
img = x[i]
label_vect = y[i]
return img, label_vect
i = 0
i_backup = 0
while True:
x_ = []
y_ = []
for k in range(batch_size): # バッチサイズ分、ループ
j = (i + k) % len(x)
img_origin, label_origin = get_img(j)
img1 = img_origin.astype(np.float64) # 単なるnumpyの行列計算なら32bitが速いが、64bitでの計算がより速い
flag_label = False
# 画像の加工
if self.rotation_range != 0 and np.random.rand() < 0.5: # 回転
theta = np.random.randint(-self.rotation_range, self.rotation_range)
img1 = rotate(img1, theta) # skimageのライブラリを使った場合、サイズは変わらないがfloat64になる。scipyのrotateはサイズが変わる
if self.horizontal_flip and np.random.rand() < 0.5: # 水平方向に反転
img1 = np.fliplr(img1)
if self.vertical_flip and np.random.rand() < 0.5: # 垂直方向に反転
img1 = np.flipud(img1)
if np.random.rand() < self.mixup: # 他の画像と合成
n = np.random.randint(0, len(x)) # 合成する画像のインデックス
r = np.random.rand() # 合成比
img_origin2, label_origin2 = get_img(n)
img1 = img1 * r + img_origin2 * (1 - r) # 合成
label_vect1 = label_origin * r + label_origin2 * (1 - r)
flag_label = True
if self.crop and np.random.rand() < 0.5: # 切り出し
img1 = random_crop(img1)
if self.random_erasing and np.random.rand() < 0.5: # ランダムに一部にマスクをかける
img1 = random_erasing(img1)
# ラベルに対して何の処理も行われなかった場合の対応
if flag_label == False:
label_vect1 = label_origin.copy()
# リサイズ
if x[0].shape[:2] != self.shape:
img1 = resize(img1, self.shape)
# 保存
if save_to_dir is not None and save_format is not None:
img3 = img1 * 255 # 別の変数として保存しないと、x_に影響する
img3 = img3.astype(np.uint8)
pilImg = Image.fromarray(np.uint8(img3))
pilImg.save("{0}/{1}_{2}_hoge.{3}".format(save_to_dir, i, k, save_format))
# 返り値のリストに格納
img1 = img1.astype(np.float16) # メモリ節約のため、型を小さくする
x_.append(img1)
y_.append(label_vect1)
# 処理結果を返す
if self.return_type == "ndarray":
yield np.array(x_), np.array(y_)
else:
yield x_, y_
# 次のアクセスに備えた処理
i_backup = i
i = (i + batch_size) % len(x)
if i_backup > i: # 1順を検知
if shuffle: # シャッフルが指定されていたら
np.random.shuffle(address_map) # アクセス先をシャッフル
## ImageDataGenerator end ################################################
def load_save_images(read_func, param, validation_rate=0.1):
""" 画像の読み込みと教師データの作成と保存を行う
read_func: function, 画像を読み込む関数
param: dict<str: obj>, read_funcに渡すパラメータ
validation_rate: float, 検証に使うデータの割合
"""
# 画像を読み込む
x, y, weights_dict, label_dict, output_dim, file_names = read_func(param)
x_train, y_train_o, x_test, y_test_o, test_file_names = split(x, y, validation_rate, file_names) # データを学習用と検証用に分割
if "preprocess_func" in param: # 必要なら前処理
preprocess_func = param["preprocess_func"] # func, 前処理を行う関数
x_train = preprocess_func(x_train)
x_test = preprocess_func(x_test)
y_train, y_test = one_hotencoding(data=[y_train_o, y_test_o]) # 正解ラベルをone-hotencoding。分割表を作りたいので、splitの後でone-hotencodingを行う
# 保存
np.save('x_train.npy', x_train)
np.save('y_train.npy', y_train)
np.save('y_train_o.npy', y_train_o)
np.save('x_test.npy', x_test)
np.save('y_test.npy', y_test)
np.save('y_test_o.npy', y_test_o)
with open('weights_dict.pickle', 'wb') as f: # 再利用のために、ファイルに保存しておく
pickle.dump(weights_dict, f)
with open('label_dict.pickle', 'wb') as f: # 再利用のために、ファイルに保存しておく
pickle.dump(label_dict, f)
with open('param.pickle', 'wb') as f: # 再利用のために、ファイルに保存しておく
pickle.dump(param, f)
with open('test_names.pickle', 'wb') as f: # 再利用のために、ファイルに保存しておく
pickle.dump(test_file_names, f)
return x_train, y_train_o, x_test, y_test_o, weights_dict, label_dict, y_train, y_test, output_dim, test_file_names
def main():
data_format = "channels_last"
# pattern 1, flower
dir_names_dict = {"yellow":["sample_image_flower/1_train"],
"white":["sample_image_flower/2_train"]}
param = {"dir_names_dict":dir_names_dict, "data_format":data_format, "size":(32, 32), "mode":"RGB", "resize_filter":Image.NEAREST, "preprocess_func":preprocessing2}
x_train, y_train_o, x_test, y_test_o, weights_dict, label_dict, y_train, y_test, output_dim, test_file_names = load_save_images(read_images1, param, validation_rate=0.2)
# 確認
print("test_file_names: ", test_file_names)
# pattern 1, animal
#dir_names_dict = {"cat":["sample_image_animal/cat"],
# "dog":["sample_image_animal/dog"]}
#param = {"dir_names_dict":dir_names_dict, "data_format":data_format, "size":(32, 32), "mode":"RGB", "resize_filter":Image.NEAREST, "preprocess_func":preprocessing}
#x_train, y_train_o, x_test, y_test_o, weights_dict, label_dict, y_train, y_test, output_dim =load_save_images(read_images1, param, validation_rate=0.2)
# pattern 2, animal
#dir_names_list = ["sample_image_animal/cat", "sample_image_animal/dog"]
#name_dict = read_name_dict("sample_image_animal/file_list.csv")
#param = {"dir_names_list":dir_names_list, "name_dict":name_dict, "data_format":data_format, "size":(32, 32), "mode":"RGB", "resize_filter":Image.NEAREST, "preprocess_func":preprocessing}
#x_train, y_train_o, x_test, y_test_o, weights_dict, label_dict, y_train, y_test, output_dim =load_save_images(read_images2, param, validation_rate=0.2)
if __name__ == "__main__":
main()
|
491df162a8c8cf2c69dfcee689fa4c9da7f642fb | kasthuri28/Python | /python.py | 130 | 3.984375 | 4 | n=int(input())
if(n>0) :
print("The number is +ve")
elif(n==0) :
print("The number is 0")
else :
print("The number is -ve")
|
42271e653dc0e194900989799e3279979fd20a90 | andramarkov/StockScrape | /main.py | 5,378 | 3.640625 | 4 | # getData function returns stock symbol, current price, and and current date in a list.
from scrape import getData
# scr function scrapes the database for information about purchased stocks
from scrape import scr
# Current version gets declared as a global var up here
version = 1.0
# This will act as the main file that everything flows through.
# This function gets a list of all stock symbols in the database
def getSymbolsDatabase():
dataList = scr()
symbols = []
# I'm going to try and do a flag while loop here
flag = False
initial = 0
while not flag:
lastIndex = len(dataList) - 1
symbols.append(dataList[initial])
if initial == lastIndex - 2:
flag = True
break
initial = initial + 3
return symbols
# This function gets a list of all prices in the database
def getPricesDatabase():
dataList = scr()
prices = []
# I'm going to try and do a flag while loop here
flag = False
initial = 1
while not flag:
lastIndex = len(dataList) - 1
prices.append(dataList[initial])
if initial == lastIndex - 1:
flag = True
break
initial = initial + 3
return prices
# This function gets a list of all dates in the database
def getDatesDatabase():
dataList = scr()
dates = []
# I'm going to try and do a flag while loop here
flag = False
initial = 2
while not flag:
lastIndex = len(dataList) - 1
dates.append(dataList[initial])
if initial == lastIndex:
flag = True
break
initial = initial + 3
return dates
def review():
symbols = getSymbolsDatabase()
numberOfStocks = len(symbols)
prices = getPricesDatabase()
newPrices = []
for price in prices:
newPrices.append(float(price))
totalPrice = sum(newPrices)
dates = getDatesDatabase()
print("You have purchased {} stocks, for an initial investment of ${} \n" .format(numberOfStocks, totalPrice))
initial = 0
for stock in symbols:
print("{} for ${} on {} \n".format(stock, prices[initial], dates[initial]))
initial = initial + 1
def returnReview():
prices = getPricesDatabase()
newPrices = []
for price in prices:
newPrices.append(float(price))
totalPrice = sum(newPrices)
return totalPrice
def current():
print("Checking current prices...\n")
# Make sure to enter data in quotes
stockSymbols = getSymbolsDatabase()
totalPrice = []
# Loops through all stocks, printing out their current prices
for stock in stockSymbols:
price = getData(stock)
converted = float(price[1])
totalPrice.append(converted)
print("{} is valued at ${} \n" .format(stock, price[1]))
newTotalPrice = sum(totalPrice)
print("Your portfolio is currently valued at ${}" .format(round(newTotalPrice, 2)))
# This function will return the current portfolio value
def returnCurrent():
stockSymbols = getSymbolsDatabase()
totalPrice = []
# Loops through all stocks, printing out their current prices
for stock in stockSymbols:
price = getData(stock)
converted = float(price[1])
totalPrice.append(converted)
newTotalPrice = sum(totalPrice)
return round(newTotalPrice,2)
# I can tell this is going to be the hardest function here to write. yikes
def compareTotal():
symbols = getSymbolsDatabase()
prices = getPricesDatabase()
dates = getDatesDatabase()
# This var is the current value of portfolio
totalCurrentValue = returnCurrent()
# This var is initial amount invested
totalInitialValue = returnReview()
if totalCurrentValue > totalInitialValue:
totalReturn = totalCurrentValue - totalInitialValue
percentChange = (totalReturn / totalInitialValue) * 100
print("Your portfolio has made ${}, a {}% increase " .format(totalReturn, percentChange))
if totalInitialValue > totalCurrentValue:
totalReturn = totalInitialValue - totalCurrentValue
percentChange = (totalReturn / totalInitialValue) * 100
print("Your portfolio has lost ${}, a {}% drop " .format(round(totalReturn, 2), round(percentChange,2)))
def main():
# Some formatting to make stuff look pretty.
print("-----------------------------------")
print("Welcome to StockScrape, version {}" .format(version))
print("-----------------------------------")
print("Would you like to... \n\n 1. Review portfolio \n 2. Check current prices \n 3. Compare\n")
q = input(" Type a number from above: ")
# Creates a flag for the while loop
flag = False
# While loop iterate until user types a correct response
while not flag:
if q == "1":
print("-----------------------------")
review()
flag = True
break
if q == "2":
print("--------------------------")
current()
flag = True
break
if q == "3":
print("-----------------------------")
compareTotal()
flag = True
break
# if q == "3":
# print("exiting")
# flag = True
# break
else:
q = input("You typed neither. Type a number from above: ")
main()
|
ab869dd38e2a573cbbd30bbc74732d7258c6a86b | keith-fischer/gurucv | /face1/face_detect.py | 748 | 3.71875 | 4 | # import the necessary packages
import cv2
# load our image and convert it to grayscale
image = cv2.imread("orientation_example.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# load the face detector and detect faces in the image
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
rects = detector.detectMultiScale(
gray,
scaleFactor=1.05,
minNeighbors=10,
minSize=(20, 20),
flags=cv2.CASCADE_SCALE_IMAGE)
#flags=cv2.CV_HAAR_SCALE_IMAGE) opencv 3 changed
# loop over the faces and draw a rectangle surrounding each
for (x, y, w, h) in rects:
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
s="%d Faces" % len(rects)
# show the detected faces
cv2.imshow(s, image)
cv2.waitKey(0)
|
ea76a11674e184f49ced584222a74685d2c1cda5 | mariamiah/Event-Life | /reception/reception.py | 913 | 4.0625 | 4 | # Read ordinary file and append names to a list
ordinary = open("ordinary.txt", "r")
ordinary_list = [line.rstrip() for line in ordinary.readlines()]
# Read VIP file and append names to the vip_list
vip = open("vip.txt", "r")
vip_list = [line.rstrip() for line in vip.readlines()]
# Request user to enter their name
singlename = input("Enter single name:")
def registration_checker(singlename):
''' Function that checks if the user exists either in ordinary_list
or in vip_list'''
for name in ordinary_list:
if name.split()[0] == singlename:
return [name, "ORDINARY"]
for name in vip_list:
if name.split()[0] == singlename:
return [name, "VIP"]
for name in ordinary_list and vip_list:
if singlename not in name.split()[0]:
return "User does not exist"
print(registration_checker(singlename))
ordinary.close()
vip.close()
|
2df6ff13c5c936dc180433eb12825b5b9115e5e6 | nullbit01/Cracking-Python-Bootcamp | /coding projects/game_of_conditions.py | 9,477 | 4.1875 | 4 | ###########################################################
# A Game of Conditions: Text Based Fantasy Game in Python
# --------------------------------------------------------
# This is the text based adventure game.
# It works by asking the gender of the user,
# asking them additional questions, and then modifying the
# storyline accordingly.
#
# By Doug Purcell
# http://www.purcellconsult.com
#
###########################################################
def male_adventure():
your_name = input('Enter your name: ')
queen_name = input('What\'s the name of your queen? ')
kingdom = input('What\'s the name of your kingdom? ')
your_name, queen_name, kingdom = your_name.capitalize(), queen_name.capitalize(), kingdom.capitalize()
have_allies = input('Do you have allies? Enter "y" for yes or "n" for no. ')
have_enemies = input('Do you have enemies? Enter "y" for yes or "n" for no. ')
have_allies, have_enemies = have_allies.lower(), have_enemies.lower()
if have_allies == 'y':
paladin = input('Enter your paladin\'s name ')
wizard = input('Enter your wizard\'s name ')
warrior = input('Enter your warrior\'s name ')
paladin, wizard, warrior = paladin.capitalize(), wizard.capitalize(), \
warrior.capitalize()
elif have_allies == 'n':
pass
if have_enemies == 'y':
print('{} got enemies, got a lot of enemies'.format(your_name))
villian = input('Enter your villian\'s name ')
war_name = input('What\'s the name of your war? ')
years = int(input('How many years did the war last? '))
thief = input('Enter your thief\'s name ')
evil_sorcerer = input('Enter evil sorcerer\'s name ')
rogue = input('Enter rogue\'s name ')
thief, evil_sorcerer, rogue = thief.capitalize(), evil_sorcerer.capitalize(), rogue.capitalize()
elif have_enemies == 'n':
pass
if have_allies == 'y' and have_enemies == 'y':
message = """
The great {0} and his queen {1} peacefully ruled the kingdom of
{2}. However, a great war called {3} erupted. {0}'s nemesis {4} invaded
his kingdom. With the help of {5}, {6}, and {7}, {4} pillaged their land,
stole precious resources, and brutally attacked their villagers.
King {0} and Queen {1} with the help of {8}, {9}, and {10} valiantly
fought back and defeated {4} after {11} years of fierce fighting. Order was finally
restored and everyone in their kingdom lived happily ever after :-).""".format(your_name, queen_name,
kingdom, war_name, villian,
thief, evil_sorcerer, rogue,
paladin, wizard, warrior,
years)
print(message)
elif have_allies == 'y' and have_enemies == 'n':
message = """
The great {0} and his queen {1} peacefully ruled the kingdom of
{2}. With the help of {3}, {4}, and {5}, {0} and {1} were able to keep their
kingdom safe forever. The entire kingdom of {2} lived happily ever after :-).True Story.THE END.""".format(
your_name, queen_name,
kingdom, paladin, wizard, warrior, kingdom)
print(message)
elif have_allies == 'n' and have_enemies == 'y':
message = """
The great {0} and his queen {1} peacefully ruled the kingdom of
{2} for many years. However, one evening their nemesis {3} with the help of
{4}, {5}, and {6} invaded their kingdom which lead to an infamous war in {2}
history called {8}. This war lasted {9} years. In the end {3} and his goons pillaged the land, destroyed the villagers,
and usurped {0} and {1}. THE END :-(""".format(your_name, queen_name, kingdom, villian, thief,
evil_sorcerer, rogue, kingdom, war_name, years)
print(message)
elif have_enemies == 'n' and have_enemies == 'n':
message = """
The great {0} and his queen {1} lived in the kingdom of
{2} for many years alone.
""".format(your_name, queen_name, kingdom)
print(message)
pass
def female_adventure():
"""This the function for the female adventure."""
your_name = input('Enter your name: ')
king_name = input('What\'s the name of your king? ')
kingdom = input('What\'s the name of your kingdom? ')
have_allies = input('Do you have allies? Enter "y" for yes or "n" for no. ')
have_enemies = input('Do you have enemies? Enter "y" for yes or "n" for no. ')
if have_allies == 'y':
paladin = input('Enter your paladin\'s name ')
wizard = input('Enter your wizard\'s name ')
warrior = input('Enter your warrior\'s name ')
if have_allies == 'n':
pass
if have_enemies == 'y':
print('{} got enemies, got a lot of enemies'.format(your_name))
villian = input('Enter your villian\'s name ')
war_name = input('What\'s the name of your war? ')
years = int(input('How many years did the war last? '))
thief = input('Enter your thief\'s name ')
evil_sorcerer = input('Enter evil sorcerer\'s name ')
rogue = input('Enter rogue\'s name ')
if have_enemies == 'n':
pass
if have_allies == 'y' and have_enemies == 'y':
message = """
The great {0} and her king {1} peacefully ruled the kingdom of
{2}. However, a great war called {3} erupted. {0}'s nemesis {4} invaded
her kingdom. With the help of {5}, {6}, and {7}, {4} pillaged their land,
stole precious resources, and brutally attacked their villagers.
Queen {0} and King {1} with the help of {8}, {9}, and {10} valiantly
fought back and defeated {4} after {11} years of fierce fighting. Order was finally
restored and everyone in their kingdom lived happily ever after :-).""".format(your_name.capitalize(),
king_name.capitalize(),
kingdom.capitalize(),
war_name.capitalize(),
villian.capitalize(),
thief.capitalize(),
evil_sorcerer.capitalize(),
rogue.capitalize(),
paladin.capitalize(),
wizard.capitalize(),
warrior.capitalize(), years)
print(message)
elif have_allies == 'y' and have_enemies == 'n':
message = """
The great {0} and her king {1} peacefully ruled the kingdom of
{2}. With the help of {3}, {4}, and {5}, {0} and {1} were able to keep their
kingdom safe forever. The entire kingdom of {2} lived happily ever after :-).True Story.THE END.""".format(
your_name, king_name,
kingdom, paladin, wizard, warrior, kingdom)
print(message)
elif have_allies == 'n' and have_enemies == 'y':
message = """
The great {0} and her king {1} peacefully ruled the kingdom of
{2} for many years. However, one evening their nemesis {3} with the help of
{4}, {5}, and {6} invaded their kingdom which lead to an infamous war in {2}
history called {7}. This war lasted {8} years. In the end {3} and his goons pillaged the land, destroyed the villagers,
and usurped {0} and {1}. THE END :-(""".format(your_name, king_name, kingdom, villian,
thief, evil_sorcerer, rogue, kingdom,
war_name, years)
print(message)
elif have_enemies == 'n' and have_enemies == 'n':
message = """
The great {0} and her king {1} lived in the kingdom of
{2} for many years alone.
""".format(your_name, king_name, kingdom)
print(message)
pass
gender = input('Enter your gender: "m" for male, "f" for female.'
)
# converts input to lower
gender = gender.lower()
if gender == 'f':
female_adventure()
elif gender == 'm':
male_adventure()
else:
print('Enter correct option or you "can\'t" play!')
|
d197d685ffe9965de5d52f0e98499c1df83b28dd | nullbit01/Cracking-Python-Bootcamp | /01_numbers_in_python.py | 3,638 | 4.375 | 4 | ###########################################
# Code from python
# Features python variables, numbers, and
# builtin data types
#
#
# By Doug Purcell
# http://www.purcellconsult.com
#
############################################
###############################
# creating variables in python
###############################
a = 5
b = 10
c = a
d = a**2
e = d + 10
#############################################
# to view the output use the print() function
#############################################
print(a)
print(b)
print(c)
print(d)
print(e)
# prints text
print('Hello World')
# prints numbers and text, is really a tuple.
print(5, 'birds')
# prints empty space
print()
###############################
# using python as a calculator
# learn the operators:
# + & -
# * & /
# % & //
# ** and ()
###############################
print(10 + 10)
print(20 - 5)
print(9 * 9)
print(5 / 2)
# floor functionality
print(5 // 2)
print(10 % 3)
print(5 ** 3)
# the parentheses changes order of execution
print(10 - 3 / (5 % 3))
print()
#######################################
# two main types of numbers in python:
# int and float.
########################################
a1 = 5
print(type(a))
# euler's number
b1 = 2.7182818284590452353602874713527
print(type(b1))
# 7.718281828459045
c1 = a1 + b1
print(c1)
# 7.Truncates the mantissa
print(int(c1))
print(float(c1))
print()
##################################################
# reading in text and numbers in python!
# the input() function allows
# you to create interactive and fun programs :-)!
##################################################
# reading in text
# your_message = input('What\'s your message? ')
# print('The message is: ', your_message)
################################################
# reading in numbers. Pass the input() function
# to the int() function.
################################################
your_int = int(input('Enter any number '))
print('Your number is: ', your_int)
print()
###########################################
# importing modules
# Gain more functionality by importing
# modules like math
###########################################
import math
from math import degrees
print(math.sin(90))
print(math.cos(180))
print(math.tan(45))
# converts to degrees
print(degrees(math.pi/2))
print(math.pi)
print(math.factorial(4))
print(math.gcd(75, 1000))
print(math.isclose(10, 10.00000000000000000000000000000001))
print(math.exp(3))
print(math.log(16, 2))
print(math.floor(5.5242))
print(math.sqrt(9))
#################################
# Microprogramming session
#
# calculate change for groceries
# area of a triangle
# quadratic equation
#
################################
milk = 2.90
loaf_of_bread = 1.89
pack_of_ham = 4.99
grocery_cost = milk + loaf_of_bread + pack_of_ham
change = int(input('Enter the amount of change you have in $10, $20, or '
'$50 portions. '))
your_change = change - grocery_cost
print(round(your_change, 2))
# area of a triangle is 1/2 * b * h
base = float(input('Enter base of a triangle '))
height = float(input('Enter height of triangle '))
area = 1/2 * base * height
print('Area of a triangle with base', base, 'and height ', height, 'is', area)
# quadratic formula
# Has two roots:
# x = -b + sqrt(b^2 - 4ac) / 2a
# x = -b - sqrt(b^2 - 4ac) / 2a
# write a program that accepts a, b, and c, then
# returns correct answer
from math import sqrt
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))
x1 = 0
x1 = -b + sqrt(b**2 - (4 * a * c))
x1 = x1 / (2 * a)
x2 = -b - sqrt(b**2 - (4 * a * c))
x2 = x2 / (2 * a)
print('x1 =', x1)
print('x2 =', x2)
|
a0358832b918a12cb565c33d2aec314da3755c37 | eaphilli/Geocoding_Suite | /Business_Names_to_Lat_Lng/BusinessNamestoLatLng.py | 2,239 | 3.609375 | 4 | """Python script that converts Business names to lat,lng coordinates using google places API
@author
Shyam Thiagarajan
@requires
output.txt is empty
empty last line in companies.txt
@inputs
Business names from companies.txt
@outputs
lat and lng to output.txt
API KEY CHOICES:
AIzaSyCFfJiEeUo_nXV6nc1TcOJZIS5RCTJAAHQ
"""
import requests
"""Gets companies from companies.txt.
@param companies
list of companies to geolocate
@updates companies"""
def getCompanies(companies):
with open('companies.txt') as f:
names = (f.readlines())
for words in names:
try:
words = words.split('(', 1)[0]
words = words.split('-', 1)[0]
print(words)
companies.append(words)
except:
companies.append(words)
"""Writes lat and lng to console and file.
@param lat_lng
coordinates to output
@param out
file to write to"""
def writeLatLng(lat_lng, out):
out.write(lat_lng + '\n')
print(lat_lng)
"""Finds Lat and Lng of Company.
@param comp
company to geolocate
@param count
index of list (for counting)
@param total
total number of names to geocode
"""
def findLatLng(comp, count, total):
name = str(comp)
name = name.replace(" ", "+")
print(name)
param = str(
"https://maps.googleapis.com/maps/api/place/textsearch/json?query=" + name + "&administrative_level_2=" +
"&components=|country:US" + "&key=" + API_KEY)
print(param)
# process JSON
r = requests.get(param)
j = r.json()
try:
lat = str(j['results'][0]['geometry']['location']['lat'])
lng = str(j['results'][0]['geometry']['location']['lng'])
lat_lng = lat + ',' + lng
except:
lat_lng = 'error'
print(str(count) + ' of ' + str(total))
return lat_lng
"""Determines lat and lng of company.
@updates output.txt
"""
def main():
companies = []
getCompanies(companies)
out = open('output.txt', 'a')
count = 1
total = len(companies)
for comp in companies:
lat_lng = findLatLng(comp, count, total)
writeLatLng(lat_lng, out)
count += 1
if __name__ == '__main__':
API_KEY = 'AIzaSyCFfJiEeUo_nXV6nc1TcOJZIS5RCTJAAHQ'
main()
print('DONE')
|
5b023960a27d8b0a1247a06fc3b54cb5935e9056 | aasalaza/Project_1 | /ballistic.py | 3,783 | 4.28125 | 4 | '''
The first part of the program sets the initial parameters for an object thrown at some angle above the horizont, including the air resistance dragging effect.
Then, it solves the differential equation m(dV/dT)=mg-cV, describing the motion ( the numerical solution).
The second part computes the analytical solution and plots both of them in a x-y plot.
The third part creates an animation of the motion and shows the landing point.
The new things used are odeint, plots with title, grid and labeled arrow, and animation.
'''
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import numpy as np
import math
import matplotlib.animation as animation
c=0.7 #Sets the dragging term.
m=0.1 #Sets object's mass.
g=9.81 #Sets gravitational acceleration.
Vx0=10 #Sets initial speed along the x-axis.
Vy0=10 #Sets initial speed along the y-axis.
thetha=math.pi/4 #Sets the angle of throwing.
V0=np.sqrt(Vx0**2+Vy0**2) #Calculates the initial velocity.
t0 = 0.0 # Sets the initial time
tmax=2.0 # Sets the final final time
steps=100 # Sets the number of time step
tLF = np.linspace(t0, tmax, steps+1) # Creates a 1-D array of time values
y0LF = [0.0, Vx0, 0.0, Vy0] # Creates an array with the initial condition for x-position, velocity along x, y-position, velocity along y.
def deriv(yLF,tF): #Creates the function which computes the derivatives
Vx = yLF[1] # Identifies the velocity along x axis
Vy=yLF[3] #Identifies the velocity along y axis
return [Vx, -c*Vx/m, Vy, -g-c*Vy/m] # The function outputs [dx/dt, dVx/dt, dy/dt, dVy/dt]
yM = odeint(deriv, y0LF, tLF) # The 4-D array containing the solution for the differential equation
plt.plot(yM[:,0],yM[:,2],'.',label='Numerical solution') #Plots y over x numerically.
#Analytical Solution:
VT=m*g/c #Calculates the terminal velocity
anal_x=((V0*VT)/g)*np.cos(thetha)*(1-np.exp(-g*tLF/VT)) #calculates dx/dt using the analytical solution
anal_y=(VT/g)*(V0*np.sin(thetha)+VT)*(1-np.exp(-g*tLF/VT))-VT*tLF #calculates dy/dt using the analytical solution
plt.plot(anal_x,anal_y,label='Analytical solution') #Plots y over x analytically.
plt.grid()
plt.xlabel('Horizontal axis [meters]')
plt.ylabel('Vertical axis [meters]')
plt.legend()
plt.title('Projectile motion with air resistance.')
plt.savefig('ballistic.pdf')
#Computing answer of the questions:
i=np.abs(yM[1:steps,2]).argmin() #calculates the point from the y-array closest to 0 (after the initial point)and assigns it to i (=impact).
D=yM[i+1,0] #Computes the distance to the point of impact.
H=np.amax(yM[:,2]) #Finds the max value of the array anal_y, which represents the highest point of the trajectory and assignes it to H.
TF=tLF[i+1]
Vxi=yM[i+1,1]
Vyi=yM[i+1,3]
Vi=np.sqrt(Vxi**2+Vyi**2)
#Creates the file .txt and saves the answers of the questions
f=open('ballistic.txt','w')
f.write(' The distance to the point of impact is {}.\n The highest point of the trajectory is at {} meters above ground.\n The time for flight is {} s. \n The impact velocity is {} m/s.'.format(str(D),str(H),str(TF),str(Vi)))
f.close()
#Extra: animation of the projectile motion.
fig, ax = plt.subplots() #sets the initial figure.
line, = ax.plot(anal_x,anal_y) # Sets the values of 'line'
def animate(k): #Creates the animation function, which updates the data in each frame.
line.set_data(anal_x[:k],anal_y[:k])
return line,
plt.axis([0.0, 2.5, 0.0, 2.5]) #Sets the range of the axis.
ani = animation.FuncAnimation(fig, animate,100,interval=50,blit=True) #Creates the animation.
plt.title('Animation of projectile motion with air resistance.')
#Adds an arrow pointing at the landing spot:
plt.annotate('landing point', xy=(D, 0), xytext=(1.8, 0.8), arrowprops=dict(facecolor='blue', shrink=0.02),)
plt.show()
|
d55b17b8c7c508e486c24d9822f23672b2a7afae | Sagar-16/Python-programs | /0-1 knapsack.py | 673 | 3.796875 | 4 | #python program for 0-1 knapsack using recursion
weights=[1,3,6,7,10] # weights array for items
values=[2,4,7,9,12] # values array for items
n=5 #number of items
w=10 #bags weight
def knapsack(weights,values,w,n):
if n==0 or w ==0: #base case
return 0
if weights[n-1]<=w: #if last items weight less than bags weight
return max((values[n-1]+ knapsack(weights,values,w-weights[n-1],n-1)),(knapsack(weights,values,w,n-1)))
if weights[n-1]>w: # if last items weight more than bags weight
return knapsack(weights,values,w,n-1)
result = knapsack(weights,values,w,n)
print(result) #printing result
#13 #answer
|
250d6f88944cafcbbe870b2d05813c7bf6c68d0e | SaikumarS2611/Python-3.9.0 | /Packages/Patterns_Packages/Alphabets/Lower_Case_alphabets/c.py | 909 | 4.09375 | 4 | def for_c():
""" Lower case Alphabet letter 'c' pattern using Python for loop"""
for row in range(4):
for col in range(4):
if col==0 and row%3!=0 or col>0 and row%3==0:
print('*', end = ' ')
else:
print(' ', end = ' ')
print()
def while_c():
""" Lower case Alphabet letter 'c' patter using Python while loop"""
row = 0
while row<4:
col = 0
while col<4:
if col==0 and row%3!=0 or col>0 and row%3==0:
print('*', end = ' ')
else:
print(' ', end = ' ')
col += 1
print()
row += 1
|
dc2da5e06755ee1ef83d933b77b4ed1ffa1c6d71 | SaikumarS2611/Python-3.9.0 | /Packages/Patterns_Packages/Symbols/Equilateral_Triangle.py | 479 | 4.125 | 4 |
def for_equilateral_triangle():
"""Shape of 'Equilateral Triangle' using Python for loop"""
for row in range(12):
if row%2!=0:
print(' '*(12-row), '* '*row)
def while_equilateral_triangle():
"""Shape of 'Equilateral Triangle' using Python while loop"""
row = 0
while row<12:
if row%2!=0:
print(' '*(12-row), '* '*row)
row += 1
|
97179eb2d9dcaf051c37211d40937166869a0c83 | SaikumarS2611/Python-3.9.0 | /Packages/Patterns_Packages/Alphabets/Upper_Case_alphabets/D.py | 970 | 4.21875 | 4 | # using for loop
def for_D():
""" Upper case Alphabet letter 'D' pattern using Python for loop"""
for row in range(6):
for col in range(5):
if col==0 or row in (0,5) and col<4 or col==4 and row>0 and row<5:
print('*', end = ' ')
else:
print(' ', end = ' ')
print()
# using while loop
def while_D():
""" Upper case Alphabet letter 'D' pattern using Python while loop"""
row = 0
while row<6:
col = 0
while col<5:
if col==0 or row in (0,5) and col<4 or col==4 and row>0 and row<5:
print('*', end = ' ')
else:
print(' ', end = ' ')
col +=1
print()
row +=1
|
ae17927ae7d2911b505dca233df10577c39efd6e | SaikumarS2611/Python-3.9.0 | /Packages/Patterns_Packages/Alphabets/Lower_Case_alphabets/z.py | 869 | 4.125 | 4 | def for_z():
""" Lower case Alphabet letter 'z' pattern using Python for loop"""
for row in range(4):
for col in range(4):
if row==0 or row==3 or row+col==3:
print('*', end = ' ')
else:
print(' ', end = ' ')
print()
def while_z():
""" Lower case Alphabet letter 'z' pattern using Python while loop"""
row = 0
while row<4:
col = 0
while col<4:
if row==0 or row==3 or row+col==3:
print('*', end = ' ')
else:
print(' ', end = ' ')
col += 1
print()
row += 1
|
e77e9c67faf6319143afd737cee920a98496cce0 | SaikumarS2611/Python-3.9.0 | /Packages/Patterns_Packages/Symbols/Reverse_triangle.py | 444 | 4.375 | 4 | def for_reverse_triange():
"""Shape of 'Reverse Triangle' using Python for loop """
for row in range(6,0,-1):
print(' '*(6-row), '* '*row)
def while_reverse_triange():
"""Shape of 'Reverse Triangle' using Python while loop """
row = 6
while row>0:
print(' '*(6-row), '* '*row)
row -= 1
|
35e9d5de6afa12398a59af95f454097f3231d4ad | SaikumarS2611/Python-3.9.0 | /Packages/Patterns_Packages/Symbols/Rectangle.py | 926 | 4.34375 | 4 | def for_rectangle():
"""Shape of 'Rectangle' using Python for loop """
for row in range(6):
for col in range(8):
if row==0 or col==0 or row==5 or col==7:
print('*', end = ' ')
else:
print(' ', end = ' ')
print()
def while_rectangle():
"""Shape of 'Rectangle' using Python while loop """
row = 0
while row<6:
col = 0
while col<8:
if row==0 or col==0 or row==5 or col==7:
print('*', end = ' ')
else:
print(' ', end = ' ')
col += 1
print()
row += 1
|
c465caaccdd28b99ba3cada1325ee3899e4e7542 | Konstantce/ToySTARK | /relations/ARP.py | 3,332 | 3.71875 | 4 | from algebra.polynomials import *
from utils.utils import *
import itertools
class ARP:
def __init__(self, instance, size, witness = None):
"""Instance format: The instance x is a tuple (Fq, d, C) where:
* Fq is a finite field of size q.
* d is an integer representing a bound on the degree of the witness.
* C is a set of |C| tuples (M_i, P_i, Q_i) representing constraints, where
M_i is the mask which is a sequence of field elements M_i = {M_ij in Fq} for j in (1..|M_i|)
P_i is the condition of the constraint which is a polynomial with |Mi| variables.
Q_i in Fq[x] is the domain polynomial of the constraint which should vanish on the locations where the constraint should hold.
(here we represent Q_i as a set of its' roots)
"""
(field, d, C) = instance
self.field = field
self.degree = d
self.constraints = C
"""Witness format: The witness w is a polynomial f in Fq[x]. A constraint (M, P, Q) is said to hold at a location x in Fq
if P(f(x * M_1), f(x * M_2), ..., f(x * M_|M|)) = 0
We say that f satisfies the constraint if previous equality holds at every x in Fq for which Q(x) = 0.
We say that w satisfies the instance if and only if deg(f) < d and f satisfies all of the
constraints.
"""
self.witness = witness
#TODO: remove it later, associate with particular domain instead
self.size = size
def check_witness(self):
assert self.witness is not None, "Witness is undefined at this point."
#copy witness for now
import copy
witness = copy.deepcopy(self.witness)
if witness.degree() > self.degree:
return False
for M, P, Q in self.constraints:
for x in Q:
P_copy = copy.deepcopy(P)
if P_copy.evaluate([witness.evaluate(x*m) for m in M]) != 0:
return False
return True
def set_witness(self, witness):
self.witness = witness
@classmethod
def fromAIR(cls, AIR):
assert AIR.consistency_check(), "AIR instance is not fully defined."
field = AIR.field
W = AIR.w
T = AIR.T
poly_ring = polynomialsOver(field, "X")
mul_group_order = field.get_num_of_elems() - 1
if mul_group_order % (W*T) != 0:
raise StarkError("Unable to generate ARP instance for %s of size %d" %(field, W*T))
gamma = field.get_prim_element() ** (mul_group_order / (W*T))
full_mask = [gamma ** k for k in xrange(2*W)]
Q = [gamma ** (W*k) for k in xrange(T-1)]
C = [(full_mask, P, Q) for P in AIR.trace_constraints]
C += [([1], X - alpha, [gamma**(i*W+j)]) for (i, j, alpha) in AIR.boundary_constraints]
#TODO: how is degree defined?
degree = T * W
instance = (field, degree, C)
if AIR.witness is not None:
domain, values = zip(*[(gamma**(t*W+j), AIR.witness[t][j]) for (t, j) in itertools.product(xrange(T), xrange(W))])
witness = construct_interpolation_poly(poly_ring, domain, values)
else:
witness = None
return cls(instance, W*T, witness)
|
bee56f7245f12089b0b9758c39688decddf364cc | jmcculloch796/robotplanner | /ExampleProblems/Large Grid/main.py | 3,281 | 3.890625 | 4 | """
F29AI - Artificial Intelligence and Intelligent Agents
Coursework - Part I - A* Search
Big Grid with 3 robots. An example program to show our
'10x10 grid with 3 robots' example.
Ronan Smith & Jamie McCulloch
Last edited: 10.11.2016
"""
from implementation import *
from nodes import *
from a_star import *
from collisions import *
"""
Print a newline.
"""
def nl():
print("\n")
"""
The main method.
"""
def main():
#for choosing the no of robots from command line
# remember to uncomment random generators below
#noOfRobots = int(input("How many robots would you like? "))
#print("")
#robots = [None] * noOfRobots
#goals = [None] * noOfRobots
#paths = [None] * noOfRobots
# -----------------------------------------------------
# for manually entering no of robots.
noOfRobots = 3
robots = [None] * noOfRobots
goals = [None] * noOfRobots
paths = [None] * noOfRobots
# for manually choosing the robots starting and goal positions.
# remember to comment out random generators below.
robots[0] = (2,1) #R0
robots[1] = (2,8) #R1
robots[2] = (8,1) #R2
goals[0] = (8,6) #G0
goals[1] = (8,5) #G1
goals[2] = (4,9) #G2
# -----------------------------------------------------
for i in range(noOfRobots):
#robots[i] = nodeGenerator(length, height)
while ((robots[i]) in diagram4.walls) or ((robots[i]) in diagram4.weights):
robots[i] = wallspawn(robots[i], goals[i])
print("The start for robot R", i, " is ", (robots[i]))
#goals[i] = goalGenerator(length, height, robots[i])
while ((goals[i]) in diagram4.walls or (goals[i]) in diagram4.weights):
goals[i] = wallspawn(robots[i], goals[i])
nl()
print("The goal for R", i, ", G", i, " is ", goals[i])
came_from, cost_so_far, paths[i] = a_star_search(diagram4, noOfRobots, start=(robots[i]), goal=(goals[i]))
#paths[i] = reconstruct_path(came_from, robots[i], goals[i])
print("-------------------------------------------------------------")
diagram4.robots.append((robots[i]))
diagram4.goals.append((goals[i]))
draw_grid(diagram4, width=4, point_to=came_from)
nl()
collisionChecker(paths)
print("-------------------------------------------------------------")
def collisionChecker(p):
#print("TEST length p: ", len(p))
collisionFound = False
for i in range(0,len(p)):
#print("TEST length p[", i, "]", len(p[i]))
for j in range(0,len(p[i][:-1])):
for k in range(0,len(p[i][:-1])):
if(i == k):
break
if (len(p[i]) > len(p[k])):
break
elif(p[i][j] == p[k][j]):
print("Collision between R",k,"and R",i, "at",p[i][j],".")
print("These two Robots must travel at seperate times.")
collisionFound = True
if(collisionFound == False):
print("No collisions found on these paths.")
print("The robots can travel simultaneously. ")
return collisionFound
"""
Tells Python interpreter to run the main method first.
"""
if __name__ == '__main__':
main()
|
b964aa87cc49f22ba948c6e270ebc7736e6329c6 | conorbradley7/MPT | /MPT 3/Combinations.py | 231 | 3.703125 | 4 | '''
combinations
n = number of numbers in set
k = number of numbers per combination
n/k = number of combinations
find the number of outputs given a n value and a k value where k <= n
'''
def combos():
|
214cc05b6e51051522abc9a9be28cf21130d47c0 | conorbradley7/MPT | /MPT 1 & 2/Labs/Lab04/investMoney.py | 975 | 4 | 4 | #import modules
import math
def investMoney():
'''
Pyton program to invest money over some years.
Inputs: amount, nrYears
Output: amount, profit and cummulated amount for each year
How to do it:
repeat for each year
calculate profit and cummulated amount print them
???about next year amount?
'''
#inputs
amount= float(input('Initial Amount'))
rate = float(input('Invest Rate'))
nrYears = int(input('Nr of Years'))
# repeat calculation
for i in range(nrYears):
# calculate profit, cummulate amount
profit = amount*rate
newAmount = amount+profit
print('Year:', i,)
print('Amount', round(amount,2))
print('Profit', round(profit,2))
print('New Amount', round(newAmount,2))
print(' ')
# prepare calculation for next year
amount = newAmount
#end for
# end investMoney
|
a484f8294c03e56e67adbe8480b530f3b6dcc6a4 | conorbradley7/MPT | /MPT 3/Self Descriptive.py | 673 | 3.65625 | 4 | '''
input: numbers EG: 1, 2, 3
output: selfDescribe number: 11 12 13 -> 1 one 1 two and 1 three
'''
def group(lst):
acc = []
for c in lst:
if acc != [] and c == acc[-1][0]:
acc[-1] += c
else:
acc.append(c)
return acc
word = input('Thing To Be Grouped:')
x = group(word)
print(x)
def look_say(seed):
while True:
old = str(seed)
new = int(''.join(str(len(g)) + g[0]for g in group(old)))
yield new
seed = new
num = int(input('Number:'))
i = 0
lim = 100
for x in look_say(num):
print(x)
if i>10:
break
i+=1
|
a8eb547555c78fef3925cb7b43b9f73f541a745f | conorbradley7/MPT | /Other Programs/Calculator.py | 3,235 | 4.0625 | 4 | #Pythagoras=================================================================================================================================================================================
import math
def pythagorasHyp():
adj = int(input('Adjacent:'))
opp = int(input('Opposite'))
hyp = math.sqrt(adj**2 + opp**2)
print(hyp)
def pythagorasOpp():
adj = int(input('Adjacent:'))
hyp = int(input('Hypotenuse'))
opp = math.sqrt(hyp**2 - adj**2)
print(opp)
def pythagorasAdj():
hyp = int(input('Hypotenuse:'))
opp = int(input('Opposite'))
adj = math.sqrt(hyp**2 - opp**2)
print(adj)
#Roots======================================================================================================================================================================================
import math
def roots():
a = (int(input('a:')))
b = (int(input('b:')))
c = (int(input('c:')))
desc = ((b**2) -4*a*c)
if desc < 0:
print('No Real Roots')
if desc == 0:
x1 = (-b+math.sqrt(b**2-4*a*c))/2*a
print(('x:'), x1)
if desc > 0:
x1 = (-b+math.sqrt((b**2)-(4*(a*c))))/(2*a)
x2 = (-b-math.sqrt((b**2)-(4*(a*c))))/(2*a)
print('x1:', x1)
print('x2:', x2)
def descriminent():
a = (int(input('a:')))
b = (int(input('b:')))
c = (int(input('c:')))
desc = ((b**2) -4*a*c)
print('Descriminent:',desc)
#Factors====================================================================================================================================================================================
import math
def factors():
x = int(input('Enter A Number:'))
print("The factors of",x,"are:")
for i in range(1, int(math.sqrt(x)) + 1):
if x % i == 0:
print(x//i ,i)
#Primes=====================================================================================================================================================================================
def isPrime():
num = int(input('Your Number:'))
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"Is Not Prime")
print(i,"times",num//i,"is",num)
break
else:
print(num,"Is Prime")
else:
print(num,"Is Not Prime")
def allPrimes():
n = int(input('Number To Go Up To:'))
for i in range (n+1):
if AllPrimesIsPrime(i):
print(i)
def AllPrimesIsPrime(n):
if n == 0 or n== 1:
return 'Not Prime'
elif n == 2 or n== 3:
return 'Prime'
elif n%2 == 0:
return 'Not Prime'
for d in range (3, int(math.sqrt(n))+1, 2):
if n%d == 0:
return 'Not Prime'
else:
return 'Prime'
#===========================================================================================================================================================================================
#def allPrimes():
|
e6088db9c546542b5bba0f26e67a222ed11e5878 | 3070owner/pingpong | /test.py | 4,437 | 3.5 | 4 |
#범위설정 잘못함
import pygame
import sys
import random
import time
COLOR = {"BLACK":(0,0,0),"WHITE":(255,255,255),"RED":(255,0,0),"GREEN":(0,255,0)}
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 800
#How 2 use: COLOR["BLACK"]
class Ball:
def __init__(self, x_speed_ball, y_speed_ball, pos_ball = [400,400]):
self.pos_ball = pos_ball
self.x_speed_ball = x_speed_ball
self.y_speed_ball = y_speed_ball
def ball_start(self):
self.pos_ball = [400,400]
print('ball spawn')
#time.sleep(3)
class Bar:
def __init__(self, bar_speed = 0.42, left_pos_bar = [40, 400], right_pos_bar = [760, 400] ):
self.bar_speed = bar_speed
self.left_pos_bar = left_pos_bar
self.right_pos_bar = right_pos_bar
def bar_move(self):
key_event = pygame.key.get_pressed()
if key_event[pygame.K_w]:
self.left_pos_bar[1] -= self.bar_speed
if key_event[pygame.K_s]:
self.left_pos_bar[1] += self.bar_speed
if key_event[pygame.K_UP]:
self.right_pos_bar[1] -= self.bar_speed
if key_event[pygame.K_DOWN]:
self.right_pos_bar[1] += self.bar_speed
class Game:
def __init__(self, screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)), Lp_point = 0, Rp_point = 0, Rbarlen=40, Lbarlen=40):
self.Rbarlen = Rbarlen
self.Lbarlen = Lbarlen
self.screen = screen
self.Rp_point = Rp_point
self.Lp_point = Lp_point
self.a_1 = Ball(0.2, 0.4)
self.a_2 = Bar()
pygame.init()
pygame.display.set_caption("pygame")
def draw(self):
self.screen.fill(COLOR["BLACK"])
pygame.draw.rect(self.screen, COLOR["WHITE"], pygame.Rect(self.a_2.left_pos_bar[0], self.a_2.left_pos_bar[1],5,self.Lbarlen))
pygame.draw.rect(self.screen, COLOR["WHITE"], pygame.Rect(self.a_2.right_pos_bar[0], self.a_2.right_pos_bar[1],5,self.Rbarlen))
pygame.draw.circle(self.screen, COLOR["RED"],[self.a_1.pos_ball[0],self.a_1.pos_ball[1]] ,5)
pygame.display.update()
def score(self):
if self.a_1.pos_ball[0]<5:
self.Rp_point +=2
print('right player +2')
self.a_1.ball_start()
print("right player score:",self.Rp_point)
elif self.a_1.pos_ball[0]>795:
self.Lp_point +=2
print('left player +2')
self.a_1.ball_start()
print("left player score:",self.Lp_point)
def ball_move(self):
if (self.a_1.pos_ball[1] - self.a_2.left_pos_bar[1]) <= self.Lbarlen and (self.a_1.pos_ball[1]-self.a_2.left_pos_bar[1]) >=0:
if abs(self.a_2.left_pos_bar[0] - self.a_1.pos_ball[0]) <=1:
self.a_1.x_speed_ball = abs(self.a_1.x_speed_ball)
print("done")
if (self.a_1.pos_ball[1] - self.a_2.right_pos_bar[1]) <= self.Rbarlen and (self.a_1.pos_ball[1] - self.a_2.right_pos_bar[1]) >=0:
if abs(self.a_2.right_pos_bar[0] - self.a_1.pos_ball[0]) <=1:
self.a_1.x_speed_ball = -abs(self.a_1.x_speed_ball)
print("done2")
if self.a_1.pos_ball[1]<5:
self.a_1.y_speed_ball = -self.a_1.y_speed_ball
elif self.a_1.pos_ball[1]>795:
self.a_1.y_speed_ball = -self.a_1.y_speed_ball
self.a_1.pos_ball[0] += self.a_1.x_speed_ball
self.a_1.pos_ball[1] += self.a_1.y_speed_ball
def ItemCall(self):
key_event = pygame.key.get_pressed()
if key_event[pygame.K_0]:
if self.Rp_point>=1:
self.Rp_point-=1
self.Rbarlen+=random.randint(3, 7)
print(self.Rbarlen)
if key_event[pygame.K_1]:
if self.Lp_point>=1:
self.Lp_point-=1
self.Lbarlen += random.randint(3, 7)
print(self.Lbarlen)
test = Game()
clock=pygame.time.Clock()
while True:
clock.tick(1000)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.display.quit()
sys.exit()
test.a_2.bar_move()
test.ball_move()
test.draw()
test.ItemCall()
#print(test.a_1.pos_ball)
test.score()
if test.Rbarlen>100:
print('player2 win')
pygame.display.quit()
sys.exit()
elif test.Lbarlen>100:
print('player1 win')
pygame.display.quit()
sys.exit() |
d0a6cb2b084d953f976a981259ebcc06a801ee09 | s4nktum/infa_2021 | /lec_02/multiangle.py | 346 | 3.6875 | 4 | import turtle as trt
import numpy as np
trt.shape('turtle')
n = 3
x = 50
def angle(n, x):
a = 360 / n
for i in range(1,n+1):
trt.left(a)
trt.forward(x)
trt.penup()
trt.right(a/2)
trt.forward(200**0.5)
trt.left(a/2 + 5)
trt.pendown()
for i in range(1,11):
angle(n,x)
n += 1
x += 10
|
48ed4732c564bf5f3d88aa263f727615cc8107b8 | claraqqqq/l_e_e_t | /78_subsets.py | 662 | 3.75 | 4 | # Subsets
# Given a set of distinct integers, S, return all possible subsets.
# Note:
# Elements in a subset must be in non-descending order.
# The solution set must not contain duplicate subsets.
# For example,
# If S = [1,2,3], a solution is:
# [
# [3],
# [1],
# [2],
# [1,2,3],
# [1,3],
# [2,3],
# [1,2],
# []
# ]
class Solution:
# @param S, a list of integer
# @return a list of lists of integer
def subsets(self, S):
return self.subsetsRecur([], sorted(S))
def subsetsRecur(self, cur, S):
if S:
return self.subsetsRecur(cur, S[1:]) + self.subsetsRecur(cur+[S[0]], S[1:])
return [cur] |
3646422ea8a820273f0a09a10890d06da6bff19b | claraqqqq/l_e_e_t | /11_container_with_most_water.py | 766 | 3.859375 | 4 | # Container With Most Water
# Given n non-negative integers a1, a2, ..., an, where each
# represents a point at coordinate (i, ai). n vertical lines are
# drawn such that the two endpoints of line i is at (i,ai) and (i,
# 0). Find two lines, which together with x-axis forms a
# container, such that the container contains the most water.
# Note: You may not slant the container.
class Solution:
# @return an integer
def maxArea(self, height):
left = 0
right = len(height)-1
water = 0
while left < right:
water = max(water, (right-left) * min(height[left], height[right]))
if height[left] < height[right]:
left += 1
else:
right -= 1
return water |
043941cdd77c0fbef0e2aed141fd19339ebbe3ef | claraqqqq/l_e_e_t | /36_valid_sudoku.py | 1,569 | 3.9375 | 4 | # Valid Sudoku
# Determine if a Sudoku is valid, according to: Sudoku Puzzles
# - The Rules.
# The Sudoku board could be partially filled, where empty
# cells are filled with the character '.'.
# A partially filled sudoku which is valid.
# Note:
# A valid Sudoku board (partially filled) is not necessarily
# solvable. Only the filled cells need to be validated.
# Sudoku Puzzles - The Rules.
# There are just 3 rules to Sudoku.
# Each row must have the numbers 1-9 occuring just once.
# Each column must have the numbers 1-9 occuring just once.
# And the numbers 1-9 must occur just once in each of the 9 sub
# -boxes of the grid.
class Solution:
# @param board, a 9x9 2D array
# @return a boolean
def isValidSudoku(self, board):
def isValid(x, y, tmp):
for idx in range(9):
if board[idx][y] == tmp:
return False
for idy in range(9):
if board[x][idy] == tmp:
return False
for idx in range(3):
for idy in range(3):
if board[(x/3)*3+idx][(y/3)*3+idy] == tmp:
return False
return True
for idx in range(9):
for idy in range(9):
if board[idx][idy] == '.':
continue
tmp = board[idx][idy]
board[idx][idy] = 'D'
if isValid(idx, idy, tmp) == False:
return False
else:
board[idx][idy] = tmp
return True |
b7cf0ad56f664cab16423ec3baeaea62603d29bb | claraqqqq/l_e_e_t | /102_binary_tree_level_order_traversal.py | 1,178 | 4.21875 | 4 | # Binary Tree Level Order Traversal
# Given a binary tree, return the level order traversal of its
# nodes' values. (ie, from left to right, level by level).
# For example:
# Given binary tree {3,9,20,#,#,15,7},
# 3
# / \
# 9 20
# / \
# 15 7
# return its level order traversal as:
# [
# [3],
# [9,20],
# [15,7]
# ]
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of lists of integers
def levelOrder(self, root):
if root is None:
return []
curNodes = [root]
result = []
while curNodes:
curNodeVals = []
nextNodes = []
for node in curNodes:
curNodeVals.append(node.val)
if node.left:
nextNodes.append(node.left)
if node.right:
nextNodes.append(node.right)
result.append(curNodeVals)
curNodes = nextNodes
return result
|
400c8ae876e334744176a1f747912b777083d904 | claraqqqq/l_e_e_t | /135_candy.py | 869 | 3.578125 | 4 | # Candy
# There are N children standing in a line.
# Each child is assigned a rating value.
# You are giving candies to these children subjected to the following requirements:
#
# Each child must have at least one candy.
# Children with a higher rating get more candies than their neighbors.
#
# What is the minimum candies you must give?
class Solution:
# @param ratings, a list of integer
# @return an integer
def candy(self, ratings):
candy_rcrd = [1 for dummy_index in range(len(ratings))]
for index in range(1, len(ratings)):
if ratings[index] > ratings[index - 1]:
candy_rcrd[index] = candy_rcrd[index - 1] + 1
for index in range(len(ratings) - 2, -1, -1):
if ratings[index] > ratings[index + 1]:
if candy_rcrd[index] <= candy_rcrd[index + 1]:
candy_rcrd[index] = candy_rcrd[index + 1] + 1
return sum(candy_rcrd) |
cdd09dafb35bc0077d004e332ab48436810224a7 | claraqqqq/l_e_e_t | /150_evaluate_reverse_polish_notation.py | 1,079 | 4.28125 | 4 | # Evaluate Reverse Polish Notation
# Evaluate the value of an arithmetic expression in Reverse Polish Notation.
# Valid operators are +, -, *, /. Each operand may be an integer or another expression.
# Some examples:
#
# ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
# ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
class Solution:
# @param tokens, a list of string
# @return an integer
def evalRPN(self, tokens):
stack = []
for element in tokens:
if element not in "+-*/":
stack.append(element)
else:
num2 = int(stack.pop())
num1 = int(stack.pop())
if element == "+":
stack.append(str(num1 + num2))
elif element == "-":
stack.append(str(num1 - num2))
elif element == "*":
stack.append(str(num1 * num2))
elif element == "/":
if num1 * num2 > 0:
stack.append(str(num1 / num2))
else:
stack.append(str(-(abs(num1) / abs(num2))))
return int(stack[0])
|
12afa69cd0323b3daca516c39e732f713a8cd9fc | claraqqqq/l_e_e_t | /59_spiral_matrix_II.py | 1,178 | 3.984375 | 4 | # Spiral Matrix II
# Given an integer n, generate a square matrix filled with
# elements from 1 to n2 in spiral order.
# For example,
# Given n = 3,
# You should return the following matrix:
# [
# [ 1, 2, 3 ],
# [ 8, 9, 4 ],
# [ 7, 6, 5 ]
# ]
class Solution:
# @return a list of lists of integer
def generateMatrix(self, n):
matrix = [[0 for dummy_idx in range(n)] for dummy_idx in range(n)]
left = 0
right = n - 1
top = 0
bottom = n - 1
num = 1
while left <= right and top <= bottom:
for idx in range(left, right + 1):
matrix[top][idx] = num
num += 1
for idy in range(top + 1, bottom):
matrix[idy][right] = num
num += 1
for idx in reversed(range(left, right + 1)):
if top < bottom:
matrix[bottom][idx] = num
num += 1
for idy in reversed(range(top + 1, bottom)):
matrix[idy][left] = num
num += 1
left += 1
right -= 1
top += 1
bottom -= 1
return matrix |
18ff611887dc3fa77e4c812014158a3859427171 | OranGeNaL/labs | /8_semestr/rezak/Lab5/progs/BWT.py | 533 | 3.75 | 4 |
def BWT(text):
assert "|" not in text
text = text + "|"
table = [text[i:] + text[:i] for i in range(len(text))]
# print("Перебор")
# for i in table:
# print(i)
# print("Отсортированные")
table = sorted(table)
# for i in table:
# print(i)
last_column = [row[-1:] for row in table]
bwt = ''.join(last_column)
return bwt
text = input("Введите сообщение: ")
print("Зашифрованное сообщение: " + BWT(text))
|
8a8b0c0a06c2c307defdbea728683c64b5802ca2 | KailashGanesh/Sudoku-solver | /sudoku-GUI.py | 7,164 | 3.6875 | 4 | import pygame, sys
from sudokuSolver import *
import copy
def isBoardSloved(board):
'''
parm: (sudoku board array)
return: True if no 0 present in board, False if 0 present
'''
for i in range(len(board)):
if 0 in board[i]:
return False
elif i == 8:
return True
def solveBoardViz(board):
'''
parm: sudoku board array
solves the board while also displaying it's working on pygame screen
'''
spot = find_empty_spot(board)
if spot == False:
return True
else:
row, col = spot
for i in range(1,10):
if is_valid_move(board,i,(row,col)):
board[row][col] = i
screen.fill(white)
drawGrid(9,screen,board)
pygame.display.update()
pygame.time.delay(20)
if solveBoardViz(board):
return True
board[row][col] = 0
screen.fill(white)
drawGrid(9,screen,board)
pygame.display.update()
pygame.time.delay(20)
return False
def drawGrid(grid,screen,board):
'''
parm: int - the grid size (for 9*9 give 9), pygame screen, the sudoku board
it draws lines every 3 blocks, grids, and the text of the sudoku board
'''
blockSize = int(size[0]/grid) # width/no. of grids
for x in range(grid):
if x % 3 == 0 and x != 0:
line_width = 5
else:
line_width = 1
pygame.draw.line(screen,black,(0, x*blockSize),(size[0], x*blockSize), line_width)
pygame.draw.line(screen,black,(x*blockSize,0),(x*blockSize, size[0]), line_width)
for y in range(grid):
rect = pygame.Rect(x*blockSize, y*blockSize,blockSize,blockSize)
pygame.draw.rect(screen,black,rect,1)
if board[y][x]:
text = myfont.render(str(board[y][x]),True,black)
else:
text = myfont.render(" ",True,black)
screen.blit(text, (x*blockSize+20,y*blockSize+9))
def mouseClick(pos,screen):
'''
parm: click position and screen
return: index of grid click, returns False when not click in grid
how: the grind is drawn using width/no. of cols (here: 540/9 which is 60)
so mouse click pos divided by 60 gives us the grid index which was clicked.
'''
x = int(pos[0]//(size[0]/9))
y = int(pos[1]//(size[0]/9))
if x < 9 and y < 9:
#print(pos,board[y][x])
return y,x
return False
size = width, heigh = 540,600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
boxSelected = False # is any box selected in the grid
val = 0
StatusValue = " " # status text
StatusColor = red
board = [
[7,8,0,4,0,0,1,2,0],
[6,0,0,0,7,5,0,0,9],
[0,0,0,6,0,1,0,7,8],
[0,0,7,0,4,0,2,6,0],
[0,0,1,0,5,0,9,3,0],
[9,0,4,0,6,0,0,0,5],
[0,7,0,3,0,0,0,1,2],
[1,2,0,0,0,7,4,0,0],
[0,4,9,2,0,6,0,0,7]
]
boardBackup = copy.deepcopy(board) # makes copy of board, insted of just referance
pygame.font.init()
pygame.init()
myfont = pygame.font.SysFont('Comic Sans MS', 30)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Sudoku")
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
StatusValue = " " # status text
pos = pygame.mouse.get_pos()
index = mouseClick(pos,screen)
if index != False:
y,x = index
boxSelected = True
if event.type == pygame.KEYDOWN:
StatusValue = " " # status text
if event.key == 120: # x key quits app
sys.exit()
if event.key == pygame.K_1:
val = 1
if event.key == pygame.K_2:
val = 2
if event.key == pygame.K_3:
val = 3
if event.key == pygame.K_4:
val = 4
if event.key == pygame.K_5:
val = 5
if event.key == pygame.K_6:
val = 6
if event.key == pygame.K_7:
val = 7
if event.key == pygame.K_8:
val = 8
if event.key == pygame.K_9:
val = 9
if event.key == pygame.K_SPACE: # space key solves full board
board = boardBackup # not at fault
board = copy.deepcopy(boardBackup)
solveBoardViz(board)
boxSelected = False
if isBoardSloved(board):
StatusValue = "Board Solved!"
StatusColor = (0,255,0)
pygame.display.update()
if event.key == pygame.K_LEFT or event.key == 104: # leftkey or h
if boxSelected:
if x == 0: # if can't go left anymore start at right side
x = 8
else:
x-= 1
else:
y = 0
x = 0
boxSelected = True
if event.key == pygame.K_RIGHT or event.key == 108: # rightkey or l
if boxSelected:
if x == 8:
x = 0
else:
x+= 1
else:
y = 0
x = 0
boxSelected = True
if event.key == pygame.K_UP or event.key == 107: # upkey or k
if boxSelected:
if y == 0:
y = 8
else:
y-= 1
else:
y = 0
x = 0
boxSelected = True
if event.key == pygame.K_DOWN or event.key == 106: # downkey or j
if boxSelected:
if y == 8:
y = 0
else:
y += 1
else:
y = 0
x = 0
boxSelected = True
if event.key == 114: # r key to gen new board
boardBackup = make_board()
board = copy.deepcopy(boardBackup)
#boardBackup = board
StatusValue = "New Board!"
StatusColor = (0,0,255)
screen.fill(white)
drawGrid(9,screen,board)
if boxSelected:
#y,x = index
rect = pygame.Rect(x*60,y*60,60,60)
pygame.draw.rect(screen,red,rect,5)
if val:
if board[y][x] == 0:
if is_valid_move(board, val, (y,x)):
board[y][x] = val
if isBoardSloved(board):
StatusValue = "Board Solved!"
StatusColor = (0,255,0)
else:
StatusValue = "WRONG!"
StatusColor = red
val = 0
else:
val = 0
screen.blit(myfont.render(str(StatusValue),True,StatusColor),(0,540))
pygame.display.update()
|
c63823a2c9c773b6964cdd20cae2862826cc5f40 | mamengjuan/beibei | /zuoye/timo.py | 975 | 3.921875 | 4 | """
一个回合制游戏,有两个英雄,分别以两个类进行定义。分别是timo和police。每个英雄都有 hp 属性和 power属性,hp 代表血量,power 代表攻击力
每个英雄都有一个 fight 方法:
my_hp = hp - enemy_power
enemy_final_hp = enemy_hp - my_power
两个 hp 进行对比,血量剩余多的人获胜
每个英雄都一个speak_lines方法
调用speak_lines方法,不同的角色会打印(讲出)不同的台词
timo : 提莫队长正在待命
police: 见识一下法律的子弹
"""
from zuoye.hero import Hero
class Timo(Hero):
hp = 3000
power = 200
name = "timo"
# def fight(self,enemy_hp,enemy_power):
# my_hp = self.hp - enemy_power
# enemy_final_hp = enemy_hp - self.power
# if my_hp > enemy_final_hp:
# print(f"timo赢了")
# elif my_hp < enemy_final_hp:
# print(f"敌人赢了")
# else:
# print("我们打平了")
|
f248af63a79a8f960c7139d6f301b1294bf3f99e | StevenHowlett/pracs | /prac3/broken_score.py | 450 | 3.90625 | 4 | """
CP1404/CP5632 - Practical
Broken program to determine score status
"""
def main():
score = float(input("Enter score: "))
if score < 0 or score > 100:
print("Invalid score")
else:
text = text_for_scores(score)
print (text)
def text_for_scores(score):
if score >= 90:
text = "Excellent"
elif score >= 50:
text = "Passable"
else:
text = "Bad"
return text
main() |
045ad42fadd7542f7932345050395615896b6543 | StevenHowlett/pracs | /prac5/hex_colours.py | 468 | 4.375 | 4 | COLOUR_TO_HEX = {'aliceblue': '#fof8ff', 'antiquewhite': '#faebd7', 'aquamarine': '#7fffd4', 'azure': '#f0ffff',
'beige': '#f5f5dc', 'bisque': 'ffe4c4', 'black': '#000000', 'blue': '#0000ff', 'blueviolet': '8a2be2'}
colour = input("Enter colour: ").lower()
while colour != "":
if colour in COLOUR_TO_HEX:
print(colour, "is", COLOUR_TO_HEX[colour])
else:
print("colour not listed")
colour = input("Enter colour: ").lower()
|
b6a02861984e2eb65b763b35b0ee43aa4fffbada | felixtomlinson/Udacity | /Log Analysis Project/Logs_Analysis_Project.py | 3,435 | 3.890625 | 4 | #!/usr/bin/env python
import psycopg2
DBNAME = "news"
def connect(database_name):
"""Connect to the PostgreSQL database. Returns a database connection."""
try:
db = psycopg2.connect("dbname={}".format(database_name))
c = db.cursor()
return db, c
except psycopg2.Error as e:
print "Unable to connect to database"
sys.exit(1)
def most_popular():
"Connects to an PostgreSQL database and runs a query to return the answer\
to Q1 then print the answer in the right format."
database, command = connect(DBNAME)
command.execute("select articles.title, count(log.path) \
from log \
join articles \
on log.path like '%' || articles.slug \
group by articles.title \
order by count(log.path) desc \
limit 3;")
most_popular_articles = command.fetchall()
for article in most_popular_articles:
print(str(article[0]) + ' - ' + str(article[1]) + ' views\n')
database.close()
def most_popular_author():
"Connects to an PostgreSQL database and runs a query to return the answer\
to Q2 then print the answer in the right format."
database, command = connect(DBNAME)
command.execute("select authors.name, count(log.path) \
from log \
join articles on log.path like '%' || articles.slug \
join authors on articles.author = authors.id \
group by authors.name \
order by count(log.path) desc;")
most_popular_authors = command.fetchall()
for author in most_popular_authors:
print(str(author[0]) + ' - ' + str(author[1]) + ' views\n')
database.close()
def error_days():
"Connects to an PostgreSQL database and runs a query to retrun the answer\
to Q3. It then looks up the number of the month in a dictionary of month \
name and prints it in the right format."
database, command = connect(DBNAME)
command.execute("select date, errorcount*100.00/total as percentage_error \
from (select cast(time as date) as Date, count(time) as Total, \
sum(case when status = '200 OK' then 0 else 1 end) ErrorCount \
from log \
group by cast(time as date)) as errorcalculator \
where errorcount*100/total > 1;")
worst_error_days = command.fetchall()
for days in worst_error_days:
date = str(days[0]).split('-')
day = date[2]
if day[-1] == '1':
day += 'st'
if day[-1] == '2':
day += 'nd'
if day[-1] == '3':
day += 'rd'
else:
day += 'th'
month_dictionary = {'01': 'January', '02': 'February', '03': 'March',
'04': 'April', '05': 'May', '06': 'June',
'07': 'July', '08': 'August', '09': 'September',
'10': 'October', '11': 'November',
'12': 'December'}
month = date[1]
month = month_dictionary[month]
year = date[0]
properly_formatted_date = month + ' ' + day + ', ' + year
percentage_error = str(days[1])[:3] + "%" + " errors"
print(properly_formatted_date + ' - ' + percentage_error + '\n')
database.close()
print('1. What are the most popular three articles of all time?\n\n')
most_popular()
print('\n2. Who are the most popular article authors of all time?\n\n')
most_popular_author()
print('\n3. On which days did more than 1% of requests lead to errors?\n\n')
error_days()
|
93bd0eeac2c81ab4af6c1e336eb0ac0a46825b7e | petersheck/SimplePython | /Variables.py | 634 | 4.03125 | 4 | fruit = 'apple'
fruit = "apple"
frint = 'orange'
sentence = 'She said, "This is a great tasting apple!"'
sentence = "That's a great tasting apple!"
a = 'apple'[0]
e = 'apple'[4]
fruit = "apple"
first_character = fruit[0]
fruit_len = len(fruit)
print(fruit_len)
print(len(fruit))
fruit = "Apple"
print(fruit.lower())
print(fruit.upper())
version = 3
print("I love Python " + str(version) + ".")
print("I {} Python.".format("love"))
print("{} {} {}.".format("I", "love", "Python"))
print("I {0} {1}. {1} {0}s me.".format("love", "Python"))
fruit = input("Enter a name of a fruit: ")
print("{} is a lovely fruit.".format(fruit))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.