blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
cd64a6e20458d824b471fa58bc96874f8e8cafe0 | IvanWoo/coding-interview-questions | /puzzles/capacity_to_ship_packages_within_d_days.py | 2,028 | 4.3125 | 4 | # https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/
"""
A conveyor belt has packages that must be shipped from one port to another within days days.
The i-th package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.
Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.
Example 1:
Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5
Output: 15
Explanation:
A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:
1st day: 1, 2, 3, 4, 5
2nd day: 6, 7
3rd day: 8
4th day: 9
5th day: 10
Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.
Example 2:
Input: weights = [3,2,2,4,1,4], days = 3
Output: 6
Explanation:
A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:
1st day: 3, 2
2nd day: 2, 4
3rd day: 1, 4
Example 3:
Input: weights = [1,2,3,1,1], days = 4
Output: 3
Explanation:
1st day: 1
2nd day: 2
3rd day: 3
4th day: 1, 1
Constraints:
1 <= days <= weights.length <= 50000
1 <= weights[i] <= 500
"""
def ship_within_days(weights: list[int], days: int) -> int:
def count_ds(weights, c):
i = 0
ans = 1
left = c
while i < len(weights):
if weights[i] > left:
ans += 1
left = c
continue
else:
left -= weights[i]
i += 1
return ans
lo, hi = max(weights), sum(weights)
while lo <= hi:
mid = (lo + hi) // 2
c = count_ds(weights, mid)
if c > days:
lo = mid + 1
elif c < days:
hi = mid - 1
elif c == days:
hi = mid - 1
return lo
|
d94f9c45aa6ea2140f01f0ceb835947a796a0c86 | yunai39/turbo-happiness | /bin/charriot.py | 1,525 | 3.609375 | 4 | from motor import Motor
"""
Class chariot
Un chariot est composé de deux moteur
Ces deux moteur permettent d'avance, de reculer, de tourné etc...
"""
class Chariot:
def __init__(self, rightMotor: Motor, leftMotor: Motor):
self.rightMotor = rightMotor
self.leftMotor = leftMotor
self.rightMotor.initMotor()
self.leftMotor.initMotor()
self.isGoingForward = True
self.isStarted = False
"""
Démarrer le charriot
"""
def start(self):
if not self.isStarted:
self.rightMotor.start()
self.leftMotor.start()
"""
Arrêter le charriot
"""
def stop(self):
if self.isStarted:
self.rightMotor.stop()
self.leftMotor.stop()
"""
Accélère le charriot
"""
def goFaster(self):
self.rightMotor.speedUp()
self.leftMotor.speedUp()
"""
Ralenti le charriot
"""
def goSlower(self):
self.rightMotor.slowDown()
self.leftMotor.slowDown()
"""
Tourne à droite
"""
def turnRight(self):
self.rightMotor.slowDown()
self.leftMotor.speedUp()
"""
Tourne à gauche
"""
def turnLeft(self):
self.leftMotor.slowDown()
self.rightMotor.speedUp()
"""
Inverse les moteurs
"""
def switchDirection(self):
self.isGoingForward = not self.isGoingForward
self.rightMotor.reverse()
self.leftMotor.reverse()
|
0793ae185fa90a80092cc52cbb0fccb8f47ca35d | appratt/python | /ex16.py | 1,965 | 4.53125 | 5 | # Exercise 16
# this is a very simple text editor to practice file manupulation commands
# import the argv module from the sys module
from sys import argv
# unpacks the argv into script and filename
# 'script' indicates the program itself. 'filename' is a string that here takes the name of an existing .txt file or creates one if it does not exist.
# the variables after 'script' must be spplied AT THE COMMAND LINE
script, filename = argv
# the variable here is the name of the file supplied at the command line
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
# this pauses the program to take input from the user. really, it doesn't matter what you put in here--it's just giving you the chance to proceed by hitting enter or terminate the program with ^C.
raw_input("?")
# open takes that parameters (file, mode); here 'w' mode is for writing. target is just the target file.
print "Opening the file..."
target = open(filename, 'a')
# this truncates or erases the file.
# print "Truncating the file. Goodbye!"
# target.truncate()
print "Now I'm going to ask you for three lines."
# take three piees of raw input and assign each to a variable. the paramater for 'raw_input' here is the promt that will be displayed.
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
# again, 'target' is the object holding the file that got opened above. this writes the value of each 'line' variable into the contents of the file, with a "\n" (line break) written in between each.
# target.write(line1)
# target.write("\n")
# target.write(line2)
# target.write("\n")
# target.write(line3)
# target.write("\n")
# This does the same thing as above, but is more terse.
lines = line1 + "\n" + line2 + "\n" + line3 + "\n"
target.write(lines)
# obvi.
print "And finally, we close it."
target.close() |
499cf4a792f58dce8e2669decc6433f1dafdb074 | WwwYiNan/Test100 | /Example/Example10.py | 292 | 3.625 | 4 | vec1 = [2, 4, -6]
vec2 = [1, -3, -7]
print([x*y for x in vec1 for y in vec2])
print([x+y for x in vec1 for y in vec2])
print(x**2 for x in vec1)
print(x*2 for x in vec2)
print([vec1[i]*vec2[i] for i in range(len(vec1))])
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
print(str(dict))
|
364139a1c7c0a4a56982e21f53f2d09d41a5356a | sbtries/Class_Polar_Bear | /Code/James/Python/rps_version_2.py | 1,133 | 3.9375 | 4 | '''
___________________________________________________________________________
Project: Full Stack Evening Boot Camp - Python Lab (05 Rock Paper Scissors)
Version: 1.0
Author: James Thornton
Email: James.ed.thornton@gmail.com
Date: 27 SEP 2021
___________________________________________________________________________
'''
import random
options = ["rock", "paper", "scissors"]
while True:
comp = random.choice(options)
user = ""
while user not in options:
user = input("Pick 'rock', 'paper', or 'scissors': ").lower()
if user == "exit":
break
if user == "exit":
break
if user == comp:
print("You tied!")
elif user == "rock":
if comp == "scissors":
print("You win!")
elif comp == "paper":
print("You lose!")
elif user == "paper":
if comp == "rock":
print("You win!")
elif comp == "scissors":
print("You lose!")
elif user == "scissors":
if comp == "paper":
print("You win!")
elif comp == "rock":
print("You lose!")
user2 = input("Would you like to play again: ").lower()
if user2 == "yes":
continue
if user2 == "no":
quit() |
42a52e0d3c69bbcdf002301575cd1676560d5f41 | tommidavie/Practise-Python | /lists.py | 3,383 | 4 | 4 | import random
# Just for the shuffle
def get_integer(m):
my_integer = int(input(m))
return my_integer
def get_string(m):
my_string = input(m)
return my_string
def print_at_index(L):
my_index = get_integer("Please choose index -> ")
print(L[my_index])
def print_list(L):
for x in L:
print(x)
def print_list_indexes(L):
for i in range (0, len(L)):
print("{} : {}".format(i, L[i]))
def add_item(L):
new_item = get_string("Please enter new item: ")
L.append(new_item)
def change_value(L):
print_list_indexes(L)
index_num = get_integer("Please choose the index number: ")
new_value = get_string("Please enter new value: ")
# we now have all the values we need
# temporarily hold old value for print out
old_value = L[index_num]
# update value
L[index_num]=new_value
# confirmation message
output = "The old value of {} has now been changed to {}".format(old_value, L[index_num])
print(output)
def remove_item(L):
item = get_string("What do you want to remove: ")
if item in L:
L.remove(item)
output = "{} has been removed from the list.".format(item)
print(output)
else:
output = "{} could not be found, so must have not been in the list".format(item)
print(output)
def sort_list(L):
L.sort()
def shuffle_list(L):
random.shuffle(L)
def find_item(L):
item = get_string("What do you want to find? : ")
if item in L:
index_num = L.index(item)
output = "{} has been found at an index number of {}".format(L[index_num], index_num)
print(output)
else:
print("{} cannot be found in the list".format(item))
print("."*100)
def menu():
my_list_one=["Tommi", "Grace", "Paige", "Rebecca", "Nia"]
my_list_two=["Mango", "Apple", "Pear", "Orange", "Banana"]
my_list = my_list_two
my_menu = '''
A: Print the list
B: Print the list with indices
C: Add item to the list
D: Print at index number
E: Choose list one
F: Choose list two
G: Change a Value
H: Remove an Item
I: Sort a list
J: Shuffle a list
L: Find an item
Q: Quit
'''
print(id(my_list_one))
print(id(my_list_two))
print(id(my_list))
run = True
while run == True:
print(my_menu)
ask = get_string("Please select an option: ")
print("."*100)
if ask == "A":
print_list(my_list)
elif ask == "B":
print_list_indexes(my_list)
elif ask == "C":
add_item(my_list)
elif ask == "D":
print_at_index(my_list)
elif ask == "E":
my_list = my_list_one
print("My list one is now selected")
elif ask == "F":
my_list = my_list_two
print("My list two is now selected")
elif ask == "G":
change_value(my_list)
elif ask == "H":
remove_item(my_list)
elif ask == "I":
sort_list(my_list)
elif ask == "J":
shuffle_list(my_list)
elif ask == "L":
find_item(my_list)
elif ask == "Q":
print("Thank you for playing")
run = False
menu()
#print_at_index(my_list)
#print_list(my_list)
#print_list_indexes(my_list)
#add_item(my_list)
|
24e93e8e55df95a3636cb4cec1f3150e2e2ee5b9 | MAPLE-Robot-Subgoaling/IPT | /data/HW4/hw4_438.py | 437 | 4.21875 | 4 | def main():
height = int(input("Please enter the starting theight of the hailstone: "))
print("Hail is currently at height", height)
while height != 1:
if height%2 != 0:
height = (height*3)+1
print("Hail is currently at height", height)
if height%2 == 0:
height = (height//2)
print("Hail is currently at height", height)
print("Hail stopped at height 1")
main()
|
ba8c51bacf7b0656198099214566070e8414ce6e | VaibhavBiturwar/Image-processing | /demo.py | 838 | 3.703125 | 4 | import cv2
# returns a 3D array for colored image ->second parameter 1
# 2D array for grayscale image -. second parameter 0
# Numpy_array imread( File_location , 0-1)
# img = cv2.imread("C://Users//lenovo//Desktop//OpenCV//image.png", 1)
# print(img)
# print(type(img))
# TO GET THE SIZE OF THE IMAGE
# print(img.shape)
# TO DISPLAY THE IMAGE
# imshow( name_to_display , numpy_array_of_image)
# waitKey() -> to wait for any keypress
# waitKey(2000) -> to wait for specific time
# destroyAllWindows() to distroy all Windows
# cv2.imshow("Material" , img)
# cv2.waitKey(2000)
# cv2.destroyAllWindows() #par farak nahi padta
# TO RESIZE IMAGE
# resize = cv2.resize(img , (int(img.shape[1]/2),int(img.shape[0]/2)))
# cv2.imshow("Material Resized" , resize)
# cv2.waitKey(2000)
# cv2.destroyAllWindows() #par farak nahi padta
|
511d03e7316a95f2e2af9eac9364df5004c67b0c | lientdang/Cheldarr | /familytree/familytree.py | 1,143 | 4.03125 | 4 | class Familytree:
def __init__(self, first, last, age, gender, birth_month, birth_day, birth_year, mother_first, mother_last, father_first, father_last, is_grandkid):
self.first = first
self.last = last
self.name = 'Name: ' + first + ' ' + last
self.age = age
self.gender = 'Gender: ' + gender
self.birth_month = birth_month
self.birth_day = birth_day
self.birth_year = birth_year
self.mother_first = mother_first
self.mother_last = mother_last
self.father_first = father_first
self.father_last = father_last
self.is_grandkid = 'Grand kid: ' + ' ' + is_grandkid
def name(self):
return 'Name: {} {}'.format(self.first, self.last)
def birthday(self):
return 'Birthday: {} {}, {}'.format(self.birth_month, self.birth_day, self.birth_year)
def mother_name(self):
return 'Mother\'s Name: {} {}'.format(self.mother_first, self.mother_last)
def father_name(self):
return 'Father\'s Name: {} {}'.format(self.father_first, self.father_last)
def child_info(self):
print("chelsea") |
2fe8af8c093e88b7756406121d12da6e1791b836 | Shad87/python-programming | /UNIT-1/list.py | 2,114 | 4.25 | 4 | '''
#declare an empty list
classmates = []
#add items to lsit
classmates.append("Sue")
classmates.append("Shad")
classmates.append("Aaron")
classmates.append("Chinonso")
classmates.append("Eva")
classmates.append("Jeremy")
classmates.append("Dan")
classmates.append("Mayank")
classmates.append("Eva")
classmates.append("Julain")
classmates.append("Gus")
print(classmates)
#access an itme at a specific pposition
print(classmates[0])
print(classmates[5])
#get the size of the list
print(len(classmates))
#remove an item from the end of teh lsit
classmates.pop()
print(classmates)
#insert at a specific position (0,-infinity)
classmates.insert(0, "Gus")
print(classmates)
#removing an item from a list
classmates.remove("Shad")
print(classmates)
#edit an item in the list
classmates[1] = "Sue Work"
print(classmates)
#iterate over a list
for classmate in classmates:
if(classmates == "Gus"):
print("Great guys")
#edit elements while iterating
for index, classmate in enumerate(classmates):
classmates[index] += " - Python Student"
print(classmates)
for index, classmate in enumerate(classmates):
classmates[index] = ''
print(classmates)
#changing the entire index to Upper Case
for index, classmate in enumerate(classmates):
classmates[index] = classmates[index].upper()
classmates[index] = classmate.upper()
print(classmates)
'''
#create a list of all the marvel movies fromiron man to end game
marvel_movies = ['Captain America: The First Avenger','Captain Marvel','Iron Man','Iron Man 2','The Incredible Hulk','Thor','Avengers','Iron Man 3','Thor: The Dark World','Captain America: The Winter Soldier','Guardians of the Galaxy','Guardians of the Galaxy Vol. 2','Avengers: Age of Ultron','Ant-Man','Captain America: Civil War','Spider-Man: Homecoming','Doctor Strange','Black Panther','Thor: Ragnarok','Ant-Man and The Wasp','Avengers Infinity War','Avengers: Endgame']
movies_with_the = []
for movie in marvel_movies:
if 'the ' in movie.lower():
#print(movie)
movies_with_the.append(movie)
# print(marvel_movies)
print(movies_with_the)
|
e74115764dbcd0b592982ca6565fdd1259c80b51 | teyrana/py_opt_talk | /_6_CPython_cffi/profile.py | 1,796 | 3.59375 | 4 | #!/usr/bin/env python3
import time
import random
import _bst.lib as bst
def create_tree():
"""This method creates a fully-populated binary-search-tree of depth 4, on the numbers: [0, 30]"""
#
# ___________________15_____________________
# / \
# ______7_______ __________23_________
# / \ / \
# __3__ ___11___ ____19___ ____27___
# / \ / \ / \ / \
# 1 5 9 _13 _17 _21 _25 _29
# / \ / \ / \ / \ / \ / \ / \ / \
# 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30
#
# If we add the above values in the correct order, the tree is balanced, for free.
init_values = [15,
7, 23,
3, 11, 19, 27,
1, 5, 9, 13, 17, 21, 25, 29,
0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]
root = bst.node_new(15)
for value in init_values:
bst.node_add(root, value)
return root
def run_time_trial(tree, maxvalue, ncount = 100):
start = time.process_time()
# do the thing
for _ in range(ncount):
search_value = int(random.random() * maxvalue)
_ = bst.node_search(tree, search_value)
end = time.process_time()
trial_time = end - start
print(f"# Ran {ncount} trials over {trial_time} seconds.\n")
if __name__ == '__main__':
tree = create_tree()
run_time_trial(tree, 30, ncount=1000000)
|
e5a4be87f737a773e6168e7512e24d3cb11e88d0 | SuperSpy20/Python-Projects | /midpoint.py | 611 | 3.96875 | 4 | try:
c_1 = input('What is the coordinate of the first point?\n').split(',')
c_2 = input('What is the coordinate of the second point?\n').split(',')
p = list(map(float, c_1))
q = list(map(float, c_2))
except:
print('\n\nYou must input a correct coordinate!')
exit()
def midpoint(p, q):
x1 = p[0]
y1 = p[1]
x2 = q[0]
y2 = q[1]
x = ((x1) + (x2))/2
y = ((y1) + (y2))/2
xy_list = []
xy_list.append(x)
xy_list.append(y)
return xy_list
midpoint_calculation = midpoint(p, q)
print('\nMidpoint: %s'%midpoint_calculation) |
ebed6082f15d1407b1f687d627d5107626c2838a | mishrakeshav/Competitive-Programming | /binarysearch.io/tree_sum.py | 433 | 3.515625 | 4 | # class Tree:
# def __init__(self, val, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def solve(self, root):
# Write your code here
def cal(root):
if root is None:
return 0
else:
return root.val + cal(root.left) + cal(root.right)
return cal(root)
|
bcbf9311070baad1485be2b405c7f31a18ad4077 | joker2009/Python_learn | /0409.py | 624 | 3.625 | 4 | __author__ = 'Joker'
"""请定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程:
ax2 + bx + c = 0
的两个解。"""
def quadratic(a, b, c):
if not isinstance(a, (int, float)):
raise TypeError('参数类型错误')
if not isinstance(b, (int, float)):
raise TypeError('参数类型错误')
if not isinstance(c, (int, float)):
raise TypeError('参数类型错误')
A = b * b - 4 * a * c
if a == 0:
if b == 0:
if c == 0:
return '方程根为全体实数'
else:
return '方程无根'
|
9b72b95da974d53657351e687c6146a97ef1fea2 | IliasOu/programming1 | /les 4/Input and Output.py | 234 | 3.578125 | 4 | uurloon = input('Hoeveel verdien je per uur: ')
werkuren = input('Hoeveel uur heb je gewerkt: ')
salaris = float(uurloon) * float(werkuren)
overzicht = str(uurloon) + ' uur werken levert ' + str(salaris) + ' Euro op.'
print(overzicht) |
37c2f2dd81357d86813fc06f9baf9a682670b814 | 2018-B-GR1-Python/O-a-Salazar-Christian-David | /01_Python.py | 1,230 | 4 | 4 | #!/usr/bin/env python
print("hola mundo")
edad: int = 20
sueldo = 1.02
print(edad + int(sueldo))
nombre = "Christian"
apellido = "Oña"
apellido_materno = """Salazar"""
print(nombre == apellido)
print(apellido == apellido_materno)
print(apellido_materno)
print(int(True))
print(int(False))
print(str(True))
print(str(False))
print("christian oña".capitalize())
a = "christian oña".split(" ")
print(a[0].capitalize() + " " + a[1].capitalize())
print("Christian".isalpha())
print("Christian10".isalpha())
print("10".isnumeric())
print("Christian10".isnumeric())
print("10".isalnum())
print("Vicente10".isalnum())
##print(int("hola"))
print("Mi nombre es {0} {1}".format(a[0].capitalize(),a[1].capitalize()) )
print(f"Mi nombre es {a[0].capitalize()}")
no_existe = None
print(no_existe)
print("christian oña".capitalize())
a = "christian oña".split(" ")
print(a[0].capitalize() + " " + a[1].capitalize())
print("Christian".isalpha())
print("Christian10".isalpha())
print("10".isnumeric())
print("Christian10".isnumeric())
print("10".isalnum())
print("Vicente10".isalnum())
##print(int("hola"))
print("Mi nombre es {0} {1}".format(a[0].capitalize(),a[1].capitalize()) )
print(f"Mi nombre es {a[0].capitalize()}")
no_existe = None
print(no_existe)
|
05fd6cb93113604d6762829193a3db49517d5302 | seanmenezes/python_projects | /basic/classes/Account.py | 987 | 3.859375 | 4 | class Account:
def __init__(self,title = None, balance=0):
self.__title = title
self.__balance = balance
def getBalance(self):
return self.__balance
def deposit(self,amount):
self.__balance += amount
def withdrawal(self,amount):
self.__balance -= amount
class SavingsAccount(Account):
def __init__(self, title=None, balance=0,interest_rate=0.0):
super().__init__(title=title, balance=balance)
self.__interest_rate = interest_rate
def interestAmount(self):
return (self.__interest_rate * self.getBalance())/100
account1 = Account("Mark",5000)
account1.deposit(8000)
account1.withdrawal(3000)
print("\n balance of account 1 =>",account1.getBalance())
account2 = SavingsAccount("Mark",5000,5)
account2.deposit(10000)
account2.withdrawal(2500)
print("\n balance of account 2 => ",account2.getBalance())
print("\n Interest Amount for account 2 => ",account2.interestAmount())
|
c50d9ba3543be51bd6da22321dad6ce830f86eb6 | ahmedsalah52/Self_Driving_Car_Course | /Python/q15.py | 149 | 4.125 | 4 | file_name = input("please enter the file name \n")
file = open(file_name,'r')
for word in file.read().split():
print(word.upper())
file.close() |
7f60151fd1f509949c3e925abe92e9e17c425059 | shobhitmishra/CodingProblems | /LeetCode/Session3/PathSumIII.py | 1,007 | 3.625 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
if not root:
return 0
return self.pathSumHelper(root, 0, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum)
def pathSumHelper(self, root, currentSum, targetSum):
if not root:
return 0
currentSum += root.val
leftCount = self.pathSumHelper(root.left, currentSum, targetSum)
rightCount = self.pathSumHelper(root.right, currentSum, targetSum)
if currentSum == targetSum:
return 1 + leftCount + rightCount
return leftCount + rightCount
root = TreeNode(1)
root.right = TreeNode(2)
root.right.right = TreeNode(3)
root.right.right.right = TreeNode(4)
root.right.right.right.right = TreeNode(5)
ob = Solution()
print(ob.pathSum(root, 3)) |
9388143b9dff7b19f45f4b3b7046af13b623067d | forthing/leetcode-share | /python/062 Unique Paths.py | 878 | 4.125 | 4 | '''
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
'''
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
dp = [[1 for __ in range(n)] for __ in range(m)]
for i in range(1, n):
for j in range(1, m):
dp[j][i] = dp[j - 1][i] + dp[j][i - 1]
return dp[m - 1][n - 1]
if __name__ == "__main__":
assert Solution().uniquePaths(3, 7) == 28 |
dfd24c5c0858b9083324bffa69c131a92d186f21 | nikostsio/Project_Euler | /euler57.py | 460 | 3.625 | 4 | # I'm gonna calculate the square root of 2
# Pretty exciting!!
def main():
lst = [(3,2), (7, 5)]
counter = 0
for i in range(1000):
# I noticed a pattern in the first few fractions the problem gave, so I tried them and they seem to work!
denom = lst[-1][1]+lst[-1][0]
numer = lst[-1][1]+denom
if len(str(numer))>len(str(denom)):
counter+=1
lst.append((numer,denom))
print(counter)
print(lst[-1][0]/lst[-1][1])
if __name__=='__main__':
main() |
06843b90384807e59230b97371a52e336f59e4bb | AdamMatheus/python-project | /python7/lambda_builtin_map.py | 541 | 3.875 | 4 | # letter1=["o",'s','t','t']
# letter2=['n','i','e','w']
# letter3=['e','x','n','o']
# num=map(lambda x,y,z:x+y+z,letter1,letter2,letter3)
# print(list(num))
# nums1=[9,6,7,4]
# nums2=[3,6,5,8]
# ort=map(lambda x,y:(x+y)/2,nums1,nums2)
# print(list(ort))
# kelime=["ali veli deli","mehmet aganin kuzeni","cemilin-bacisi"]
# #print(list(map(len,kelime)))
# print(list(map(sorted,kelime)))
# word1=["you",'much',"hard"]
# word2=["i","you","he"]
# word3=["love",'ate',"works"]
# print(list(map(lambda x,y,z:y+" "+z+" "+x,word1,word2,word3))) |
7a80bc4c61b30903e69c7e3b2f10e78d3362b9d4 | sanketgadiya/PYTHON-ETHANS | /solutions/hotel.py | 937 | 3.890625 | 4 | def print_header():
print "#"*30+"\n MENU \n"+ "#"*30
def print_menu_item(item,price,total_gap=30):
total_char = len(item) + len(str(price)) + 2
h_needed = total_gap - total_char
print item + " " +"-"*h_needed + " " + str(price)
def print_menu(menu_dict=''):
print_header()
for item in menu_dict:
print_menu_item(item,menu_dict[item])
def main():
dict1 = {'Rice':40,'Roti':13,'Curry':450,'Papad':45}
print_menu(dict1)
all_choice = []
print " "
while True:
choice = raw_input("Enter the item to order else 'D' for done :")
if choice == 'D':
break
elif choice not in dict1:
print "Not available in menu"
print " "
else:
all_choice.append(choice)
bill = 0
for c in all_choice:
if 'Roti' in all_choice and 'Curry' in all_choice:
bill = bill + dict1[c]
else:
print "\n \n Your order is incomplete \n \n"
return
print "\n \n Total Bill : %s" %bill
main()
|
e7bda1c21c77f70c03b2012f323847af03ea4101 | mveselov/CodeWars | /katas/kyu_6/triple_trouble.py | 329 | 3.75 | 4 | def chunks(string, size):
result = set()
for a in xrange(len(string) - (size - 1)):
current = string[a:a + size]
if len(set(current)) == 1:
result.add(current[0])
return result
def triple_double(num1, num2):
return 1 if chunks(str(num1), 3).intersection(chunks(str(num2), 2)) else 0
|
c3ce4f991aa7f4a0ff59188126e4feff753df4e3 | gus07ven/CCIPrac | /Leet303_2.py | 485 | 3.640625 | 4 | from typing import List
class Leet303_2:
def __init__(self, nums: List):
self.sums = [0] * (len(nums) + 1)
for i in range(0, len(nums)):
self.sums[i + 1] = self.sums[i] + nums[i]
def sum_range(self, i: int, j: int) -> int:
return self.sums[j + 1] - self.sums[i]
if __name__ == "__main__":
nums = [-2, 0, 3, -5, 2, -1]
le = Leet303_2(nums)
print(le.sum_range(0, 2))
print(le.sum_range(2, 5))
print(le.sum_range(0, 5)) |
44bac80f20ccc0a2ca05a25855032040716a9c88 | kriti-ixix/python-ms | /python/basic list.py | 1,581 | 4.03125 | 4 | '''
stdNames = ['abc', 'xyz', 'pqr']
print(stdNames)
# adding a element in list
stdNames.append('fgh')
print(stdNames)
# Acessing a element
print(stdNames[2])
# Searching a element
if 'x' in stdNames:
print('Fount it')
else:
print('Not found')
# CHanging a value
stdNames[1] = 456
print(stdNames)
# inseting a value
stdNames.insert(3, 'std')
print(stdNames)
#Removing a element
stdNames.remove('abc')
print(stdNames)
#task for now: print your list in reverse order
# append 6 different items in list using for loop
# task 1:
print(stdNames[::-1])
#task2
list = []
for i in range(6):
list.append(i)
print(list)
list2 = []
for i in range(6):
user = input()
list2.append(user)
print(list2)
'''
# LIst comprehension
myList = []
for i in range(1,11):
if i%2==0:
myList.append(i)
print(myList)
myList1 = [x for x in range(1,11) if i%2==0]
myList1
#Make a list of any elemets(eg: fruits) and store only those elemets in
# new list which consist "a" letter in it.
#Hint: 1. Make a list in which you have to use first for loop and then use if
# statement to check "a" letter in it.
#Saturday task
user = input('Enter your name: ')
print(user +" "+ "Welcome here!!")
list = []
n = int(input('Please enter number of students: '))
for i in range(n):
name = input("Enter student name: ")
Age = input('Enter student age: ')
list.append("student name is "+ " " + name + 'and age is '+ " " + Age)
print(list)
|
46573216a99963b48326ebf474be6ed4182591ca | ManaliKulkarni30/MachineLearning_CaseStudues | /Iris3.py | 1,422 | 3.53125 | 4 | ###########################################################################
#
#Author:Manali Milind Kulkarni
#Date:28th March 2021
#About: Applying Decision Tree Algorithm on Iris Dataset
#
###########################################################################
#Required imports
from sklearn.datasets import load_iris
import numpy as np
from sklearn import tree
##########################################################################
#Entry Point Function
def main():
#Loading Dataset
dataset = load_iris()
print("Features of Dataset: ")
print(dataset.feature_names)
print("Target of Dataset: ")
print(dataset.target_names)
#print("Iris Dataset is: ")
#for iCnt in range(len(dataset.target)):
#print("ID : %d Features:%s Lable: %s"%(iCnt,dataset.data[iCnt],dataset.target[iCnt]))
index = [1,51,101]
test_target = dataset.target[index]
test_feature = dataset.data[index]
train_target = np.delete(dataset.target,index)
train_feature = np.delete(dataset.data,index,axis = 0)
obj = tree.DecisionTreeClassifier()
obj.fit(train_feature,train_target)
result = obj.predict(test_feature)
print("Result predicted by ML: ",result)
print("Result expected: ",test_target)
##############################################################################
#Starter
if __name__ == '__main__':
main()
|
2edeb82edf25a00fe45fd3f87bc31863e091c3a9 | yuryanliang/Python-Leetcoode | /recursion/24 swap-nodes-in-pairs.py | 1,388 | 4.0625 | 4 | """
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __repr__(self):
if self:
return "{} -> {}".format(self.val, self.next)
class Sol:
def swap(self,head):
if head is None or head.next is None: # 终止条件
return head
rev_rest = self.swap(head.next.next) # 1:head-> 2:node2 -> None;
node2 = head.next
node2.next = head
head.next = rev_rest
return node2
class Solution:
# @param a ListNode
# @return a ListNode
def swapPairs(self, head):
dummy = ListNode(-1)
dummy.next = head
cur = dummy
while cur.next and cur.next.next:
node1, node2, node3 = cur.next, cur.next.next, cur.next.next.next
cur.next = node2
node2.next = node1
node1.next = node3
cur = cur.next.next
return dummy.next
if __name__ == "__main__":
head = ListNode(1)
head.next, head.next.next, head.next.next.next = ListNode(2), ListNode(3), ListNode(4)
# print(Solution().swapPairs(head))
print(Sol().swap(head))
|
a7c1c2fea1f7f8372d3ab33d8a00961c77d28ae8 | jerrylance/LeetCode | /58.Length of Last Word/58.Length of Last Word.py | 892 | 3.671875 | 4 | # LeetCode Solution
# Zeyu Liu
# 2019.1.30
# 58.Length of Last Word
from typing import List
# method 1 remove 和while 应用
class Solution:
def lengthOfLastWord(self, s: str) -> int:
if s:
last = s.split(" ")
while '' in last:#循环去除空值
last.remove('')
if last == []:
return 0
else:
return len(last[-1])
else:
return 0
# transfer method
solve = Solution()
print(solve.lengthOfLastWord(" a "))
# method 2 方法1的优化,strip可以去除首和尾的空白字符.
class Solution:
def lengthOfLastWord(self, s: str) -> int:
if s:
s = s.strip()
last = s.split(" ")
return len(last[-1])# 注意这里如果返回的是空值,则长度len(last[-1]) = 0
else:
return 0
# transfer method
solve = Solution()
print(solve.lengthOfLastWord(" "))
|
89cf5519d27a376dbefd6a46c12c9298b3a8fdea | lavisha752/Python- | /Stock of a pharmacy.py | 1,145 | 4.375 | 4 | # creating a list with items
stock=['paracetamol','bandage','antiseptic wipes','cough syrup','antibiotics']
print("Current Stock")
# User input and to choose the option
option = input("1. Add an item to the stock pharmacy.\n\
2. Remove item from stock.\n\
3. Insert item at a specific location.\n\
Please enter an option:")
# check for the statements in different choices
# Adding items
if option=="1":
item=input("Enter the item you want to add in stock :")
stock.append(item)
print(stock)
# Removing items
elif option=="2":
item = input("Enter the item you want to remove from stock :")
stock.remove(item)
print(stock)
# Inserting number at specific index
elif option == "3":
pos_index = int(input("In which position would you like to add to the stock :"))
item = input("Enter the item you want to insert in stock :")
# An if condition to check for the correct position
if pos_index < len(stock):
stock.insert(pos_index,item)
print(stock)
else:
print("Invalid Position")
# Message for choosing the wrong choice
else:
print("Invalid choice")
|
1de6b4d19f48050128625ac2fdd0b4841c3ad477 | wmackowiak/Zadania | /Zajecia05/zad07.py | 1,030 | 3.78125 | 4 | # 8▹ Napisz program, który będzie sprawdzał, czy nasz samochód kwalifikuje się do zarejestrowania jako zabytek.
# Program zacznie ze stworzonym słownikiem o trzech kluczach:
# marka (str)
# model (str)
# rocznik (int)
# Wypisze ten słownik na ekran (bez żadnego formatowania)
# Sprawdzi, czy samochód ma minimum 25 lat. Jeśli tak, wypisze komunikat:
# “Gratulacje! Twój samochód (tutaj_marka) może być zarejestrowany jako zabytek.”
# Jeśli nie spełnia powyższego warunku, wypisze komunikat:
# “Twój samochód (tutaj_marka) jest jeszcze zbyt młody.”
# Gdy program będzie poprawnie działał, pozmieniaj wartości słownika (ale nie klucze!), aby zobaczyć, czy progam
# również zmienia swoje zachowanie.
slownik = {'marka': 'Ford','model': 'T','rocznik': 1920}
# marka = str(input("Podaj markę samochodu: "))
# model = str(input("Podaj model samochodu: "))
# rocznik = int(input("Podaj rok produkcji: "))
print(slownik)
|
f3dea2bd28958d8b7ff9294b45da1bac22b166fb | Yadynesh-Nandane/YD-dcoder | /Symmetric_Swap.py | 345 | 3.796875 | 4 | """
Author:Yadynesh-Nandane
Program for Symmetric Swap
"""
#Accepting Input
N = int(input())
s = input()
d = s.split(' ')
#Swapping of numbers having symmetric positions
#i.e Swaping 1st position number from top and 1st position number from bottom of the list
for i in range(0,N//2):
d[i],d[N-(i+1)] = d[N-(i+1)],d[i]
print(*d,sep=' ')
|
d3ff306d26516b4e18348d054b09a305a924b972 | bibotai/LeetCodeExercise | /25_Longest_Substring_Without_Repeating_Characters/25_Longest_Substring_Without_Repeating_Characters.py | 1,230 | 3.859375 | 4 | # coding:utf-8
"""
问题链接:
https://leetcode.com/problems/longest-substring-without-repeating-characters/description/
问题描述:
找出一个字符串中,连续的,且不包含重复字符的,最长的字符串的长度
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3.
思路:
开辟一个数组,存放字符和字符的位置,然后遍历字符串中的所有字符。
如果字符不在新数组中,将这个字符和位置加入数组
如果字符在新的数组中,长度从这个字符的上一个位置开始计算。
长度的计算为从当前位置到上一个重复字符的位置,并记录下,留着做比较
"""
def lengthOfLongestSubstring(s):
start = maxLength = 0
usedChar = {}
for i in range(len(s)):
if s[i] in usedChar and start <= usedChar[s[i]]:
start = usedChar[s[i]] + 1#开始的位置
else:
maxLength = max(maxLength, i - start + 1)#计算最大的长度
usedChar[s[i]] = i
return maxLength
if __name__ == '__main__':
a = "abcbcdefgg"
print lengthOfLongestSubstring(a) |
ce75d6fe7e900b47c78ea504241243928e5be28f | Canyon1997/PythonComputerShopping | /BuyComputer.py | 1,270 | 4 | 4 | available_parts = ["Computer",
"Monitor",
"Keyboard",
"Mouse",
"Mouse Mat",
"HDMI Cable",
"Graphics Card",
"CPU",
"Headset",
"Ram",
"Fans",
"Mother Board",
"SSD",
"Computer Case",
"Power Supply"
]
valid_choices = []
for i in range(1, len(available_parts) + 1):
valid_choices.append(str(i))
choice = "-"
computer_parts = []
while choice != "0":
print("Please add options from the list below:")
for number, item in enumerate(available_parts):
print("{0}: {1}".format(number + 1, item))
print("0: Exit")
choice = input()
if not choice.isnumeric():
while not choice.isnumeric():
print("Invalid Choice, try again")
choice = input()
if choice in valid_choices:
print("Adding {}".format(available_parts[int(choice) - 1]))
computer_parts.append(available_parts[int(choice) - 1])
elif choice == "0":
print("Exiting")
else:
print("Choice not available")
print(computer_parts)
|
51dc73efdfe3d01afaf43a0c1210e11282254f39 | zvarychdenys/MyProject | /sort/bublesort.py | 410 | 3.5625 | 4 | from random import random
data = []
def random_values(arr):
for elem in range(15):
arr.append(int(random()*100))
return arr
print(random_values(data))
def buble_sort(arr):
n = len(arr)
for i in range(n - 1):
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
print(buble_sort(data)) |
1b1047e4e8df945d7a4c3ba4f1382774502b87b0 | bmorale1/Program-Repository | /Python/Morales_I_Assignment#5.py | 1,565 | 4.25 | 4 | #author: Isaac Morales
#filename: Morales_I_assignment#5.py
#purpose: to create a visually appealing pattern using functions
# and user input values
#date: october, 18, 2015
import random
#Set user input function
def inputValidate():
user_number = input("Enter the side size of the hexagons(10-200): ")
if user_number.isdigit():
while int(user_number)<10 or int(user_number)>200:
user_number=int(input('invalid, please re-enter(10-200)'))
global number
number = int(user_number)
else:
while user_number.isdigit() == False or int(user_number)<10 or int(user_number)>200:
user_number = input('invalid, please re-enter(10-200)')
number = int(user_number)
#Set turtle design function
def patternCons():
import turtle
megan = turtle.Turtle()
turtle.bgcolor('grey')
megan.hideturtle()
megan.speed(10)
for i in range(18):
megan.begin_fill()
megan.color(random.random(),random.random(),random.random())
for i in range(5):
megan.forward(number)
megan.left(60)
megan.forward(number)
megan.left(40)
megan.penup()
megan.forward(30)
megan.pendown()
megan.end_fill()
#define main function
def main():
print('This program makes a ring of hexagons,\nthe number you enter determines the size of the hexagons')
inputValidate()
print('Constructing pattern..')
patternCons()
#call main
main()
|
b2918bf4f77c355b2dbb2d1296fb5d29eb25c2b3 | ajjumaxy/trump_tweet_analysis | /python_code/create_word_cloud_and_scatter_plot_by_topic.py | 4,923 | 3.96875 | 4 | import plotly.express as px
import seaborn as sns
import re
import csv
import matplotlib.pyplot as plt
import pandas as pd
from wordcloud import WordCloud, STOPWORDS
from nltk.corpus import stopwords
stop_words = set(stopwords.words('english'))
# a function to create a word cloud of Trump's tweets that contain the topic words searched for by the user
def create_word_cloud(user_text):
#function to flatten the user text data array
def flatten_user_text(user_text): return [
item for sublist in user_text for item in sublist]
# create the word cloud text
word_cloud_text = flatten_user_text(user_text)
# create a word cloud object
wc = WordCloud(width=800, height=800,
background_color='white',
min_font_size=10)
#call word cloud
word_cloud_image = wc.generate_from_text(' '.join(word_cloud_text))
#plot the WordCloud image
plt.figure(figsize=(8, 8), facecolor=None)
plt.imshow(word_cloud_image)
plt.axis("off")
plt.tight_layout(pad=0)
plt.show()
# a function to load the topic clusters from the CSV
def load_topic_data():
topic_word_list = []
# import the csv file with the topic clusters and extract the text entries
with open("../data/topic_groups.csv", "r") as f:
csvReader = csv.reader(f)
for row in csvReader:
data = row
topic_word_list.append(data)
# create a dataframe of the topic words and return the top 10 words
data_df = pd.DataFrame(topic_word_list)
# a function to let the user choose which topic to look at
def get_user_search_words():
# check validity of user input
while True:
user_search_topic = input("Which topic would you like to view? There are 28 topics to choose from: ")
if not 0<int(user_search_topic)<29:
print("Please enter an integer between 1 and 28.")
#better try again... Return to the start of the loop
continue
else:
break
# call the load data function
data_df = load_topic_data()
# return the top ten words from the topic cluster selected by the user
topic_number = 2 * (int(user_search_topic)-1)
search_words = data_df.iloc[1:11, topic_number]
search_word_weights = data_df.iloc[1:11, topic_number+1]
print(search_words, search_word_weights)
return search_words.values.tolist()
# a function to load the topic clusters from the CSV and return a dataframe of the top 10 words for each cluster
def load_topic_data():
topic_word_list = []
# import the csv file with the topic clusters and extract the text entries
with open("../data/topic_groups.csv", "r") as f:
csvReader = csv.reader(f)
for row in csvReader:
data = row
topic_word_list.append(data)
# create a dataframe of the top 10 words for each topic cluster
data_df = pd.DataFrame(topic_word_list)
return data_df
# import and clean all tweets
def import_tweets():
# import the csv file and extract the text entries
search_term_list = get_user_search_words()
print(search_term_list)
with open('../data/condensed_dow_and_sentiment.csv', 'r') as f:
csvReader = csv.DictReader(f)
tweet_list = []
original_tweet_list = []
clean_tweet_list = []
for row in csvReader:
data = row["Time"], row["Vader_compound"],row["Volatility"], row["Open"],row["Close"],row["Tweet_text"], row["Volume"]
tweet_list.append(data)
for tweet in tweet_list:
time = tweet[0]
sentiment = tweet[1]
dow_volatility = tweet[2]
dow_open = tweet[3]
dow_close = tweet[4]
text = tweet[5]
dow_volume = tweet[6]
if len(text)>5:
text = re.sub(r'https.*', ' ', text)
text = text.replace('&', '')
text = text.replace('U.S.', 'usa')
text = text.replace('dems', 'democrats')
text = text.replace('RT', '')
text = text.replace('-', '')
text = text.replace('?', '')
text = text.replace('.', '')
text = text.replace('#', '')
text = text.replace('@', '')
text = text.lower()
tokens = text.split()
tokens = [w for w in tokens if not w in stop_words]
listToStr = ' '.join(map(str, tokens))
content_word_tweets = time, sentiment, dow_volatility, dow_open, dow_close, listToStr, dow_volume
#searching for user input term (lower case)
for word in search_term_list:
if word in tokens:
clean_tweet_list.append(content_word_tweets)
original_tweet_list.append(tweet)
user_text = clean_tweet_list
df = pd.DataFrame(clean_tweet_list, columns = ["Time", "Sentiment","A", "B", "C", "Text", "F"])
df["Tweet"] = original_tweet_list
df = df.drop(columns = ["A", "B", "C", "F"])
create_word_cloud(user_text)
return df, search_term_list
# call the import data function and create the search term list
tweet_dataframe, search_term_list = import_tweets()
search_terms = ' '.join(map(str, search_term_list))
fig = px.scatter(tweet_dataframe, x= "Time",y="Sentiment", hover_data=["Tweet", "Sentiment"])
fig.update_layout(
title={
'text': "Results for: " + search_terms,
'y': 0.99,
'x': 0.5,
'xanchor': 'center',
'yanchor': 'top'})
fig.show()
|
aa93f1d40e4a4b808d3e29ff92b7b35b2b97e1c0 | lizenghui1121/DS_algorithms | /算法思想/回溯/04.生成括号.py | 1,806 | 3.875 | 4 | """
已知N组括号,生成这N组括号的所有合法可能
@Author: Li Zenghui
@Date: 2020-04-06 15:10
"""
# 递归生成所有可能,包括合法不合法
def gen_test(n):
def generate(item, n, result):
if len(item) >= 2 * n:
result.append(item)
return
generate(item + '(', n, result)
generate(item + ')', n, result)
res = []
generate("", n, res)
return res
def gen_test_2(n):
def backtrack(q, i, track, res):
if i == 2 * q:
res.append(''.join(track))
return
for item in ["(", ')']:
track.append(item)
backtrack(q, i+1, track, res)
track.pop()
track = []
res = []
backtrack(n, 0, track, res)
return res
def generate_parentheses(n):
def generate(item, left, right, result):
if left == 0 and right == 0:
result.append(item)
return
if left > 0:
generate(item + '(', left - 1, right, result)
if left < right:
generate(item + ')', left, right - 1, result)
start = ''
res = []
generate(start, n, n, res)
return res
def generate_parentheses_2(n):
def back_track(track, left, right, res):
if left == 0 and right == 0:
res.append(''.join(track))
if left > 0:
track.append('(')
back_track(track, left-1, right, res)
track.pop()
if left < right:
track.append(')')
back_track(track, left, right-1, res)
track.pop()
track = []
res = []
back_track(track, n, n, res)
return res
if __name__ == '__main__':
# print(gen_test(2))
print(gen_test_2(2))
print(generate_parentheses(2))
print(generate_parentheses_2(2))
|
eb3de63b345baac3a866da5d3ffaeeb807f71fa9 | rakzroamer/ExerciseCourse | /mod_ex.py | 751 | 4.15625 | 4 | score = input("Enter Score: ")
fscore = float(score)
if not fscore <= 0.0 or fscore >= 1.0:
if fscore >0.0 and fscore <0.6:
print ("F")
elif fscore >=0.6 and fscore <0.7:
print ("D")
elif fscore >=0.7 and fscore <0.8:
print ("C")
elif fscore >=0.8 and fscore <0.9:
print ("B")
else:
print ("A")
'''Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours.
Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75).
if (h > 40):
pay = (40 * r) + (h - 40) * 1.5 * r
else:
pay = (h * r)
return pay''' |
3c7aa3fc8a84d443c2484e73999c9b84ad9e3fec | theevilaunt/Projects | /wroxprojects/straight_line.py | 225 | 4.21875 | 4 | def straight_line(gradient, x, constant):
''' return y coordinate of straight line -> gradient * x + constant'''
return gradient*x + constant
print(straight_line(2,4,-3))
for x in range(10):
print(x,straight_line(2,x,-3)) |
fd4986f3f247eba7dabcf7d3f5d7d06c5eefa656 | chends888/CodingInterviews | /recursion/sum1.py | 1,286 | 3.625 | 4 | from tree import Tree
def sum_all(A, n):
if (n == -1):
return 0
else:
A[n]+=sum_all(A, n-1)
return A[n]
# A = [1, 2, 2,3,4,5]
# print(sum_all(A, len(A)-1))
def sum_digits(n):
def sum_digits_r(n, sum=0):
# print(n)
if (n > 0):
if (n%10 == 0):
sum = sum_digits_r(n//10)
else:
sum += 1
sum += sum_digits_r(n-1)
# print(n, sum)
return sum
return sum_digits_r(n)
# print(sum_digits(333))
def sum_tree(root):
res = root.value
if (root.left):
res += sum_tree(root.left)
if (root.right):
res += sum_tree(root.right)
return res
# tree = Tree(list(range(3)))
# print(tree)
# print()
# print(sum_tree(tree.root))
def max_tree(root):
res = root.value
if (root.left):
res2 = max_tree(root.left)
if (res2 > res):
res = res2
if (root.right):
res3 = max_tree(root.right)
if (res3 > res):
res = res3
# if (root.value >):
return res
# tree = Tree(list(range(9999)))
# print(tree)
# print()
# print(max_tree(tree.root))
def k_elem(root):
res = [root.value]
if (root.left):
res += pre_order_recursive(root.left)
return res |
accf1bb4f35cae2d9a78b8aa1ac2996aee358df1 | juliannepeeling/class-work | /Chapter 5/5-5.py | 709 | 3.96875 | 4 | alien_color = 'green'
print(alien_color)
if alien_color == 'green':
print("You just earned 5 points for shooting the alien.")
elif alien_color == 'yellow':
print("You just earned 10 points!")
else:
print("You just earned 15 points!")
alien_color = 'yellow'
print(alien_color)
if alien_color == 'green':
print("You just earned 5 points for shooting the alien.")
elif alien_color == 'yellow':
print("You just earned 10 points!")
else:
print("You just earned 15 points!")
alien_color = 'red'
print(alien_color)
if alien_color == 'green':
print("You just earned 5 points for shooting the alien.")
elif alien_color == 'yellow':
print("You just earned 10 points!")
else:
print("You just earned 15 points!") |
89ff0a193e8bbb742a364afb47a261335de9c62f | padmaja125/Python-Assignment_Padmaja | /Task-2(Q-10).py | 653 | 3.921875 | 4 | x = 1
while x :
guess = input('Do you want to enter the game(Y/N) : ')
if guess == 'Y' or guess == 'y':
counter =1
while counter <= 5:
print("Type in the", counter, "number")
global number
number = int(input('Enter the number : '))
counter = counter +1
if number == 10 :
print("Good Guess")
break
else:
print("Try again!")
if number == 10:
print ('Game Over')
else :
print("Sorry but that was not very successful")
else:
print('See you later')
x = 0 |
893ac6ab9d195519f357518de91e9e2aaac66ba5 | slott56/my-euler | /euler38.py | 2,852 | 4.34375 | 4 | #!/usr/bin/env python3
# Pandigital multiples
# =====================
# Problem 38
# Take the number 192 and multiply it by each of 1, 2, and 3:
#
# 192 × 1 = 192
#
# 192 × 2 = 384
#
# 192 × 3 = 576
#
# By concatenating each product we get the 1 to 9 pandigital, 192384576. We will
# call 192384576 the concatenated product of 192 and (1,2,3)
#
# The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and
# 5, giving the pandigital, 918273645, which is the concatenated product of 9 and
# (1,2,3,4,5).
#
# What is the largest 1 to 9 pandigital 9-digit number that can be formed as the
# concatenated product of an integer with (1,2, ... , n) where n > 1?
# .. rubric:: Solution
# .. py:module:: euler38
# :synopsis: Pandigital multiples
# We'll use :py:func:`euler04.digits` and :py:func:`euler35.number`.
from euler04 import digits
from euler35 import number
# A test for being pan-digital. Zero's are excluded from the test.
def pandigital( da, order=9 ):
"""All digits from 1 to order?
>>> from euler38 import pandigital
>>> pandigital( digits(192384576) )
True
>>> pandigital( digits(192384476) )
False
"""
if len(da) != 9: return False
dSeen= (order+1)*[False]
for d in da:
dSeen[d]= True
return all(dSeen[1:])
# Compute a product concatenation from multiples of *n*. Stop when we
# have a 9-digit number.
def prodConcat( n ):
"""Create a 9-digit concatenaed product by successive multiplications
of n by 1, 2, 3, ..., 9
>>> from euler38 import prodConcat
>>> prodConcat( 192 )
[1, 9, 2, 3, 8, 4, 5, 7, 6]
>>> prodConcat( 9 )
[9, 1, 8, 2, 7, 3, 6, 4, 5]
"""
seq= []
for p in range(1,10):
seq.extend( digits(n*p) )
if len(seq) >= 9: break
return seq
# Generate all pan-digital numbers by starting within a range of 1,000,000.
def genPanDigitalProdConcat():
"""Get the list of pandigital products.
>>> from euler38 import genPanDigitalProdConcat
>>> pdpc= list( genPanDigitalProdConcat() )
>>> pdpc.sort()
>>> pdpc # doctest: +ELLIPSIS
[123456789, 192384576, 219438657, ..., 927318546, 932718654]
"""
for i in range(1000000):
seq= prodConcat(i)
if pandigital(seq):
yield number(seq)
# Test the module components.
def test():
import doctest
doctest.testmod(verbose=0)
assert pandigital( digits(192384576) )
# Create the answer.
def answer():
return max( genPanDigitalProdConcat() )
def confirm(ans):
assert ans == 932718654, "{0!r} Incorrect".format(ans)
if __name__ == "__main__":
test()
ans= answer()
confirm(ans)
print( "The largest 1 to 9 pandigital 9-digit number that can be formed as the"
" concatenated product of an integer with (1,2, ... , n) where n > 1:", ans ) |
acef67bf17194166f94aad2e23b4d3df70349bc1 | adrianmarino/algorithms | /guia/4.3.py | 1,213 | 3.53125 | 4 | #!/bin/python
def max_plateau(numbers):
"""
Order: O(n)
"""
max_num = None
max_count = count = i = 0
while i < len(numbers):
cur_num = numbers[i]
next_num = numbers[i + 1] if i + 1 < len(numbers) else None
count += 1
if next_num != cur_num:
if count > max_count:
max_count = count
max_num = cur_num
count = 0
i += 1
return max_num, max_count
def test(list, expected_element, expect_count):
element, count = max_plateau(list)
assert expected_element == element, f'Input: {list}, Element: {expected_element} != {element}'
assert expect_count == count, f'Input: {list}, Max count: {expect_count} != {count}'
print('Pass -> List:', list, 'element:', element, 'Max count:', count)
test([1, 1, 2, 6, 6, 6, 3, 3, 3, 3], expected_element=3, expect_count=4)
test([1, 1, 2, 6, 6, 6, 3, 3, 3], expected_element=6, expect_count=3)
test([], expected_element=None, expect_count=0)
test([1, 2, 3], expected_element=1, expect_count=1)
test([1, 2], expected_element=1, expect_count=1)
test([1, 1], expected_element=1, expect_count=2)
test([1], expected_element=1, expect_count=1) |
02fb53eec5067a3d774a0e98ff479e4a05449ae5 | Santhoshharsha/python_practice | /bracevalidate.py | 654 | 4.03125 | 4 | #!/usr/local/bin/python
def braceValidate(s):
stk = []
for c in s:
if c == '{':
stk.append(1)
elif c == '(':
stk.append(2)
elif c == '[':
stk.append(3)
elif c == '}':
if stk.pop(-1) != 1:
return False
elif c == ')':
if stk.pop(-1) != 2:
return False
elif c == ']':
if stk.pop(-1) != 3:
return False
if stk:
return False
return True
if __name__ == '__main__':
if braceValidate("{ [ }"):
print "Match"
else:
print "Mismatched brackets"
|
5afd1ffb669acca6c310d846a8e2fba240bbcc0f | Ayush456/MyJavascript | /Desktop/ayush/python/GlobLocVar.py | 161 | 3.71875 | 4 | total=30
def sum(arg1,arg2):
total=arg1+arg2
print("Inside the function : ",total)
return total
sum(10,12)
print("Outside The function : ",total)
|
4b3c432d7fafe217323bb6021cb9f58c086df442 | rathoresrikant/HacktoberFestContribute | /Algorithms/Array/zeroMover.py | 234 | 3.71875 | 4 | # Replace this with your own array.
arr = [1, 1, 0, 2, 3, 0, 1, 0]
zeroCounter = 0
newArr = []
for num in arr:
if num == 0:
zeroCounter+=1
else:
newArr.append(num)
for i in range(0, zeroCounter):
newArr.append(0)
print(newArr)
|
13809b285fcbc811323d9d0dab27f051bdebe8c0 | dqhcjlu06/python-algorithms | /test_linked.py | 1,100 | 4.125 | 4 | from ch03linked.positional_list import PositionalList
from ch03linked.favorites_list import FavoritesList
# 位置列表执行插入排序
def insertion_sort(L):
if (len(L) > 1):
maker = L.first()
while maker != L.last():
pivot = L.after(maker)
value = pivot.element()
if value > maker.element():
maker = pivot
else:
walk = maker
while walk != L.first() and L.before(walk).element() > value:
walk = L.before(walk)
L.delete(pivot)
L.add_before(walk, value)
if __name__ == "__main__":
L = PositionalList()
L.add_first(2)
L.add_first(5)
L.add_first(9)
L.add_first(7)
L.add_first(4)
L.add_first(6)
insertion_sort(L)
print('PositionalList {0}'.format([e for e in L]))
fav = FavoritesList()
for c in 'hello. this is a test of':
if c != ' ':
fav.access(c)
k = min(5, len(fav))
print('Top {0}) {1} {2}'.format(k, [x for x in fav.top(k)], fav))
|
13d608787bebef1f66a9dd9c9b313fbf072be824 | gabriellaec/desoft-analise-exercicios | /backup/user_084/ch59_2020_03_17_22_52_16_143390.py | 105 | 3.703125 | 4 | def asteriscos(n):
n=int(input('escolha um numero positivo: ')
y='*'
print (y*n)
return n |
290471713796baec34e9eff9291691dc4f545947 | BillionsRichard/pycharmWorkspace | /DataStructure/queue/ListQueue.py | 1,260 | 3.78125 | 4 | # encoding: utf-8
"""
用数组实现队列:
@version: v1.0
@author: Richard
@license: Apache Licence
@contact: billions.richard@qq.com
@site:
@software: PyCharm
@file: ListQueue.py
@time: 2018/8/26 15:47
"""
class ListQueue(object):
def __init__(self):
self.queue = []
def enqueue(self, data):
"""入队。
:param data:
:return:
"""
self.queue.append(data)
return
def dequeue(self):
"""出队
:return:
"""
if self.queue:
return self.queue.pop(0)
else:
return None
def front_value(self):
"""返回队首的值
:return:
"""
if not self.queue:
return None
return self.queue[0]
def is_empty(self):
"""队列是否为空
:return:
"""
return not bool(self.queue)
def traverse(self):
print('遍历:', self.queue)
if __name__ == '__main__':
q = ListQueue()
q.traverse()
q.enqueue('晓明')
q.traverse()
q.enqueue('晓红')
q.enqueue('晓嘉')
q.enqueue('晓慧')
q.traverse()
q.dequeue()
q.traverse()
q.enqueue('小松')
q.traverse()
q.dequeue()
q.traverse()
|
2900bfb60ae162e6b410a1bf5be1e35c36be590e | liketheflower/CSCI13200 | /list/basic_list.py | 440 | 3.671875 | 4 | """
basic list operations
Sep 13, 2019
jimmy shen
"""
# sum of 1 to n by using list
def sum_1_to_n(n):
a = []
for i in range(1, n+1):
a.append(i)
print(a)
return sum(a)
n = 100
res = sum_1_to_n(n)
print(res)
a = [1, 2, 3, 4, 5]
b = [10, 13, -1, -1000]
print('a', a)
print(a[0])
print(a[-1])
print('length of list a', len(a))
c = a+b
print('b', b)
print('c is a+b, what is c', c)
c = c[::-1]
print('reserve c', c)
|
b987255f4ca617b4c00645bd56df00843251ebe7 | heddle317/coding-exercises | /min_max.py | 656 | 3.828125 | 4 | """
go-left Software Rotating Header Image
100 Little Programming Exercises
https://go-left.com/blog/programming/100-little-programming-exercises/
A.6 Min and Max
Write a program which accepts numbers as arguments and which determines the lowest and highest number.
$ min-max 1 10 99 5 19 -23 17
Read 7 numbers
Min value: -23
Max value: 99
"""
import sys
if __name__ == '__main__':
# This is how you get the items in a list from 1 to the end of the list.
# If you type, "python min_max.py 1 4 3 2 10 9", then this will create a list with the
# numbers [1 4 3 2 10 9]
numbers = sys.argv[1:]
# Replace 'pass' with your code
pass
|
be61ee63a72dc930bf1ec21548f3e9b632e6f784 | woodpeckeh/python | /Programa-4.py | 325 | 3.90625 | 4 | #-- 4. realiza una funcion que permita tener el maximo de 3 numeros --
def mayor(a,b,c):
may = ''
if a > b:
if a > c:
may=a
else:
if b > a:
if b > c:
may=b
else:
may=c
return may,a,b,c
mayo, x , y , z = mayor(4,10,3)
print "de los numeros: " , x , " , " , y , " , " , z , " el mayor es: " , mayo |
cbb41c9109e792ae4b461a6cf05fd829173df663 | ramilabd/tasks_python | /hexlet/FizzBuzz.py | 423 | 3.6875 | 4 | def fizz_buzz(begin, end):
if begin > end:
return ''
result = ''
for i in range(begin, end + 1):
if i % 3 == 0 and i % 5 == 0:
result = result + 'FizzBuzz '
elif i % 3 == 0:
result = result + 'Fizz '
elif i % 5 == 0:
result = result + 'Buzz '
else:
result = result + str(i) + ' '
return '{0}'.format(result.rstrip())
|
43c13e456a00ac8bb20b97b1d7f7c56ce189d2d4 | mananrg/Machine_Learning | /Machine Learning/2.Regression/2.Multiple_Linear_Regression/Multiple_Linear_Regression.py | 927 | 3.640625 | 4 | # Importing the libraries and dataset
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_csv('50_Startups.csv')
X = df.iloc[:, :-1].values
y = df.iloc[:, -1].values
# Encoding the independent data (State)
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
ct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [3])], remainder='passthrough')
X = np.array(ct.fit_transform(X))
# Splitting the data into training set and testing set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train ,y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# Training the Multiple Linear Regression model on the Training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
# Predicting the Test set results
y_pred = regressor.predict(X_test)
print(y_pred) |
c937d2fa924c7275b81db5895b41fceef05a2f32 | MarianoMartinez25/Python | /2 - operadores y expresiones/oplogico.py | 489 | 3.734375 | 4 | # Operador not
# print(not True)
# Operador and
# print(True and False)
# Operador or
# print (True or False)
c = "Phyton"
print(len(c) < 8 and c[0] == "P")
kil = int(input("A cuantos kilometros se encuentra de la escuela?: "))
her = int(input("Cuantos hermanos tiene en la escuela?: "))
ing = int(input("De cuanto es el ingreso en su casa?: "))
if kil < 10 and her < 2 or ing > 2000:
print("Tienes derecho a beca")
else:
print("No tienes derecho a beca")
|
4bcf8527a0fc45f7dc487c91235f2c7b4cd1dcc1 | yzl232/code_training_leet_code | /Remove Invalid Parentheses.py | 1,805 | 3.984375 | 4 | '''
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
Note: The input string may contain letters other than the parentheses ( and ).
Examples:
"()())()" -> ["()()()", "(())()"]
"(a)())()" -> ["(a)()()", "(a())()"]
")(" -> [""]
'''
'''
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
Note: The input string may contain letters other than the parentheses ( and ).
Examples:
"()())()" -> ["()()()", "(())()"]
"(a)())()" -> ["(a)()()", "(a())()"]
")(" -> [""]
'''
class Solution(object):
def removeInvalidParentheses(self, s):
cur = set([s]); ret = [x for x in cur if self.isValid(x)] # set("")会返回empty set . set([""]) OK
while not ret: #实际上是BFS, pre和cur都在下面这行
cur = set([x[:i] + x[i+1:] for x in cur for i in range(len(x))])
ret = [x for x in cur if self.isValid(x)]
return ret
def isValid(self, s):
cnt = 0
for c in s:
if c == '(': cnt += 1
elif c == ')': cnt -= 1
if cnt < 0: return False
return cnt == 0
'''
class Solution(object):
def removeInvalidParentheses(self, s):
cur = set([s]); # set("")会返回empty set . set([""]) OK
while True:
ret = [s for s in cur if self.isValid(s)]
if ret: return ret #实际上是BFS, pre和cur都在下面这行
cur = set([x[:i] + x[i+1:] for x in cur for i in range(len(x))])
def isValid(self, s):
cnt = 0
for c in s:
if c == '(': cnt += 1
elif c == ')': cnt -= 1
if cnt < 0: return False
return cnt == 0
''' |
027b72adb804597d6fba9090e452d4bc3be811e1 | Martsyalis/data-preprocessing | /index.py | 2,006 | 3.546875 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Import Dataset
dataset = pd.read_csv('./Data.csv')
x = dataset.iloc[:, :-1].values # grab values in all rows and all but the last columns
y = dataset.iloc[:, -1].values # grab values in all rows for the last column
# print(x)
# print(y)
# print("".join(['-' for i in range(40)]))
print(type(x))
# Handle Missing Data
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values=np.nan, strategy='mean') # replace missing values as defined in np with 'mean' strategy
imputer.fit(x[:, 1:3]) # compute the missing values for all rows for 1st and 2nd calumn
x[:, 1:3] = imputer.transform(x[:, 1:3]) # replace all rows for 1st and second column with imputers version
# print(x)
# print("".join(['-' for i in range(40)]))
# Transform and Encode Categorical Data
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
# use oneHotEncoder to trasform 0th column, keep the others unchanged
ct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [0])], remainder='passthrough')
x = np.array(ct.fit_transform(x)) # transform the x and convert it to np array
# print(x)
# print("".join(['-' for i in range(40)]))
# Transform and Encode The Dependent Variable
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
y = le.fit_transform(y)
# print(y)
# print("".join(['-' for i in range(40)]))
# Split dataset into Training and Testing sets
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state = 1) # split 80/20 and seed random with 1
print(X_train)
print("".join(['-' for i in range(40)]))
# Sacle Features using Standarization
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train[:, 3:] = sc.fit_transform(X_train[:, 3:])
X_test[:, 3:] = sc.transform(X_test[:, 3:])
print(X_test)
print("".join(['-' for i in range(40)]))
print(X_train)
|
6a1c180a60338b97299a58fcee3839c865a21f9f | anki112279/Calculator | /Calculator.py | 1,011 | 3.625 | 4 | import re
def calculator(exp):
if check_float(exp):
return float(exp)
operators = ['+', '-', '*', '/']
for c in operators:
left, opt, right = exp.partition(c)
if opt == '+':
return calculator(left) + calculator(right)
elif opt == '-':
return calculator(left) - calculator(right)
elif opt == '*':
return calculator(left) * calculator(right)
elif opt == '/':
return calculator(left) / calculator(right)
def check_float(exp):
try:
float(exp.strip())
return True
except ValueError:
return False
def resolving_brackets(s):
org_s = s
k = re.search(r"\(.+\)", s)
if not k:
return s
start = k.span()[0]
stop = k.span()[1]
sub_exp = k[0][1:-1]
new_exp = resolving_brackets(sub_exp)
num = calculator(new_exp)
new_exp = org_s[0:start]+str(num)+org_s[stop:]
return new_exp
if __name__ == '__main__':
expression = '8+9/6'
res = resolving_brackets(expression)
print(calculator(res))
|
8111a44e3256e57110cc9d7626717d91e2c49bb1 | Lunaire86/DummyCluster | /src/main.py | 2,046 | 3.828125 | 4 | ##
# Main program
# @author: marispau
from test import Test
def run_tests(test_unit, file_name):
"""
Runs various tests to make sure the program works as intended.
:param test_unit: str
:param file_name: str
"""
program = test_unit
if program == "Abel":
print("\nYOU ARE RUNNING THE MAIN PROGRAM\n")
elif program == "Test 1":
print("\nYOU ARE RUNNING TEST PROGRAM 1\n")
elif program == "Test 2":
print("\nYOU ARE RUNNING TEST PROGRAM 2\n")
else:
return "Error"
run = Test(test_unit, file_name)
run.print_orders()
run.print_cluster_info()
run.print_cluster_numbers(32)
run.print_check_for_holes()
def main():
"""
The main program sets the values for the tests and initiates the testing.
User input driven.
"""
abel = "Abel", "data.txt"
test_1 = "Test 1", "zero_nodes.txt"
test_2 = "Test 2", "zero_orders.txt"
start_msg = "\n<<PROGRAM STARTED>>"
choices = "\nPress [A] for Abel\nPress [1] for test 1\nPress [2] for test 2\nPress [X] to exit\n"
print(start_msg, choices)
user_input = input().strip().upper()
valid_input = ("A", "1", "2", "X")
while user_input not in valid_input:
print("Invalid input.\n", choices)
user_input = input().strip().upper()
while user_input != "X":
if user_input not in valid_input:
print("Invalid input.\n", choices)
user_input = input().strip().upper()
if user_input == "A":
run_tests(*abel)
print(choices)
user_input = input().strip().upper()
elif user_input == "1":
run_tests(*test_1)
print(choices)
user_input = input().strip().upper()
elif user_input == "2":
run_tests(*test_2)
print(choices)
user_input = input().strip().upper()
print("TERMINATED")
if __name__ == '__main__':
main()
|
762cff88aa556d890ea3f234a508f74785da7bb4 | frclasso/revisao_Python_modulo1 | /cap12-dicionarios/11_get_method.py | 461 | 3.859375 | 4 | #!/usr/bin/env python3
"""obtém o conteúdo de uma chave. Não causa erro caso uma chave não exista, retorna valor;e
Se valor não for especificados nas chaves existentes, retorna None.
Sintaxe:dict.get(key, default=None)
"""
dict = {'Name':'Zara', 'Age':7}
print('Valor do campo: {}'.format(dict.get('Age')))
print('Valor do campo: {}'.format(dict.get('Sexo')))
print('Valor do campo: {}'.format(dict.get('Sobrenome', 'Vasquez'))) # passando valor |
4c4b8eec61bae0df4d61e95e22abb5854b6ebd5b | Lairin-pdj/coding_test_practice_programmers | /디스크 컨트롤러.py | 1,429 | 3.609375 | 4 | import heapq
def solution(jobs):
answer = 0
count = 1
jobs.sort() # 시간 순서대로 정렬
temp = []
for a, b in jobs: # 우선순위큐를 사용하기 위해 뒤집음
temp.append([b, a])
jobs = temp
queue = []
heapq.heappush(queue, jobs[0]) # 맨 처음 작업을 진행
time = jobs[0][1] # 작업한 뒤 시간을 측정
while len(queue) > 0: # 모든 작업이 마무리 될때 까지 반복
temp = heapq.heappop(queue) # 현재 큐 중 가장 짧은 작업 진행 및 시간 추가
time += temp[0]
answer += (time - temp[1])
while count < len(jobs) and jobs[count][1] <= time: # 현재 시간에 요청이 온 작업들 큐에 삽입
heapq.heappush(queue, jobs[count])
count += 1
if count < len(jobs) and len(queue) == 0: # 큐를 다 소진하고 요청또한 없을 경우 다음 요청까지 건너뛰기
heapq.heappush(queue, jobs[count])
time = jobs[count][1]
count += 1
return int(answer / len(jobs)) # 결과값 반환
|
8a51dcc887d29344b68b8e0f145bb1152f90649b | vinayakentc/BridgeLabz | /AlgorithmProg/MonthlyPayment.py | 1,245 | 4.46875 | 4 | # Write a Util Static Function to calculate monthlyPayment that reads in three
# commandline arguments P, Y, and R and calculates the monthly payments you
# would have to make over Y years to pay off a P principal loan amount at R per cent
# interest compounded monthly.
# ------------------------------------------------------------------------------------
# Function to calculate monthly payments
def monthlypayment(p, y, r):
# Formulas to calculate monthly payment
n = 12 * y # years to months
rate = r / (12 * 100)
payment = (p * rate) / (1 - ((1 + rate) ** (-n)))
return payment
if __name__ == '__main__':
# taking inputs of Principle,year and interest rate
principle = float(input("Enter principle amount"))
year = float(input("enter no. of years"))
interest = float(input("Enter rate of interest"))
# if year/interest is zero
# raises a zero float division exception
# so it checks that year/interest should be non 0
while year == 0 or interest == 0:
print("year/interest can't be zero:")
year = float(input("enter no. of years"))
interest = float(input("Enter rate of interest"))
print("Monthly payment: ", monthlypayment(principle, year, interest))
|
26f41c8b251b6dc77be5770614df8bf5791abffd | udoyen/pythonlearning | /1-35/ex24.py | 1,242 | 4.15625 | 4 | print "Let's practice everything."
print 'You\'d need to know \'bout excapes with \\ that do \n newlines and \t tabs.'
poem = """
\tThe lovely world
with logic so firmly planted
cannot deiscern \n the needs of love
nor comprehend passion from intuition
and required an explanation
\n\t\twhere there is none.
"""
print "----------------"
print poem
print "----------------"
five = 10 - 2 + 3 - 6
print "This should be five: %s" % five
# Function that returns three values in the order they appear
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
# Assign variable names to the return values of the function, in the
# return order. The name given is irrelevant
beans, jars, crates = secret_formula(start_point)
print "With a starting point of: %d" % start_point
# Print the return values in order
print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates)
start_point = start_point / 10
print "We can also do that this way:"
# Function retruns values in the order they are generated in the function
print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point)
|
132099e7fc87f9b26ed6dcf55b4bd482d95be922 | praveendk/programs | /loops/whileLoop3.py | 254 | 4.1875 | 4 | # whileLoop practise
name = ""
while not name :
name = input("Please enter your name: \n")
numOfGuests = int(input("How many guests will you have? \n"))
if numOfGuests :
print("make sure you have enough rooms for accomodation.")
print("done") |
cc6bfa509b2b45f95c2bc014030a639592b7b581 | almoss1/CS-UY-1134 | /CODE/UnsortedArrayMap.py | 1,755 | 3.796875 | 4 | class UnsortedArrayMap:
class Item:
def __init__(self,key,value = None):
self.key = key
self.value = value
def __init__(self):
self.table = []
def __len__(self):
return len(self.table)
def is_empty(self):
return len(self) ==0
#m[key] ==> m.__getitem__(key) ==> __getitem__(m,key)
def __getitem__(self,key):
for item in self.table:
if key == item.key:
return item.value
raise KeyError(str(key) + "is not in the map")
#m[key] = value ==> m.__setitem__(key,value)
def __setitem__(self,key, value):
for item in self.table:
if key == item.key:
item.value = value
return
#if we get here, the key is not in the map
self.table.append(UnsortedArrayMap.Item(key,value))
#del m[key] ==> m.__Delitem__(self,key)
def __delitem__(self,key):
for idx in range(len(self.table)):
if key == self.table[idx].key:
#could do one or the other, a little better runtime
self.table.pop(idx)
# self.table[idx], self.table[-1] = self.table[-1], self.table[idx]
# self.table.pop()
return
#if we get here, then key is not in the map
raise KeyError(str(key) + "is not in the map")
def __iter__(self):
for item in self.table:
yield item.key
m = UnsortedArrayMap()
m["one"] = 1
m["two"] = 2
m["three"] = 3
m["four"] = 4
m["five"] = 5
val1 = "one"
val2 = "three"
#want t compute "one" + "three" ==> 4
result = m[val1] +m[val2]
print(result)
m["five"] = "0b101"
print(m["five"])
for key in m:
print(key, m[key])
|
d17edefb098e75c69e5cd5b23d0f6d57949aa816 | damiati-a/CURSO-DE-PYTHON-2 | /ex113.py | 1,028 | 3.9375 | 4 | # reescrever o programa e corrigir os erros do mesmo
def leiaInt(msg):
while True:
try:
n = int(input(msg))
except (ValueError, TypeError):
print('\033[31mPor favor. Digite um número inteiro válido\033[m')
continue
except KeyboardInterrupt:
print('\033[31mEntrada de dados não fornecida pelo usuario\033[m')
return 0
else:
return n
def leiaFloat(msg):
while True:
try:
n = float(input(msg))
except (ValueError, TypeError):
print('\033[31mPor favor. Digite um número inteiro válido\033[m')
continue
except KeyboardInterrupt:
print('\033[31mEntrada de dados não fornecida pelo usuario\033[m')
return 0
else:
return n
num1 = leiaInt('Digite um valor Inteiro: ')
num2 = leiaFloat('Digite um valor Real: ')
print(f'O valor digitado inteiro foi {num1} e o real foi {num2}')
|
3aabc3f69f33a9aa7e3dae27f96a0e353dc2196c | Vanya-Rusin/lavbs-5 | /Завдання 3.py | 375 | 3.859375 | 4 | import math
x = float(input("Введіть змінну х : "))
e = float(input("Введіть точність е: "))
S = 0
a = 1
while x ** (2 * a) / math.factorial(2 * a) > e:
S = -1**a * x ** (2 * a) / math.factorial(2 * a)
a += 1
print(S)
if math.cos(x) - S < e:
print("справедлива")
else:
print("несправедлива") |
54525f49f024477518690f29c92798bbdddaf5c9 | arnoringi/forritun | /Skilaverkefni/fibo_abundant.py | 2,487 | 4.3125 | 4 | # Project 3: Fibo and abundant
type_sequence = input("Input f|a|b (fibonacci, abundant or both): ")
### Fibonacci Sequence
if type_sequence == 'f' or type_sequence == 'b':
length = int(input("Input the length of the sequence: "))
print("Fibonacci Sequence:")
print("-------------------")
# These variables are meant for the start of the sequence
num1 = 0
num2 = 1
sum_int = 0
print(num1)
print(num2)
# The sum adds the most recent numbers (num1, num2) together, then changes them
for i in range(2, length):
sum_int = num1 + num2
print(sum_int)
num1 = num2
num2 = sum_int
### Abundant numbers
if type_sequence == 'a' or type_sequence == 'b':
max_num = int(input("Input the max number to check: "))
print("Abundant numbers:")
print("-----------------")
sum_int = 0
# The i for loop checks if number n is an abundant number
for i in range(1, max_num+1):
for j in range (1, i): # The j for loop checks all numbers that are proper divisors for number i
# If number can be divided with number j, then add to sum
if i % j == 0:
sum_int += j
# If sum is bigger than number, then print
if sum_int > i:
print(i)
sum_int = 0
break
# Sum reset
if j == (i - 1):
sum_int = 0
### ALGRÍM ###
# Fibonacci
# Fyrstu tvær tölurnar eru 0 og 1
# Næstu tölur eftir það eru summa næstu tveggja á undan (0, 1, 1, 2, 3, 5, 8, 13...)
# Tala n á að vera >= 2
# 1. Ef input er 'f' EÐA 'b' þá keyrir þetta
# 2. Input length segir til um hversu margar tölur á að prenta
# 3. Prentar "Fibonacci Sequence:" og svo "-------------------" í annari línu
# 4. Byrja á að prenta 0 og 1
# 5. For loopa 2, n mörgum sinnum
# 6. Í hverju loopi skal bæta saman seinustu tveim tölum
# Abundant
# Summa allra talna sem gengur upp í n töluna er hærri en n talan sjálf
# Summan eru allar tölurnar nema n talan
# 1. Ef input er 'a' EÐA 'b' þá keyrir þetta
# 2. Input max number til að gá hvaða tölur eru abundant
# 3. Prentar "Abundant numbers:" og svo "-------------------" í annari línu
# 4. Gera for loop fyrir tölurnar sem á að tjékka
# 5. Gera nested for loop til að tjékka hvaða tölur ganga upp í töluna |
645f9c469988776ceb1e9a362125884a4efa8955 | zhuangsen/python-learn | /com/advanced/2-13.py | 2,787 | 3.78125 | 4 | # -*- coding: utf-8 -*-
# python中编写带参数decorator
#
# 考察上一节的 @log 装饰器:
#
# def log(f):
# def fn(x):
# print 'call ' + f.__name__ + '()...'
# return f(x)
# return fn
#
# 发现对于被装饰的函数,log打印的语句是不能变的(除了函数名)。
#
# 如果有的函数非常重要,希望打印出'[INFO] call xxx()...',有的函数不太重要,希望打印出'[DEBUG] call xxx()...',这时,log函数本身就需要传入'INFO'或'DEBUG'这样的参数,类似这样:
#
# @log('DEBUG')
# def my_func():
# pass
#
# 把上面的定义翻译成高阶函数的调用,就是:
#
# my_func = log('DEBUG')(my_func)
#
# 上面的语句看上去还是比较绕,再展开一下:
#
# log_decorator = log('DEBUG')
# my_func = log_decorator(my_func)
#
# 上面的语句又相当于:
#
# log_decorator = log('DEBUG')
# @log_decorator
# def my_func():
# pass
#
# 所以,带参数的log函数首先返回一个decorator函数,再让这个decorator函数接收my_func并返回新函数:
#
# def log(prefix):
# def log_decorator(f):
# def wrapper(*args, **kw):
# print '[%s] %s()...' % (prefix, f.__name__)
# return f(*args, **kw)
# return wrapper
# return log_decorator
#
# @log('DEBUG')
# def test():
# pass
# print test()
#
# 执行结果:
#
# [DEBUG] test()...
# None
#
# 对于这种3层嵌套的decorator定义,你可以先把它拆开:
#
# # 标准decorator:
# def log_decorator(f):
# def wrapper(*args, **kw):
# print '[%s] %s()...' % (prefix, f.__name__)
# return f(*args, **kw)
# return wrapper
# return log_decorator
#
# # 返回decorator:
# def log(prefix):
# return log_decorator(f)
#
# 拆开以后会发现,调用会失败,因为在3层嵌套的decorator定义中,最内层的wrapper引用了最外层的参数prefix,所以,把一个闭包拆成普通的函数调用会比较困难。不支持闭包的编程语言要实现同样的功能就需要更多的代码。
# 任务
#
# 上一节的@performance只能打印秒,请给 @performace 增加一个参数,允许传入's'或'ms':
#
# @performance('ms')
# def factorial(n):
# return reduce(lambda x,y: x*y, range(1, n+1))
#
import time
from functools import reduce
def performance(unit):
def per_dec(f):
def fn(*args, **kw):
t1 = time.time()
r = f(*args, **kw)
t2 = time.time()
t = (t2 - t1) * 1000 if unit == 'ms' else (t2 - t1)
print('call %s in %f %s' % (f.__name__, t, unit))
return r
return fn
return per_dec
@performance('ms')
def factorial(n):
return reduce(lambda x, y: x * y, range(1, n + 1))
print(factorial(10))
|
314652af704372aae4e03e637944d8964f592c6c | row-yanbing/code_knowledge | /chars_use.py | 993 | 3.6875 | 4 | # -*- codiyng: UTF-8 -*-
# Filename : chars_use
# author by : yanbing
# 测试实例一
print("测试实例一")
str1 = "runoob.com"
print(str1.isalnum()) # 判断所有字符都是数字或者字母
print(str1.isalpha()) # 判断所有字符都是字母
print(str1.isdigit()) # 判断所有字符都是数字
print(str1.islower()) # 判断所有字符都是小写
print(str1.isupper()) # 判断所有字符都是大写
print(str1.istitle()) # 判断所有单词都是首字母大写,像标题
print(str1.isspace()) # 判断所有字符都是空白字符、\t、\n、\r
# 测试实例二
print("测试实例二")
str2 = "www.rUnoob.com"
print(str2.upper()) # 把所有字符中的小写字母转换成大写字母
print(str2.lower()) # 把所有字符中的大写字母转换成小写字母
print(str2.capitalize()) # 把第一个字母转化为大写字母,其余小写
print(str2.title()) # 把每个单词的第一个字母转化为大写,其余小写 |
9824df765c162659a46a44171f5bd7f281a3557b | ZimingGuo/MyNotes01 | /MyNotes_01/Step01/2-BASE02/day02_06/demo02.py | 1,602 | 4.46875 | 4 | # author: Ziming Guo
# time: 2020/2/8
'''
demo02
元组
基础操作
'''
# 1 创建元组(空)
tuple01 = ()
tuple01 = tuple()
# 因为一个元组里面也是一个个变量,所以也可以指向任何数据类型
# 所以元组里面也能放列表,字符串,数字
# 列表可以转换成元组:
tuple01 = tuple(["a", "b"])
print(tuple01)
# 元组也可以转换成列表:
list01 = list(tuple01)
print(list01)
# 这两种形式的相互转换其实是两个存储机制之间的转换
# 由按需分配到预留空间 & 由预留空间到按需分配
# 创建元组(具有默认值)
tuple01 = (1, 2, 3)
print(tuple01)
# 如果元组里面只有一个元素,要在这个元素的后面加上逗号
tuple02 = (100)
print(tuple02) # 此时打印出来的只是一个整形 100 int
tuple02 = (100,)
print(tuple02) # 此时打印出来的才是元组形式
# 这是元组的一个特殊形式
# 不能增加
# 没有 append 和 insert
# 2 获取元素(索引 & 切片)
tuple03 = ("a", "b", "c", "d")
e01 = tuple03[1] # 此处的 e01 是字符串类型
e01 = tuple03[-2:] # 表示的是取后两个元素 # 切片出来的是元组类型
tuple04 = (100, 200)
# 可以直接将元组赋值给多个变量,但是变量的个数和元组里面的元素个数必须相等
# 其实所有容器都支持这种写法,但一般都是用元组
a, b = tuple04
print(a) # 100 整形
print(b) # 200 整形
# 3 遍历元素
# 正向
for item in tuple04:
print(item)
# 反向
for i in range(-1, -len(tuple04) - 1, -1):
print(tuple04[i])
|
83c0bfb753aab01e089ba02a8f65e0877f54ea5b | cochosca/curso_de_python | /Aprendizaje/python/POO/Herencia.py | 2,260 | 3.96875 | 4 | #------------------##
# HERENCIA
#------------------##
# Cuando hay una clase principal o padre que herede sus metosod y atributos a las subclases o clases hijo
class Principal:
def __init__(self,nombre,edad):
self.nombre = nombre
self.edad = edad
# la clase Principal tiene los atributos nombre y edad
class Secundaria(Principal):# Entre parentesis se pone la clase de donde se hereda, en este caso de la clase Principal
def __init__(self,nombre,edad,pie,mano):
super().__init__(nombre,edad) # el comando super().metodo() lo que hace en referenciar a los atributos que fueron heredados de la clase anterior
self.pie = pie
self.mano = mano
def __str__(self):
return self.pie
pepe = Secundaria('pepe', 15, 'chico', 'grande')
print(pepe)
#--------------------
# __STR___
#____________________
# Su funcion es que el objeto sea mas legible, ya que el mismo retona una cadena de texto
class Pedro:
def __init__(self,c):
self.c = c
pedro = Pedro('c')
print(pedro)
# >>> <__main__.Pedro object at 0x7f0e75bd3790>
# Con el metodo __str__ podemos hacer al imprimir el objeto en si sea mas legible
class Pedrito(Pedro):
def __init__(self,c,sapo,gato):
super().__init__(c)
self.sapo = sapo
self.gato = gato
def __str__(self):
return f'la variable es: {self.sapo}'
pato = Pedrito('c', 'hola', 'chau')
print(pato)
# >>> la variable es: hola
#------------------
# HERENCIA MULTIPLE
#------------------
# Consiste en que una subclase puede heredear de muchas clases principales
class Padre:
def __init__(self,nombre,apellido):
self.nombre = nombre
self.apellido = apellido
def __str__(self):
return f'Clase padre, su nombre es {self.nombre} y su apellido es {self.apellido}'
print(Padre('jose','bentiez'))
class Madre:
def __init__(self,altura,peso):
self.altura = altura
self.peso = peso
# Clase que hereda de padre y madre
class Hijo(Padre,Madre):
def __init__(self,nombre,apellido,altura,peso,oficio):
# se llama el nombre de la clase y su atributo __init__(parametros a traer)
Padre.__init__(self,nombre,apellido)
Madre.__init__(self,altura,peso)
self.oficio = oficio |
f8d5dc821074a5478eb348bcf63a9d868bb2933e | BIAOXYZ/variousCodes | /_CodeTopics/LeetCode/401-600/000563/000563.py | 994 | 3.8125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
res = [0]
def dfs_tree_sum(node):
if not node:
return 0
if not node.left and not node.right:
return node.val
leftSum, rightSum = dfs_tree_sum(node.left), dfs_tree_sum(node.right)
res[0] += abs(leftSum - rightSum)
return leftSum + rightSum + node.val
dfs_tree_sum(root)
return res[0]
"""
https://leetcode-cn.com/submissions/detail/239727751/
执行用时:36 ms, 在所有 Python 提交中击败了87.50%的用户
内存消耗:15.7 MB, 在所有 Python 提交中击败了87.50%的用户
通过测试用例:
77 / 77
"""
|
1ceaa699ce47fd7b3fc58e400d50e750452dff71 | KVasileva/cd101 | /CW3/avage.py | 428 | 3.875 | 4 | def avg(ages):
return sum (ages) / len (ages)
if __name__== "__main__":
print(avg([12, 34, 21, 56]))
import math
def cos2(num):
for i in num:
return math.cos(i)/ 2
if __name__== "__main__":
print(cos2 ([12, 34, 21, 56]))
def sum3(a,b,c):
z = a+b+c
return z
y= sum3(1,1,3)
print (y)
import math
def st (x,y):
a = pow(x,y)
return (a)
b = st (2,8)
print (b) |
a2f760cfdf21be74ef5adf0bd4bc0ac9afbd0f00 | nylbert/PARSER | /lista.py | 2,106 | 3.6875 | 4 | import sys
class Node:
# Declaracao dos atributos desta Classe
tipo = None
nome = None
escopo = None
nextNode = None
# Fim declaracao
# Nesta secao encontram-se os metodos para acesso
# dos respectivos atributos
def __init__(self,nome, tipo, escopo):
self.tipo = tipo
self.nome = nome
self.escopo = escopo
self.proximo = None
def getTipo(self):
return(self.tipo)
def getNome(self):
return(self.nome)
def getEscopo(self):
return(self.escopo)
def getProximo(self):
return(self.proximo)
def setTipo(self, tipo):
self.tipo = setTipo
def setNome(self, nome):
self.nome = nome
def setEscopo(self, escopo):
self.escopo = escopo
def setProximo(self, proximo):
self.proximo = proximo
# Fim declaracao Metodos Get e Set
class List:
def __init__(self):
self.firstNode = None
self.lastNode = None
def insereInicio(self, nome, tipo, escopo):
newNode = Node(nome,tipo,escopo)
if self.isEmpty():
self.firstNode = self.lastNode = newNode
else:
newNode.setProximo(self.firstNode)
self.firstNode = newNode
# Metodo para remocao
def remove(self,escopo):
while self.firstNode.getEscopo() == escopo:
if self.firstNode == self.lastNode:
self.firstNode = self.lastNode = None
sys.exit()
else:
self.firstNode = self.firstNode.getProximo()
def buscaEscopo(self,nome, escopo):
temp = self.firstNode
while temp != None:
if temp.getNome() == nome and temp.getEscopo() == escopo :
return True
else:
temp = temp.getProximo()
return False
def buscar(self,nome):
temp = self.firstNode
while temp != None:
if temp.getNome() == nome:
return temp.getTipo()
else:
temp = temp.getProximo()
return False
def isEmpty(self):
if self.firstNode == None:
return True
else:
return False |
576779722b7612720f91a73aab21fdc97b0bd699 | NZSGIT/Comp-110-Zybook-Labs | /Section 2/2.15.py | 1,050 | 4.125 | 4 | '''
2.15 LAB: Using math functions
Given three floating-point numbers x, y, and z, output x to the power of z, x to the power of (y to the power of z), the absolute value of (x minus y), and the square root of (x to the power of z).
Output each floating-point value with two digits after the decimal point, which can be achieved as follows:
print('{:.2f} {:.2f} {:.2f} {:.2f}'.format(your_value1, your_value2, your_value3, your_value4))
Ex: If the input is:
5.0
1.5
3.2
Then the output is:
172.47 361.66 3.50 13.13
'''
'''----------------------------------------------------------------------------------------------------------'''
#Code Below
Age = int(input())
Weight = int(input())
HeartRate = int(input())
Time = int(input())
calories_woman = ((Age * 0.074) - (Weight * 0.05741) + (HeartRate * 0.4472) - 20.4022) * Time / 4.184
calories_man = ((Age * 0.2017) + (Weight * 0.09036) + (Heart Rate * 0.6309) - 55.0969) * Time / 4.184
print('Women: {:.2f} calories'.format(calories_woman))
print('Men: {:.2f} calories'.format(calories_man))
|
82c2eb3f20255c5859ad3da8b3e763bc4b59a164 | MaryanneNjeri/pythonModules | /.history/reverseString_20200605151541.py | 80 | 3.734375 | 4 | # looping through the array
def reverse(str):
reverse(["h","e","l","l","o"]) |
07d57ae131b32442893c61a01b92552abcde324e | faizkhan12/Basics-of-Python | /exercise9.6.py | 779 | 4 | 4 | class Restaurant(): #making a class
#defining methods
def __init__(self,name,cuisine):
self.name=name
self.cuisine=cuisine
def describe_restaurant(self):
print(self.name +" is name of the restaurant.")
print(self.name +" is famous for this "+self.cuisine+" food.")
def open_restaurant(self):
print(name+" is now open.")
class IceCreamStand(Restaurant):
def __init__(self,name,cuisine):
super().__init__(name,cuisine)
self.flavours=['vanilla','chocalate']
def describe_flavours(self):
print("This restaurant has " +str(self.flavours))
my_restaurant=IceCreamStand('Taj','Paneer')
my_restaurant.describe_restaurant()
my_restaurant.describe_flavours()
|
384024473e97ab302b5d262cf5e9e5c61e48eaf0 | HassanElDesouky/Data-Structures-In-Python | /Dynamic Array.py | 1,401 | 3.875 | 4 | import ctypes
class DynamicArray(object):
# init method
def __init__(self):
self.n = 0
self.capacity = 1
self.original_array = self.make_array(self.capacity)
# Special methods
def __len__(self):
"""
:return: the length of the array.
"""
return self.n
def __getitem__(self, item):
"""
Returns the item at the given index.
"""
if not 0 <= item < self.n:
return IndexError("Item is out of bounce.")
return self.original_array[item]
# Public methods
def append(self, element):
"""
Adds an element to at the last index in the array.
"""
if self.n == self.capacity:
self._resize(2*self.capacity) # resizing by 2x if size is not enough
self.original_array[self.n] = element
self.n += 1
def make_array(self, new_capacity):
"""
Make a new array with the defined capacity.
"""
return (new_capacity * ctypes.py_object)()
# Private methods
def _resize(self, new_capacity):
"""
Resize the array by 2x the original capacity.
"""
temp_array = self.make_array(new_capacity)
for i in range(self.n):
temp_array[i] = self.original_array[i]
self.original_array = temp_array
self.capacity = new_capacity
|
ef944d5382a4c906958062b976f628ed8f141293 | liyi0206/leetcode-python | /92 reverse linked list II.py | 1,187 | 3.890625 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if head == None: return None
dummy = ListNode(0)
dummy.next = head
start = dummy
for i in range(m-1):
start = start.next
#print "start",start.val
front = start.next
tmp = front
for i in range(n-m+1):
tmp1=front.next
tmp2=start.next
start.next = front
start.next.next = tmp2
front=tmp1
#print "front",front.val
tmp.next = front
return dummy.next
head=ListNode(1)
head.next=ListNode(2)
head.next.next=ListNode(3)
head.next.next.next=ListNode(4)
head.next.next.next.next=ListNode(5)
cur = head
while cur:
print cur.val,
cur=cur.next
print
a=Solution()
new=a.reverseBetween(head,1,4)
cur = new
while cur:
print cur.val,
cur=cur.next
|
5e270bb2098403d734a4fd918b64fbd055ba4be4 | AlexeyAMorozov/git-lesson | /NewYear.py | 265 | 3.90625 | 4 | from datetime import date
today = date.today()
print('Сегодня', today)
def NewYear():
delta = date(date.today().year + 1, 1, 1) - date.today()
return delta.days
print('До нового года осталось', NewYear(), 'дней')
|
9c7e8f010e82aa5b28d79757f6f0330a93c673dc | weilyu/hackerrank_python | /string/Capitalize.py | 334 | 4.15625 | 4 | # https://www.hackerrank.com/challenges/capitalize
line = input()
last_is_space = True
result = ''
for letter in line:
if last_is_space and letter.islower:
result += letter.upper()
else:
result += letter
if letter == ' ':
last_is_space = True
else:
last_is_space = False
print(result)
|
3a039ec788bf5dfd3d2a36199efec4680a44737a | RBaner/Project_Euler | /Python 3.8+/26-50/Problem 046/main.py | 553 | 4 | 4 | from sympy import isprime
from math import sqrt
import time
def main():
num = 3
while True:
if isprime(num):
num += 2
continue
else:
passed = False
for i in range(1,int(sqrt((num-3)/2))+1):
if isprime(num-2*(i**2)):
passed = True
break
if passed== False:
return(num)
num+=2
if __name__=="__main__":
start = time.time()
print(main())
end = time.time()
print(end-start) |
77563ef42cd8d7c89249d99b2d31139364b7d806 | neuralfilter/hackerrank | /Coding_Bat/front_backer.py | 230 | 3.75 | 4 | def front_back(str):
if(str == ""):
return ""
temp = str[0]
if(len(str) == 1):
return str
store = list(str)
store[0] = str[len(str) - 1]
store[len(str) - 1] = temp
return "".join(store)
|
55c3182e191d1f525205c038196ea1b60d21d344 | qkleinfelter/AdventOfCode2020 | /Solutions/day5.py | 1,038 | 3.765625 | 4 | def day5():
data = open(r'Inputs\day5.in').readlines()
print('Part 1 result: ' + str(part1(data)))
print('Part 2 result: ' + str(part2(data)))
def part1(data):
# calculate the seatids for every seat in the data and return the maximum
return max(calc_seat_id(line) for line in data)
def part2(data):
# create a set of all the seatids
seats = set(calc_seat_id(line) for line in data)
# 127 rows = 127 * 8 ids
for seatid in range(127 * 8):
# if the seatid isn't in our list
# and both +1 and -1 are in the list,
# we've found our seat
if seatid not in seats and seatid + 1 in seats and seatid - 1 in seats:
return seatid
def calc_seat_id(line):
# Binary counting, F and L are equivalent to 0 and B and R are equivalent to 1
# this handles the row being multiplied by 8 since it is 3 spaces to the left in the binary number
seatid = int(line.replace('F', '0').replace('L', '0').replace('B', '1').replace('R', '1'), 2)
return seatid
day5() |
ec116c05469a42e4d2b148c3dbd8063eaee5cb2c | kevinvkasundra/Naval-Mine-Rock-Classifier | /Sonar.py | 3,973 | 3.5 | 4 | import pandas as pd
from sklearn.model_selection import train_test_split
#file import
path = ""
df = pd.read_csv(path + "sonar_hw1.csv")
df.head()
##### Outlier Analysis #####
#Number of data points
n = df.shape[0]
#missing cases
missing = n - pd.DataFrame(df.count(), columns = ['Missing'])
#outliers below 0
df_low = pd.DataFrame(df[df<0].count(), columns = ['Low outliers'])
#outliers above 1
df_high = pd.DataFrame(df[df>1].count(), columns = ['High outliers'])
#Boolean dataframe where True indicates not an outlier & not missing
df_accept = df[(df>=0) & (df<=1)]
#Minimum for only valid cases
minimum = pd.DataFrame(df_accept.min(), columns = ['Min'])
#Maximum for only valid cases
maximum = pd.DataFrame(df_accept.max(), columns = ['Max'])
#Median for only valid cases
median = pd.DataFrame(df_accept.median(), columns = ['Median'])
# Create list of dataframe names that will be joined into a single dataframe
df_list = [df_low, df_high, minimum, maximum, median]
#Initialize dataframe
dataframe = missing
# loop over the list of dataframes joining them to create a single dataframe
for i in df_list:
dataframe = dataframe.join(i)
print(dataframe)
##### Model fitting #####
X = df.drop(['R41','R46'], axis =1) #Dropping the whole Columns
D = X.dropna() #Dropping the missing value rows
y = D['object']
X = D.drop('object', axis=1) #dropping the target value
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=4)
print ('Train set:', X_train.shape, y_train.shape)
print ('Test set:', X_test.shape, y_test.shape)
# Logistic Regression #
from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression()
logreg.fit(X_train, y_train)
y_pred = logreg.predict(X_test)
print('Accuracy of logistic regression classifier on test set: {:.2f}'.
format(logreg.score(X_test, y_test)))
#Confusion Matrix
from sklearn.metrics import confusion_matrix
confusion_matrix = confusion_matrix(y_test, y_pred)
print(confusion_matrix)
#Precision, Recall, F score
from sklearn.metrics import classification_report
print(classification_report(y_test, y_pred))
#ROC Curve
import matplotlib.pyplot as plt
plt.rc("font", size=14)
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve
logit_roc_auc = roc_auc_score(y_test, logreg.predict(X_test))
fpr, tpr, thresholds = roc_curve(y_test, logreg.predict_proba(X_test)[:,1])
plt.figure()
plt.plot(fpr, tpr, label='Logistic Regression (area = %0.2f)' % logit_roc_auc)
plt.plot([0, 1], [0, 1],'r--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC for Logistic Regression')
plt.legend(loc="lower right")
plt.savefig('Log_ROC')
plt.show()
# SVM #
from sklearn import svm
clf= svm.SVC(kernel='linear',C = 1.0,probability=True, random_state =12345)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print('Accuracy of SVM classifier on test set: {:.2f}'.
format(clf.score(X_test, y_test)))
#Confusion Matrix
from sklearn.metrics import confusion_matrix
confusion_matrix = confusion_matrix(y_test, y_pred)
print(confusion_matrix)
#Precision, Recall, F score
print(classification_report(y_test, y_pred))
#ROC Curve
import matplotlib.pyplot as plt
plt.rc("font", size=14)
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve
logit_roc_auc = roc_auc_score(y_test, clf.predict(X_test))
fpr, tpr, thresholds = roc_curve(y_test, clf.predict_proba(X_test)[:,1])
plt.figure()
plt.plot(fpr, tpr, label='SVM (area = %0.2f)' % logit_roc_auc)
plt.plot([0, 1], [0, 1],'r--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC for SVM')
plt.legend(loc="lower right")
plt.savefig('Log1_ROC')
plt.show()
|
19c20e9197198bf6a926d89050b9a6c720ca98e2 | kshirsagarsiddharth/Algorithms_and_Data_Structures | /Linked_Lists/single_linked_list.py | 6,199 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 4 03:51:02 2020
@author: siddharth
"""
class Node:
#constructor
def __init__(self,data):
self.data = None
self.next = None
# method for setting the data field of the node
def set_data(self,data):
self.data = data
# method for getting data field of the node
def get_data(self):
return self.data
# method for setting next field in the node
def set_next(self,next):
self.next = next
# method for getting next field in the node
def get_next(self):
return self.next
# returns true if the node points to another node
def has_next(self):
return self.next != None
# function to get the length of the list
class LinkedList:
def __init__(self):
self.length = 0
self.head = None
def list_length(self):
current = self.head
count = 0
while current != None:
count = count + 1
current = current.get_next()
return count
def insert_at_beginning(self,data):
new_node = Node(data = None)
new_node.set_data(data)
if self.length == 0:
self.head = new_node
else:
new_node.set_next(self.head)
self.head = new_node
self.length += 1
def insert_at_end(self,data):
new_node = Node(data = None)
new_node.set_data(data)
current = self.head
while current.get_next() != None:
current = current.get_next()
current.set_next(new_node)
self.length += 1
def insert_at_position(self,position,data):
if position > self.length or position < 0:
return None
else:
if position == 0:
self.insert_at_beginning(data)
else:
if position == self.length:
self.insert_at_end(data)
else:
new_node = Node(data = None)
new_node.set_data(data)
count = 0
current = self.head
while count < position - 1:
count += 1
current = current.get_next()
new_node.set_next(current.get_next())
current.set_next(new_node)
self.length += 1
def delete_from_linked_list_beginning(self):
if self.length == 0:
print('The list is empty')
else:
self.head = self.head.get_next()
self.length = -1
def delete_from_linked_list_end(self):
if self.length == 0:
print('the list is empty')
else:
current = self.head
previous = self.head
while current.get_next() != None:
previous = current
current = current.get_next()
previous.set_next(None)
self.length = self.length - 1
def delete_from_linked_list_with_node(self,node):
if self.length == 0:
raise ValueError('List is empty')
else:
current = self.head
previous = None
found = False
while not found:
if current == node:
found = True
elif current is None:
raise ValueError('Node is not in the linked list')
else:
previous = current
current = current.get_next()
if previous is None:
self.head = current.get_next()
else:
previous.set_next(current.get_next())
self.length = self.length - 1
def delete_from_linked_list_with_value(self,value):
if self.length == 0:
raise ValueError('List is empty')
else:
current = self.head
previous = None
found = False
while not found:
if current.get_data() == value:
found = True
elif current is None:
raise ValueError('Node is not in the linked list')
else:
previous = current
current = current.get_next()
if previous is None:
self.head = current.get_next()
else:
previous.set_next(current.get_next())
self.length = self.length - 1
def delete_from_linked_list_with_position(self,position):
if self.length == 0:
raise ValueError('List is Empty')
elif position > self.length + 1 or position < 0:
raise ValueError('Invalid Position')
else:
count = 1
current = self.head
previous = None
while count != position:
previous = current
current = current.get_next()
count+= 1
if previous is None:
self.head = current.get_next()
else:
previous.set_next(current.get_next())
self.length =self.length - 1
node1 = Node(1)
node2 = Node(2)
node3 = Node(3)
node4 = Node(4)
node5 = Node(5)
ll = LinkedList()
ll.addNode(node1)
ll.addNode(node2)
ll.addNode(node3)
ll.addNode(node4)
ll.addNode(node5)
ll.print_list() |
7558d5363e6446ce8184e5689e135f75b5b47968 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2470/60618/312215.py | 780 | 3.65625 | 4 |
T=int(input())
for t in range(0,T):
length=int(input())
matrix=[[0]*length for _ in range(length)]
string=[int(k) for k in input().split()]
res=''
for i in range(0,length):
for j in range(0,length):
matrix[i][j]=string[i*length+j]
res+=' '
res+=str(matrix[i][j])
for i in range(0,length):
for j in range(i,length):
matrix[i][j],matrix[j][i]=matrix[j][i],matrix[i][j]
for i in range(0,length):
for j in range(0,length//2):
matrix[i][j],matrix[i][length-1-j]=matrix[i][length-1-j],matrix[i][j]
res=''
for i in range(0,length):
for j in range(0,length):
res+=' '
res +=str(matrix[i][j])
print(res[1:])
|
23a182151b5e7a2cba472f45c7b0692a269ad4c9 | mitchellvitez/py2hs | /examples/example.py | 1,428 | 3.640625 | 4 | def lessThanOne(x):
if x < 1:
return True
return False
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
def fibonacci2(n):
if n <= 1:
return n
else:
return fibonacci2(n - 1) + fibonacci2(n - 2)
def allPairs(arrA, arrB):
return [(a, b) for a in arrA for b in arrB]
def plusOne(x):
return x + 1
def plusOneLambda():
return lambda x: x + 1
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
def squares(n):
return [x**2 for x in range(1, n)]
def pythagoreanTriples(n):
return [(a, b, c) for a in range(1, n) for b in range(1, n) for c in range(1, n)]
# unsupported
# def matmul(a, b):
# return a @ b
def quadraticFormula(a, b, c):
d = b ** 2 - 4 * a * c
ans1 = (-b - sqrt(d)) / (2 * a)
ans2 = (-b + sqrt(d)) / (2 * a)
return ans1, ans2
# ideas for handling while loops, variable assignment, etc. either purely or via IO
# def divide(x, y):
# count = 1
# while x > 0:
# x -= y
# count += 1
# return count
# divide x y = do
# x <- newIORef x
# y <- newIORef y
# count <- newIORef 1
# whileM (fmap (> 0) (readIORef x)) $ do
# modifyIORef x (-y)
# modifyIORef count (+1)
# readIORef count
# divide2 x y =
# go x 1
# where
# go x count =
# if x > 0
# then go (count + 1) (x - y)
# else count
|
028758603d04d9610caad5ef23cdfe279077a0b4 | softborg/Python_HWZ_Start | /fitness_programm/fit_6.py | 734 | 3.765625 | 4 | # coding=utf8
# Fit 6
def checkio(number: int) -> int:
# Programmier - Aufgabe 6
# Input: Zahl
# Bedingung 1: Multiplizier alle einzlnen Stellen einer Zahl
# Bedingung 2: die 0 soll übersprungen werden
# Output: Zahl Multiplikation aller einzelnen Stellen (Zahlen)
str_number = str(number)
result = 1
for n in str_number:
if n != '0':
result *= int(n)
return result
if __name__ == '__main__':
print('Example:')
print(checkio(123405))
assert checkio(123405) == 120
assert checkio(999) == 729
assert checkio(1000) == 1
assert checkio(1111) == 1
assert checkio(332) == 18
print("Wenn alles korrekt ist, dann wird diese Zeile ausgegeben !")
|
c74427fecf307d22a7d796a24e59a87455cdb388 | Yema94/Python-Projects | /controlstatements/gradecalculator.py | 507 | 4.21875 | 4 | #Grade Calculation
"""Subjects: Maths, Physics, Chemistry
Pass Marks : 35
if Avg <=59 grade C
if Avg <=69 grade B
if Avg >69 grade A """
subjects = input("Enter the names of 3 subjects: ").split()
marks = [float(mark) for mark in input("Enter 3 subjects marks:").split(',')]
if marks[0]>=35 and marks[1]>=35 and marks[2]>=35 :
print( "passed ")
avg = sum(marks)/len(marks)
if avg <=59 : print ("Grade C")
elif avg <=69 : print("Grade B")
else : print ("Grade A")
else : print("Failed!") |
74535ed03e2a6286edf990dcd58ce14ee86f42d9 | Qeswer/info_second | /lab3/lab3.py | 1,742 | 3.734375 | 4 | import re
def first(text): #создаем функцию для первого задания
print("дан текст: ", text)
reg = re.compile('[^а-яА-Я ][^a-zA-Z ]')
text1 = reg.sub('', text)
#text.replace('.')
print(text1)
Broke=text1.split() #разбиваем текст на список слов
k=len(Broke) #длина списка
list_three=[] # создаем список
for i in range(k):
if len(Broke[i])==3:
list_three.append(Broke[i]) # добавляем в новый список все слова с 3-мя буквами
print("слова содержащие 3 буквы: "," ".join(list_three)) #выводим на экран
first(input(str("введите текст: "))) #обращаемся к первому заданию
def second(text_a): #функция для второго задания
print("дан текст: ", text_a)
reg = re.compile('[^a-zA-Z ][^а-яА-Я ]')
text_a = reg.sub('', text_a)
words = text_a.split()#разбиваем предложение на список слов
new = [] #создаем новый список
for i in range(len(words)): #цикл до длины списка
word=words[i][::-1] #переворачиваем слово
new.append(word) #перевернутое слово добавляем в новый список
new.append(str('.')) #добавляем удаленный символ
print("ответ:",'\n', ' '.join(new)) # вывод на экран
second(str(input("введите зашифрованный текст: "))) #обращаемся ко второй функции
input()
|
1f952eb61529beca813f9e3bfcd3c16f929359b4 | roninski/perl2python | /demos/demo6.py | 962 | 3.671875 | 4 | #!/usr/bin/python2.7
import sys
sys.stdout.write (str("Please enter a number: "))
num = raw_input()
num = str(num)[:-1] if str(num)[-1] == '\n' else num
sys.stdout.write (str("\n"))
count = 0
for i in xrange(int(1), int(num)+1):
sys.stdout.write (str("count + i = "))
count = float(count) + float(i)
sys.stdout.write (str(""+str(count)+"\n"))
sys.stdout.write (str(""+str(count)+" divided by "+str(num)+" leaves a remainder of " )+str( float(count) % float(num) )+str( "\n"))
sys.stdout.write (str(""+str(count)+" times "+str(num)+" = " )+str( float(count) * float(num) )+str( "\n"))
sys.stdout.write (str(""+str(count)+" ^ "+str(num)+" = " )+str( float(count) ** float(num) )+str( "\n"))
sys.stdout.write (str(""+str(count)+" divided by "+str(num)+" = " )+str( float(count) / float(num) )+str( "\n"))
for i in xrange(int(1), int(num)+1):
sys.stdout.write (str("count - i = "))
count = float(count) - float(i)
sys.stdout.write (str(""+str(count)+"\n"))
|
00700e20edb6d59eeef27eb25838f077ff19b683 | kwahome/python-escapade | /sort-algorithms/merge_sort.py | 3,714 | 3.921875 | 4 | # -*- coding: utf-8 -*-
#============================================================================================================================================
#
# Author: Kelvin Wahome
# Title: Merge Sort Algorithm
# Project: python-escapade
# Package: sorting-algorithms
#
# Merge sort is a sorting algorithm based on divide and conquer technique.
# With worst-case time complexity being Ο(n log n), it is one of the most respected algorithms.
#
# Algorithm:
# ----------
#
# Merge sort keeps on dividing the list into equal halves until it can no more be divided.
# By definition, if it is only one element in the list, it is sorted.
# Then, merge sort combines the smaller sorted lists keeping the new list sorted too.
#
# Step 1 − if it is only one element in the list it is already sorted, return.
# Step 2 − divide the list recursively into two halves until it can no more be divided.
# Step 3 − merge the smaller lists into new list in sorted order.
#
# Pseudocode:
# ----------
#
# procedure mergesort( var a as array )
# if ( n == 1 ) return a
#
# var l1 as array = a[0] ... a[n/2]
# var l2 as array = a[n/2+1] ... a[n]
#
# l1 = mergesort( l1 )
# l2 = mergesort( l2 )
#
# return merge( l1, l2 )
# end procedure
#
# procedure merge( var a as array, var b as array )
#
# var c as array
#
# while ( a and b have elements )
# if ( a[0] > b[0] )
# add b[0] to the end of c
# remove b[0] from b
# else
# add a[0] to the end of c
# remove a[0] from a
# end if
# end while
#
# while ( a has elements )
# add a[0] to the end of c
# remove a[0] from a
# end while
#
# while ( b has elements )
# add b[0] to the end of c
# remove b[0] from b
# end while
#
# return c
#
# end procedure
#
#============================================================================================================================================
import sys
import operator
def merge(left,right,operator):
"""Function to perform a two way merge"""
if not len(left) or not len(right):
return left or right
merged = []
i, j = 0, 0
while (len(merged) < len(left) + len(right)):
if operator(left[i], right[j]):
merged.append(left[i])
i+= 1
else:
merged.append(right[j])
j+= 1
if i == len(left) or j == len(right):
merged.extend(left[i:] or right[j:])
break
return merged
def merge_sort(sort_list,sorting_order):
"""Recersive merge sort function that divides the list into left and right halves"""
if sorting_order == "asc":
op = operator.lt
elif sorting_order == "desc":
op = operator.gt
if len(sort_list) < 2:
return sort_list
else:
middle = len(sort_list)/2
left_half = merge_sort(sort_list[:middle],sorting_order)
right_half = merge_sort(sort_list[middle:],sorting_order)
return merge(left_half,right_half, op)
def main():
items_list = []
number = input("How many items are in your list? ")
print "\n"
for i in range (1,number+1):
list_item = raw_input("Please enter item "+str(i)+" in your list ")
items_list.append(list_item)
print "\n"
print "Entered list: "
print items_list
print "\n"
valid_order = False
while valid_order != True:
order = raw_input("In what order should the list be sorted? (Asc/Desc) ")
print "\n"
if order.lower() == "asc" or order.lower() == "desc":
valid_order = True
if order.lower() == "asc":
order_name = "ascending"
elif order.lower() == "desc":
order_name = "descending"
print "Sorted list in " + order_name + " order:"
print merge_sort(items_list,order.lower())
print "\n"
if __name__ == "__main__":
try:
sys.exit(main())
except Exception:
print "An error has occured"
|
8f67794f6339985c6e883b4dbf29ef3cf2f31d65 | stephen-hansen/Advent-of-Code-19 | /p1/p1-1.py | 240 | 3.6875 | 4 | #!/usr/bin/env python3
import math
with open("p1-input") as f:
inputs = f.read().splitlines()
numbers = [ int(x) for x in inputs ]
total = 0
for number in numbers:
fuel = math.floor(number/3) - 2
total += fuel
print(total)
|
f09e4c276f74aa1b12c44d1a877bd9dc66dc3340 | colombelli/biocomp | /list 4/part 2/submitted/e4-2/implementation1/genetic_means.py | 9,352 | 3.90625 | 4 | """
@Title: Genetic Means
@Author: Felipe Colombelli
@Description: A genetic algorithm using k-means as classification model
for selecting genes out of a dataset with two types of
leukemia: ALL and AML.
* Chromosome encoding:
An 1D array with zeros and ones representing what gene is being considered.
e.g.
Lets consider 5 genes;
The 2nd and 4th are being considered;
The corresponding chromosome would be represented by the array:
[0, 1, 0, 1, 0]
* Fitness function rationale:
Because our objective is to find the minimum amount of genes that explain our
data, we will use a fitness function based on the model accuracy AND the number
of genes.
We will start our rationale from the following idea:
Fitness = Accuracy - Number of genes
Because the number of genes is ranged from 0 to 7128, the number of genes would
take much more importance, so we normalize it mapping the values to range between
0 and 100 using the following formula:
100 * (number of genes - min) / (max - min), where min = 0, and max = 7128
100 * (number of genes) / 7128
Now, Fitness = Accuracy - Normalized number of genes
We still want our model to prioritize the accuracy. Lets assume, for instance,
that an accuracy below or equal to 90% is utterly trash. Indeed, this claim is
based on the 98.6% accuracy got from the model using all the features.
To treat those accuracies as bad configurations, we will penalize them shifting
the numbers to the interval [-100, -10].
If accuracy < 90:
accuracy = accuracy - 100
Finally, we will boost up gains in accuracy to tell the algorithm that even if it
could reduce features, just do so by means of the Computer Science magic scale: log2.
In other words, we will tell that gains in accuracy are log2 more valuable.
If accuracy < 90:
accuracy = accuracy - 100
accuracy = accuracy * -log2(-accuracy)
Else:
accuracy = accuracy * log2(accuracy)
The final fitness function then goes as:
Fitness = Modified accuracy - Normalized number of genes
"""
import pandas as pd
import numpy as np
import random
import multiprocessing as mp
from sklearn.cluster import KMeans
from math import log2
import pickle
import os.path
import csv
NUM_OF_GENES = 7128
class GeneticMeans():
def __init__(self, df, dfLabels, populationSize=50, iterations=100,
mutationRate=0.2, elitism=0.3):
self.df = df
self.dfLabels = dfLabels
self.populationSize = populationSize
self.iterations = iterations
self.mutationRate = mutationRate
self.elitism = elitism
self.fitness = []
self.population = []
def evolve(self):
self.__generatePopulation()
self.__computeFitness()
bestIdx = np.argmax(self.fitness)
bestIndividualPrev = self.population[bestIdx]
greaterScoreFound = np.amax(self.fitness)
generation = 1
while generation <= self.iterations:
if (self.fitness[bestIdx] > greaterScoreFound):
greaterScoreFound = np.amax(self.fitness)
np.savetxt("best_genetic.txt", bestIndividualPrev)
self.__printIterationStatus(generation, bestIdx, greaterScoreFound)
self.__selectPopulation()
self.__crossPopulation()
self.__computeFitness()
generation += 1
bestIdx = np.argmax(self.fitness)
bestIndividual = self.population[bestIdx]
bestIndividualPrev = bestIndividual
print("Max generations reached. Learning algorithm stopped.")
return
def __printIterationStatus(self, generation, bestIdx, greaterScoreFound):
bestIndividual = self.population[bestIdx]
bestScore = self.fitness[bestIdx]
bestAccuracy = self.calculateAccuracy(bestIndividual)
numGenesBestIndividual = np.sum(bestIndividual)
print("\n\nGeneration:", generation)
print("Best score among the population:", bestScore)
print("Greater score found among generations:", greaterScoreFound)
print("Accuracy of the best individual:", bestAccuracy)
print("Number of genes of the best individual:", numGenesBestIndividual)
print("\n\n")
self.__dumpResults(generation, bestIndividual, bestScore, bestAccuracy, numGenesBestIndividual)
return
def __dumpResults(self, generation, bestIndividual, bestScore, bestAccuracy, numGenesBestIndividual):
with open('ga_pop.pkl', 'wb') as pop_file:
pickle.dump(self.population, pop_file)
with open('ga_best_individual.pkl', 'wb') as best:
pickle.dump(bestIndividual, best)
with open('ga_info.csv', "a", newline='') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
writer.writerow([generation, bestScore, bestAccuracy, numGenesBestIndividual])
def __generatePopulation(self):
self.population = np.array([
[bool(random.getrandbits(1)) for i in range(NUM_OF_GENES)]
for i in range(self.populationSize)])
return
def __computeFitness(self):
self.fitness = [None] * len(self.population)
pool = mp.Pool(mp.cpu_count())
self.fitness = np.array([pool.apply(self.computeIndividualFitness, args=(individual, ))
for individual in self.population])
pool.close()
return
# The three next methods (and also another ones from this file)
# violate the information hiding principles because of pickling
# issues bothering the parallel computation
def computeIndividualFitness(self, individual):
accuracy = self.calculateAccuracy(individual)
if accuracy < 90:
accuracy = accuracy - 100
accuracy = -log2(-accuracy) * accuracy
else:
accuracy = accuracy * log2(accuracy)
numOfSelectedGenes = np.sum(np.array(individual))
normNumOfSelectedGenes = 100 * (numOfSelectedGenes) / 7128
fitness = accuracy - normNumOfSelectedGenes
return fitness
def calculateAccuracy(self, individual):
kmeans = KMeans(n_clusters=2, n_init=25)
reducedDF = self.df[self.df.columns[individual]]
kmeans.fit(reducedDF)
predictedLabels = kmeans.predict(reducedDF)
# Because there's no way to know which cluster will be assigned to each class
realLabels_01 = self.convertLabelsTo01(0, 1)
realLabels_10 = self.convertLabelsTo01(1, 0)
rigthGuesses01 = (np.array(realLabels_01) == predictedLabels)
rigthGuesses10 = (np.array(realLabels_10) == predictedLabels)
rigthGuesses = max(np.sum(rigthGuesses01), np.sum(rigthGuesses10))
numSamples = len(self.dfLabels)
numRigthGuesses = np.sum(rigthGuesses)
accuracy = numRigthGuesses / numSamples * 100
return accuracy
def convertLabelsTo01(self, ALL, AML):
realLabels_01 = []
for label in list(self.dfLabels):
if label == 'ALL':
realLabels_01.append(ALL)
elif label == 'AML':
realLabels_01.append(AML)
return realLabels_01
def __selectPopulation(self):
numElite = round(self.elitism * self.populationSize)
# Get the index of the N greatest scores:
eliteIdx = np.argpartition(self.fitness, -numElite)[-numElite:]
elite = self.population[eliteIdx]
self.population = elite
return
def __crossPopulation(self):
missingPopulation = []
numMissingIndividuals = self.populationSize - len(self.population)
mask = np.random.randint(0, 2, size=self.population.shape[1])
# mask example for a problem with 5 genes [0,1,1,0,1]
# meaning that dad0 passes its first gene, da1 its second, and so on...
for _ in range(numMissingIndividuals):
dad0Idx = np.random.randint(0, len(self.population))
dad1Idx = np.random.randint(0, len(self.population))
dad0 = self.population[dad0Idx]
dad1 = self.population[dad1Idx]
son = []
for i, gene in enumerate(mask):
if gene == 0:
son.append(dad0[i])
else:
son.append(dad1[i])
son = np.array(son)
missingPopulation.append(son)
missingPopulation = np.array(missingPopulation)
missingPopulation = self.__mutatePopulation(missingPopulation)
self.population = np.append(self.population, missingPopulation, axis=0)
return
def __mutatePopulation(self, missingPopulation):
mutationPercentage = self.mutationRate*100
for individual in missingPopulation:
for gene in range(len(individual)):
rand = np.random.randint(0, 101)
if self.__mustMutate(rand, mutationPercentage):
individual[gene] = ~individual[gene]
return missingPopulation
def __mustMutate(self, rand, mutation):
return rand <= mutation |
3d38791badbf61e176e03a97a3004c15c1f6d28f | KrishnaManaswiD/Tortoises | /code/test/old/FridayDemo2.py | 1,368 | 3.875 | 4 | from tortoise import Tortoise
from enums import Direction, SensorType
# In this version, they test the robot first and then fix the values and fill in the else. If format is good, but too much work, then prefill else.
# Change this to 1 when you've calibrated and have some values for not enough light, good light and too much light.
calibrated = 0;
# Name your tortoise here.
Name = Tortoise()
if (calibrated==0):
print "Let's use different levels of light to see what calibrated readings we get"
raw_input("First let's see what the room gives us, press enter when you're done")
print Name.getSensorData(SensorType.light,1)
raw_input("Now try it with a light source right up close and press enter when you're done")
print Name.getSensorData(SensorType.light,1)
raw_input("And now try somewhere in the middle")
print Name.getSensorData(SensorType.light,1)
while True and (calibrated==1):
# First we need a reading from the light sensor
lightSensorReading = Name.getSensorData(SensorType.light,1)
# Can you tune the light sensor values for the conditions based on your calibration findings?
if lightSensorReading < 1:
Name.moveForward(30, Direction)
print "Where's the light?"
elif 1<= lightSensorReading and lightSensorReading <2:
print "Found the light!"
Name.moveBackward(30)
else:
print "Argh! Too much light!"
Name.doRandomStep()
|
fb9b40a38862f6d05595fa6032de47fe84de7e9f | t4d-classes/python_03222021_afternoon | /language_demos/fibonacci.py | 595 | 3.75 | 4 | import itertools
# 0 1 1 2 3 5 8 (num_1) 13 (num_2) 21 (next_num)
def fibonacci():
num_1 = 0
num_2 = 1
yield 0, num_1
while True:
next_num = num_1 + num_2
yield num_2, next_num
num_1 = num_2
num_2 = next_num
fib_gen = fibonacci()
print(fib_gen)
# print(next(fib_gen))
# print(next(fib_gen))
# print(next(fib_gen))
# print(next(fib_gen))
# print(next(fib_gen))
# print(next(fib_gen))
for prev_num, num in itertools.islice(fib_gen, 0, 10000):
# print(num, float(num) / float(prev_num) if prev_num > 0 else "no ratio")
print(num)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.