blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
560052bb91cf1aca14094545b33836aaca488d99 | okoks9011/problem_solving | /leetcode/1203.2.py | 1,830 | 3.5 | 4 | import enum
class Color(enum.Enum):
WHITE = 0
GRAY = 1
BLACK = 2
class Solution:
def topological_sort(self, adjs):
n = len(adjs)
visited = [Color.WHITE] * n
order = []
def dfs(u):
visited[u] = Color.GRAY
for v in adjs[u]:
if visited[v] == Color.BLACK:
continue
elif visited[v] == Color.GRAY:
return False
if not dfs(v):
return False
visited[u] = Color.BLACK
order.append(u)
return True
for s in reversed(range(n)):
if visited[s] == Color.BLACK:
continue
assert visited[s] == Color.WHITE
if not dfs(s):
return None
return order
def sortItems(self, n: int, m: int, group: List[int], before_items: List[List[int]]) -> List[int]:
def get_innode(i):
return n + 2 * i
def get_outnode(i):
return n + 2 * i + 1
adjs = [[] for _ in range(n + 2 * m)]
for i, gi in enumerate(group):
if gi == -1:
continue
adjs[get_innode(gi)].append(i)
adjs[i].append(get_outnode(gi))
for i, befores in enumerate(before_items):
gi = group[i]
for b in befores:
gb = group[b]
if gi == gb:
adjs[i].append(b)
else:
from_node = get_outnode(gi) if gi != -1 else i
to_node = get_innode(gb) if gb != -1 else b
adjs[from_node].append(to_node)
result = self.topological_sort(adjs)
if result is None:
return []
return [x for x in result if x < n]
|
77ef8052781bcd56e622b45dfdcc2da2c3524f38 | Zahidsqldba07/CodeFights-9 | /Arcade/Intro/Level 12/spiralNumbers/code.py | 878 | 3.625 | 4 | def spiralNumbers(n):
square = [[0] * n for _ in xrange(n)]
counter = 1
direction = 0
x = 0
y = 0
X = n
Y = n
while counter <= n ** 2:
if direction == 0:
square[y][x] = counter
x += 1
if direction == 1:
square[y][x] = counter
y += 1
if direction == 2:
square[y][x] = counter
x -= 1
if direction == 3:
square[y][x] = counter
y -= 1
counter += 1
if direction == 0 and square[y][(x + 1) % n]:
direction = 1
if direction == 1 and square[(y + 1) % n][x]:
direction = 2
if direction == 2 and square[y][x - 1]:
direction = 3
if direction == 3 and square[y - 1][x]:
direction = 0
return square
|
3d245ef51a40e87dfe98125eaecc997509101ff7 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/anagram/3df5a510fb9543bb8e42ee8cdabff50d.py | 274 | 3.609375 | 4 | from collections import Counter
def detect_anagrams(word, candidates):
word_lower = word.lower()
word_counter = Counter(word_lower)
def pred(c):
return Counter(c) == word_counter and c != word_lower
return [c for c in candidates if pred(c.lower())]
|
4e3146b35b47e3e5723436e27936145f75bbc288 | hycap-academy/sailbot | /bearing.py | 3,234 | 3.53125 | 4 | import math
import py_qmc5883l
from time import sleep
from gps import *
import time
import RPi.GPIO as GPIO
import time
#Tahlequah Vashon Island
long1 = -122.516422
lat1 = 47.355398
tolerancelat = .00001
toleranellong = .00001
#houselat = 47.342257833
#houselong = -122.326749667
gpsd = gps(mode=WATCH_ENABLE|WATCH_NEWSTYLE)
sensor = py_qmc5883l.QMC5883L()
def calculate_initial_compass_bearing(pointA, pointB):
"""
Calculates the bearing between two points.
The formulae used is the following:
θ = atan2(sin(Δlong).cos(lat2),
cos(lat1).sin(lat2) − sin(lat1).cos(lat2).cos(Δlong))
:Parameters:
- `pointA: The tuple representing the latitude/longitude for the
first point. Latitude and longitude must be in decimal degrees.
This should be the current location
- `pointB: The tuple representing the latitude/longitude for the
second point. Latitude and longitude must be in decimal degrees.
This should be the target location.
:Returns:
The bearing in degrees
:Returns Type:
float
"""
if (type(pointA) != tuple) or (type(pointB) != tuple):
raise TypeError("Only tuples are supported as arguments")
lat1 = math.radians(pointA[0])
lat2 = math.radians(pointB[0])
diffLong = math.radians(pointB[1] - pointA[1])
x = math.sin(diffLong) * math.cos(lat2)
y = math.cos(lat1) * math.sin(lat2) - (math.sin(lat1)
* math.cos(lat2) * math.cos(diffLong))
initial_bearing = math.atan2(x, y)
# Now we have the initial bearing but math.atan2 return values
# from -180° to + 180° which is not what we want for a compass bearing
# The solution is to normalize the initial bearing as shown below
initial_bearing = math.degrees(initial_bearing)
compass_bearing = (initial_bearing + 360) % 360
return compass_bearing
def atTarget(pointA, pointB):
if abs(pointA[0]-pointB[0]) < tolerancelat and abs(pointA[1]-pointB[1]) < tolerancelong:
return True
else:
return False
#while atTarget == False:
m = sensor.get_magnet()
report = gpsd.next()
while report['class'] != 'TPV':
report = gpsd.next()
if report['class'] == 'TPV':
cur_long = float(getattr(report,'lon',0.0))
cur_lat = float(getattr(report,'lat',0.0))
print(atTarget((lat1,long1), (cur_lat, cur_long)))
while atTarget((lat1,long1), (cur_lat, cur_long)) == False:
m = sensor.get_magnet()
report = gpsd.next()
if report['class'] == 'TPV':
heading = sensor.get_bearing()
cur_long = float(getattr(report,'lon',0.0))
cur_lat = float(getattr(report,'lat',0.0))
projectedHeading = calculate_initial_compass_bearing((cur_lat,cur_long), (lat1, long1))
necessarychange = projectedHeading-heading
print(projectedHeading, heading, necessarychange)
#print(projectedHeading)
#print(heading)
#print(necessarychange)
if necessarychange >= 10:
print("goLeft()")
elif necessarychange <= -10:
print("goRight()")
else:
print("goStraight()")
time.sleep(.1)
#stop()
time.sleep(.1)
|
b99985c1d8ae7807faf49e5cb2179550f69515bc | DaveZima/PycharmProjects | /tkinter/tkinter_menu.py | 2,353 | 3.96875 | 4 | #def example2():
root.title("Dave is Great")
user_name = tk.StringVar()
name_label = ttk.Label(root,text="Name: ")
name_label.pack(side="left",padx=(0,10)) # add 10 pixel spacing
name_entry = ttk.Entry(root, width=15, textvariable=user_name)
name_entry.pack(side="left")
name_entry.focus()
greet_button = ttk.Button(root,text="Greet",command=greet)
greet_button.pack(side="left",fill="x",expand=True)
def example3():
root = tk.Tk()
# side = anchor point
# fill x=horizontal y=vertical both=x+y
# container considers multiple element relationships,priorities
# expand - request as much space as possible
tk.Label(root, text="Label 1", bg="green").pack(side="left", fill="both", expand=True)
tk.Label(root, text="Label 2", bg="red").pack(side="top")
root.mainloop()
def example4():
root = tk.Tk()
# Create a frame to better manage the labels
# Frame becomes the first element in the root
# Element interaction for the 3rd label is now with the frame
main = ttk.Frame(root)
# pack is an algorithm for component/element interaction
# it is a TKinter geometry manager
main.pack(side="left", fill="both", expand=True)
# place the first two labels in the frame
tk.Label(main, text="Label top", bg="red").pack(side="top", fill="both", expand=True)
tk.Label(main, text="Label top", bg="red").pack(side="top", fill="both", expand=True)
tk.Label(root, text="Label left", bg="green").pack(
side="left", expand=True, fill="both"
)
root.mainloop()
def greet():
# user_name has global scope
# or expression within f variable
print(f"Hello {user_name.get() or 'World'}") # user_name is global
########
# main #
########
root = tk.Tk()
# Create a frame to better manage the labels
# Frame becomes the first element in the root
# Element interaction for the 3rd label is now with the frame
main = ttk.Frame(root)
# pack is an algorithm for component/element interaction
main.pack(side="left", fill="both", expand=True)
# place the first two labels in the frame
tk.Label(main, text="Label top", bg="red").pack(side="top", fill="both", expand=True)
tk.Label(main, text="Label top", bg="red").pack(side="top", fill="both", expand=True)
tk.Label(root, text="Label left", bg="green").pack(
side="left", expand=True, fill="both"
)
root.mainloop()
|
a81bfee5a4e3b152acfa8e5c64c53fbf2a2c61a1 | Ziang-Lu/Design-Patterns | /4-Behavioral Patterns/2-Strategy Pattern/Customer Billing Example/Python/strategy_pattern_test.py | 2,712 | 4.21875 | 4 | #!usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Application that actually uses Strategy Pattern to provide multiple algorithms,
a family of algorithms, to perform a specific task (solve a specific problem),
so that the client can select which actual implementation to use at runtime.
"""
__author__ = 'Ziang Lu'
from billing_strategy import (
BillingStrategy, HappyHourBillingStrategy, NormalBillingStrategy
)
class Customer:
"""
Customer class that works as an interface to the outside world: it wraps a
billing strategy and the client will use that strategy to calculate the
actual prices for drinks.
"""
__slots__ = ['_curr_billing_strategy', '_rounds']
def __init__(self, billing_strategy: BillingStrategy):
"""
Constructor with parameter.
:param billing_strategy: BillingStrategy
"""
self._curr_billing_strategy = billing_strategy
self._rounds = []
def set_billing_strategy(self, billing_strategy: BillingStrategy) -> None:
"""
Mutator of curr_billing_strategy.
:param billing_strategy: BillingStrategy
:return: None
"""
self._curr_billing_strategy = billing_strategy
def add_drink(self, price: float, n: int) -> None:
"""
Adds the given number of the given drinks.
:param price: float
:param n: int
:return: None
"""
self._rounds.append(
self._curr_billing_strategy.get_actual_price(price * n)
)
def print_bill(self) -> None:
"""
Prints the total bill for this customer
:return: None
"""
total = sum(self._rounds)
print(f'Total due: {total}')
self._rounds.clear()
def main():
# Prepare billing strategies
normal_strategy = NormalBillingStrategy.get_instance()
happy_hour_strategy = HappyHourBillingStrategy.get_instance()
# Normal time slot
first_customer = Customer(normal_strategy)
first_customer.add_drink(price=1.0, n=1)
# Happy Hour starts! [Switch billing strategy]
first_customer.set_billing_strategy(happy_hour_strategy)
first_customer.add_drink(price=1.0, n=2)
second_customer = Customer(happy_hour_strategy)
second_customer.add_drink(price=0.8, n=1)
# First customer checks out
first_customer.print_bill()
# Happy Hour ends [Switch billing strategy]
second_customer.set_billing_strategy(normal_strategy)
second_customer.add_drink(price=1.3, n=1)
second_customer.add_drink(price=2.5, n=1)
# Second customer checks out
second_customer.print_bill()
if __name__ == '__main__':
main()
# Output:
# Total due: 2.0
# Total due: 5.5
|
c9e8f888f2f3a03c53a5a8786266b31f4b2ddee7 | byAbaddon/Basics-Course-Python-March-2020 | /4.0 Loops/10-oddEvenSum.py | 409 | 3.78125 | 4 | #oddEvenSum
loop = int(input())
even_sum = 0
odd_sum = 0
list_num = []
while loop > 0 :
list_num.append(int(input()))
loop -= 1
for i in range(len(list_num)):
if i % 2 == 0:
even_sum += list_num[i]
else:
odd_sum += list_num[i]
if even_sum == odd_sum:
print(f'Yes\nSum = {even_sum}')
else:
print(f'No\nDiff = {abs(even_sum - odd_sum)}')
# 4, 10, 50, 60, 20 //yes |
8302f3270037e850344f99ebc8187d79c787ef43 | ZhengLiangliang1996/LeetcodePyVersion | /MaxArea.py | 758 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 8 17:07:57 2019
@author: liangliang
"""
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
#https://www.youtube.com/watch?v=wLo0xIRDjQc
res = 0
l = 0
r = len(height) - 1
while(l < r):
# choose the lowest height (mu tong yuan li)
res = max(res, min(height[l], height[r]) * (r - l))
# moving l or r
if height[l] < height[r]:
l = l + 1
else:
r = r - 1
return res
S = Solution()
height = [1,8,6,2,5,4,8,3,7]
print(S.maxArea(height))
|
6a8a6096fab33bc3bcb3015586a50f3610aa47e7 | jmcgee5/python-challenge | /PyBank/main.py | 1,849 | 3.53125 | 4 |
# First we'll import the os module
# This will allow us to create file paths across operating systems
import os
# Module for reading CSV files
import csv
print(os.path.dirname(__file__))
os.chdir(os.path.dirname(__file__))
csvpath = os.path.join("..", "Resources", "budget_data.csv")
print("Financial Analysis")
print("-----------------------------------")
with open(csvpath, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csv_header = next(csvfile)
months = []
for row in csvreader:
months.append(row[0])
print(f"Total Months: {len(months)}")
with open(csvpath, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csv_header = next(csvfile)
profits_losses = []
for row in csvreader:
profits_losses.append(int(row[1]))
print(f"Total Net Amount: ${sum(profits_losses)}")
with open(csvpath, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csv_header = next(csvfile)
revenue = []
date = []
rev_change = [0]
for row in csvreader:
revenue.append(float(row[1]))
date.append(row[0])
for i in range(1,len(revenue)):
rev_change.append(revenue[i] - revenue[i-1])
avg_rev_change = sum(rev_change)/(len(rev_change)-1)
max_rev_change = max(rev_change)
min_rev_change = min(rev_change)
max_rev_change_date = str(date[rev_change.index(max(rev_change))])
min_rev_change_date = str(date[rev_change.index(min(rev_change))])
print("Avereage Change: $", round(avg_rev_change))
print("Greatest Increase in Revenue:", max_rev_change_date,"($", max_rev_change,")")
print("Greatest Decrease in Revenue:", min_rev_change_date,"($", min_rev_change,")")
|
30fbb12dbfda8bdc3a56f15a11b3da44a74f7f41 | bwigianto/two-player-zero-sum | /test_tictactoe.py | 2,032 | 3.59375 | 4 | import unittest
from tictactoe import *
class TestTictatoe(unittest.TestCase):
def test_next_player(self):
board = Board()
self.assertEqual(board.next_player(1), 2)
self.assertEqual(board.next_player(2), 1)
def test_gets_next_state_for_p1(self):
board = Board()
expected = [['_', '_', '_'], ['_', 1, '_'], ['_', '_', '_']]
self.assertEqual(board.next_state(1, board.start(), (1, 1)), expected)
def test_gets_next_state_for_p2(self):
board = Board()
start = [['_', '_', '_'], [2, '_', '_'], ['_', '_', '_']]
expected = [['_', '_', '_'], [2, 1, '_'], ['_', '_', '_']]
self.assertEqual(board.next_state(1, start, (1, 1)), expected)
def test_finds_legal_plays_at_start(self):
board = Board()
legal_moves = [(x, y) for x in range(3) for y in range(3)]
self.assertEqual(board.legal_actions([board.start()]), legal_moves)
def test_finds_legal_moves_in_middle(self):
board = Board()
start = [[2, 1, 2], ['_', 1, '_'], [1, 2, 2]]
legal_moves = [(1, 0), (1, 2)]
self.assertEqual(board.legal_actions([start]), legal_moves)
def test_finished(self):
board = Board()
start = [[2, 1, 2], ['_', 1, '_'], [1, 1, 2]]
self.assertTrue(board.finished(start))
def test_not_finished(self):
board = Board()
start = [[2, 1, 2], ['_', 1, '_'], [1, 2, 2]]
self.assertFalse(board.finished(start))
def test_finds_winner(self):
board = Board()
start = [[2, 1, 2], ['_', 1, '_'], [1, 1, 2]]
self.assertEqual(board.winner(start), 1)
def test_finds_draw(self):
board = Board()
start = [[2, 1, 2], [2, 1, 1], [1, 2, 2]]
self.assertEqual(board.winner(start), 0)
def test_not_finished_returns_negative(self):
board = Board()
start = [[2, 1, 2], ['_', 1, '_'], [1, 2, 2]]
self.assertEqual(board.winner(start), -1)
if __name__ == '__main__':
unittest.main()
|
19db2307169609e933e9abe03ffa9ce1ffb9e21f | kaiyaprovost/algobio_scripts_python | /lab9_sort.py | 3,100 | 4.125 | 4 | def getInputList():
"""
No inputs
Returns the list to sort
"""
s = raw_input("Please enter a list of ints, separated by spaces: ")
a = [int(w) for w in s.split()]
return a
def getInputFirstN(n):
"""
Input N, output numbers 0 to n-1
Returns the list to sort
"""
aList = [i for i in range(0,n)]
return aList
def getInputRevN(n):
"""
Input N, output numbers n-1 to 0
Returns the list to sort
"""
aList = [i for i in range(n-1,-1,-1)]
#print aList
return aList
def getInputRandN(n,a,b):
"""
Input N,A,B output N numbers between A and B such that a<= number <= B
Returns the list to sort
"""
import random
aList = [random.uniform(a,b) for i in range(0,n)]
#print aList
return aList
def sortList(aList):
"""
Takes a list and sorts it in place with selection sort
"""
#For each i, starting at len(aList)-1 and decrementing to 1.
for i in range(len(aList)-1,0,-1):
#Find the index of the largest element in the list aList[0:i+1]
maxNum = max(aList[0:i+1])
maxPos = aList.index(maxNum)
#Swap the largest element with the element at position i.
aList[maxPos],aList[i] = aList[i],aList[maxPos]
def printList(b):
"""
Prints sorted list.
No outputs
"""
#print "The sorted list is:"
#print b
def mergeSort(array):
"""
Takes a list and sorts it in place with merge sort
"""
n = len(array)
if n > 1:
mid = n//2
left = array[:mid]
right = array[mid:]
mergeSort(left)
mergeSort(right)
i=0
j=0
k=0
while i < len(left) and j < len(right):
if left[i] < right[j]:
array[k]=left[i]
i += 1
else:
array[k]=right[j]
j += 1
k += 1
while i < len(left):
array[k]=left[i]
i += 1
k += 1
while j < len(right):
array[k]=right[j]
j += 1
k += 1
return array
def sortListInsert(a):
"""
Takes a list and sorts it in place with insertion sort
"""
for i in range(1,len(a)):
j = i
while j > 0 and a[j-1] > a[j]:
a[j],a[j-1] = a[j-1],a[j]
j += -1
def main():
#print "Welcome to the sorting program!"
#Get list of items to sort.
#a = getInputList()
#Get first N numbers to sort
#a = getInputFirstN(100)
#Get first N numbers in reverse order to sort
#a = getInputRevN(100)
#Get N random numbers between A and B
a = getInputRandN(10000,0,10)
#Sort list with selection sort.
#sortList(a)
#Sort list with merge sort.
#a = mergeSort(a)
#Sort list with insertion sort.
sortListInsert(a)
#Print sorted list
printList(a)
if __name__ == "__main__":
main()
|
8ceb90a68a837294dc0f05b5f5937cad675ed87f | zhaobe/ml-with-python | /3_dog_id.py | 618 | 3.546875 | 4 | import numpy as np
import matplotlib.pyplot as plt
# 1000 dog population
retrievers = 500
greyhound = 500
# avg height (in) with +/- 2 inches
h_retrievers = 22 + 2 * np.random.randn(retrievers)
h_grey = 24 + 2 * np.random.randn(greyhound)
# create histogram
plt.hist([h_retrievers, h_grey], stacked=True, color=['r','y'])
plt.show()
# height is bad feature
# eye color is bad feature
# avoid useless features
# independent features are best
# avoid redundant features
# features should be easy to understand
# simpler relationships are easier to learn
'''
---ideal---
1. informative
2. independent
3. simple
'''
|
8de7af3fbc82c8d5277257ef53ad7f51ff8d5e6c | li3meng20/Louplus | /jump7.py | 270 | 3.65625 | 4 | Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>for i in range(1,101):
if i % 7==0 or i%10==7 or i//10==7:
continue
print(i)
|
9f4bb5d3d0f15436523489c711bce18587fabb81 | Jamie-Chang/advent2019 | /d6/main.py | 1,268 | 3.546875 | 4 | from __future__ import annotations
from collections import defaultdict
from typing import Iterator, Final
COM: Final[str] = "COM"
def read() -> Iterator[tuple[str, str]]:
with open("d6/input.txt") as f:
for l in f:
yield tuple(l.rstrip().split(")"))
def build_tree(orbits: Iterator[tuple[str, str]]) -> dict[str, set[str]]:
tree: dict[str, set[str]] = defaultdict(set)
for orbitee, orbiter in orbits:
tree[orbitee].add(orbiter)
tree[orbiter].add(orbitee)
return tree
def count_orbits(tree: dict[str, set[str]], start: str = COM) -> int:
queue = [(start, 0)]
total = 0
while queue:
planet, orbit_no = queue.pop(0)
total += orbit_no
queue.extend((p, orbit_no + 1) for p in tree[planet])
return total
def count_transfers(tree: dict[str, set[str]], start: str = "YOU") -> int:
visted = set()
queue = [(start, 0)]
total = 0
while queue:
planet, orbit_no = queue.pop(0)
if planet == "SAN":
return orbit_no - 2
visted.add(planet)
queue.extend((p, orbit_no + 1) for p in tree[planet] if p not in visted)
return total
if __name__ == "__main__":
tree = build_tree(read())
print(count_transfers(tree))
|
326c86c95c1cc22be94cd3a8b74abe3216e355ef | JeeZeh/kattis.py | /Solutions/no_duplicates.py | 243 | 3.609375 | 4 | words = list(map(str, input().split(" ")))
size = len(words)-1
dupe = False
for i in range(0, size):
word = words[i]
words[i] = ""
if word in words:
dupe = True
break
if dupe:
print("no")
else:
print("yes") |
e43b7d8d40f85666c6f55127d7c2103b9a8de9bd | RyanGriffith/movie_fundraiser | /02_ticket_loop_v2.py | 521 | 4.15625 | 4 | # start of loop
# initialise loop so that it runs at least once
name = " "
count = 0
MAX_TICKETS = 5
while name != "xxx" and count < MAX_TICKETS:
print("You have {} seats left ".format(MAX_TICKETS - count))
# get details
name = input("name: ")
count += 1
print()
if name == "xxx":
count -= 1
if count == MAX_TICKETS:
print("You have sold all available tickets!")
else:
print("You have sold {} tickets. There are still {} places available".format(count, MAX_TICKETS - count))
|
5036afd46747be7ffeb3246d8730b94eb9f840b6 | biswasSaumyadip/Code-Daily | /Age_o_number_conversion.py | 374 | 4.125 | 4 | def age_calculation (age_number,days_in_a_year = 365):
return age_number * days_in_a_year
age = input("Enter your age: ")
while int(age) <0:
print("Error! Please enter appropriate age.")
age = input("Enter your age: ")
if int(age) >0:
break
if int(age) >0:
age_criteria = age_calculation(int(age),days_in_a_year=365)
print(age_criteria)
|
35cf59a09362c44bcf0e412ce17ab9416ebbf606 | vishakhagpt29/Recommender | /club_genre.py | 436 | 3.5 | 4 | from category import category
#clubs movies on the basis of their genre, genreates genre_movie dictionary
def club_genre():
temp_data = {}
for k in category:
x = category[k]
for index, item in enumerate(x):
if item in temp_data:
temp_data[item].append(k)
else:
temp_data[item] = [k]
print temp_data.keys()
if __name__ == "__main__":
club_genre()
|
b37ff6081b8f9c8e4c4c5292c42ae86e32eb45cd | ozzieliu/Metis-DataScience-Prework | /python/q8_parsing.py | 1,934 | 4.53125 | 5 | # -*- coding: utf-8 -*-
# The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.
import csv
# Open the given file to read and return a list of tuples
def read_data(data):
with open(data, 'rb') as csvfile:
reader = csv.reader(csvfile)
# Ignore the first line header in the csv file
next(reader)
# Store the read csv data into a list of tuples. Each tuple represent 1 line.
return map(tuple, reader)
# Takes an input of the read data, and return the team index with the smallest difference
# I take it that the "smallest difference" in score differential means that the for and against are closest,
# not that there is the lowest or worst differential
def get_min_score_difference(parsed_data):
# Set team index and score difference variables to the data in the first team in the file.
team_index = 0
smallest_difference = abs(int(parsed_data[0][5])-int(parsed_data[0][6]))
# Iterate through the other teams to see which team is worse.
for team in parsed_data:
difference = abs(int(team[5])-int(team[6]))
if difference < smallest_difference:
smallest_difference = difference
team_index = parsed_data.index(team)
return get_team(team_index, parsed_data)
# Given the index value of the team in the parsed data, return the team name
def get_team(index_value, parsed_data):
return parsed_data[index_value][0]
# Main function area to call the functions.
football = read_data('football.csv')
print get_min_score_difference(football)
|
5a71f3d831fa0f39513174df587892dbb43c5547 | sofia-russmann/Python-Practise | /3/probando_index.py | 162 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 23 19:51:08 2020
@author: sofia.russmann
"""
n = [1, 3, 5, 7]
m = n.index(3)
p = n[0]
print(n)
print(m)
print(p)
|
e754334a70b15bf730e563f30824f7fd8aad165f | rameshrawalr2/TaskProject | /task1.py | 1,003 | 3.9375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 15 12:31:18 2018
@author: ramesh
"""
import pandas as pd
#main function definition
def main():
#Creating two DataFrame dframe,df
dframe=pd.DataFrame()
df=pd.DataFrame()
#Reading csv file and inserting in dataframe dframe
dframe=pd.read_csv("insurance.csv")
#deleting column named traded_date
dframe.drop('traded_date', axis=1,inplace=True)
#Multiplication of two columns
newcol=dframe['closing_price']*dframe['volume']
#inserting SProduct value in a data frame
dframe.insert(5,"product",newcol)
#for loop to get the required value from dataframe
for index, row in dframe.iterrows():
if(int(row['closing_price'])>7000 and int(row['volume'])>20000):
df=df.append(row) #adding row in another dataframe
#saving the dataframe in new csv file
df.to_csv("finaldata.csv",index=False)
main() #function call
|
a1d6e9689007dcbaa19b6ddcca944a3f40211de2 | kushrami/PythonProgramms | /LoopsInPython.py | 909 | 3.953125 | 4 | Count = 0
for Count in range(10):
Count = Count + 1
for InsideCount in range(10):
InsideCount = InsideCount + 1
print(Count,"*",InsideCount,"=",InsideCount*Count)
for Count in range(10,20):
Count = Count + 1
for InsideCount in range(10):
InsideCount = InsideCount + 1
print(Count,"*",InsideCount,"=",InsideCount*Count)
for Count in range(20,30,2):
Count = Count + 1
for InsideCount in range(10):
InsideCount = InsideCount + 1
print(Count,"*",InsideCount,"=",InsideCount*Count)
for Count in [22,24,26,28,30]:
for InsideCount in range(10):
InsideCount += 1
print(Count,"*",InsideCount,"=",InsideCount*Count)
for Count in ['red','green','blue']:
for InsideCount in ['red','green','blue']:
print(Count,InsideCount)
answer = '0'
while answer != '4':
answer = input("What is 2+2 : ")
print("Good!") |
5463c1b1352dc08c2fb66018805e88a533c31c66 | Pkfication/cracking_coding_interview | /Chapter_2/2.5.1_sum.py | 1,599 | 3.5 | 4 | '''
Incomplete Solution
'''
class Node:
def __init__(self, data):
self.data = data
self.next = None
def addSameLenth(a, b):
global carry
if (a == None):
return None
res = Node(0)
res.next = addSameLenth(a.next, b.next)
sum = a.data + b.data + carry
print(a.data, b.data, carry)
res.data = sum%10
carry = sum // 10
return res
def length(a):
h = 0
while h:
h += 1
h = h.next
return h
def sum(a, b):
tail = None
carry = 0
c = None
curr = None
l_a = length(a)
l_b = length(b)
if l_a == l_b:
c = addSameLength(a, b)
else:
for i in range(abs(l_a - l_b)):
if
c = addDifferentLength(curr, b)
while a != None or b != None:
a_num = 0 if a is None else a.data
b_num = 0 if b is None else b.data
num = carry + a_num + b_num
carry = num // 10
temp = Node(num%10)
if c is None:
c = temp
else:
tail.next = temp
tail = temp
if a:
a = a.next
if b:
b = b.next
if carry > 0:
tail.next = Node(carry)
return c
def log(head):
n = head
while n is not None:
if head != n:
print "->",
print n.data,
n = n.next
a = Node(7)
a.next = Node(1)
a.next.next = Node(6)
b = Node(5)
b.next = Node(9)
b.next.next = Node(3)
carry = 0
c = addSameLenth(a,b)
if carry:
temp = Node(carry)
temp.next = c
c = temp
log(a)
print
log(b)
print
log(c)
print
print carry
|
ff0966938c036e5224e8add7b4d78fd58a5c62a3 | avengerweb/gb-ml | /lesson1/task1.py | 431 | 3.9375 | 4 | # Diagram: https://drive.google.com/file/d/1a9kCYcswKoV5ZW6rqUBEVIYrCGIcYt6d/view
# No validation required (good user)
number = int(input("Input three-digit number: "))
# We shouldn`t use arrays :(
digit1 = number // 100
digit2 = number // 10 % 10
digit3 = number % 10
digits_sum = digit1 + digit2 + digit3
digits_product = digit1 * digit2 * digit3
print("Sum of digit: %i\nProduct of digit: %i" % (digits_sum, digits_product))
|
6ef1b14f7a489880d2f26d7c577a3ffd36192371 | DWhistle/Python3 | /Education/Books/PyEdu/1.lists/1lists.py | 428 | 3.703125 | 4 | cast = ["1", "2", "3", "4"]
#print(cast[1])
#print(len(cast))
cast.append(["123", 323232])
#print(cast[4])
cast.pop()
#print(len(cast))
cast.extend(["abc, asb"])
#print(cast[4])
cast.remove("1")
cast.insert(0, 121312321)
#print(cast[0])
numbers = ["\"1\"", "2", "3", "4"]
it = 0
for i in range(len(numbers)):
numbers.insert(it + 1, i + 22)
it+=2
numbers.append([123, "323232"])
#for i in numbers:
# print(i)
|
c4a1ae9296091ec1a20a69f320e79c83b4a2ac78 | ErikWeisz5/chapter_work | /4/2.py | 130 | 3.6875 | 4 | t = int(input("time spent on treadmill"))
c = 0
a = 0
while a < t:
c = c + 4.2
a = a + 1
print("you decreased cals by", c) |
a6978a891362cb9d3bb9d9a2b7a644311d0f7e01 | nownabe/competitive_programming | /AizuOnlineJudge/ITP1_Introduction_to_Programming_1/ITP1_9_D_Transformation.py | 322 | 3.546875 | 4 | s = input()
q = int(input())
for _ in range(q):
command, *args = input().split()
a = int(args[0])
b = int(args[1]) + 1
if command == 'print':
print(s[a:b])
elif command == 'reverse':
s = s[:a] + s[a:b][::-1] + s[b:]
elif command == 'replace':
s = s[:a] + args[2] + s[b:]
|
4c3ab5e456b2e02a7971b9f555e7dfc556e22a2f | brianchiang-tw/CodingInterviews | /14-1_Rope Cut I/by_dynamic programming.py | 1,487 | 3.65625 | 4 | from collections import defaultdict
class Solution:
def cuttingRope(self, n: int) -> int:
if n == 1:
# can not make a cut
return 1
elif n == 2 or n == 3:
# 2 = 1 + 1, product = 1 x 1 = 1
# 3 = 2 + 1, product = 2 x 1 = 2
return (n-1)
# key: interger
# value: max product of integer break
dp = defaultdict(int)
# base case:
for i in range(0, 5):
dp[i] = i
# general case:
for i in range(5, n+1):
for j in range(i//2+1):
dp[i] = max(dp[i], dp[j] * dp[i-j])
return dp[n]
# n : the value of input
## Time Complexity: O( n^2 )
#
# The overhead in time is the cost of nested loops, which is of O( n ^ 2)
## Space Complexity: O( n )
#
# The overhead in space is the storage for dp table, which is of O( n )
import unittest
class Testing( unittest.TestCase ):
def test_case_1( self ):
result = Solution().cuttingRope( n=2 )
self.assertSetEqual( result, 2)
def test_case_2( self ):
result = Solution().cuttingRope( n=3 )
self.assertEqual( result, 2)
def test_case_3( self ):
result = Solution().cuttingRope( n=10 )
self.assertEqual( result, 36)
if __name__ == '__main__':
unittest.main() |
6a77ae5017b3b746c7e893620917a6d0291f22ef | bhupesshhh/Guess-Your-Number | /main.py | 1,730 | 4.25 | 4 | import random
# Game Initiation
print("GUESS YOUR NUMBER!!!\n")
print("Computer will try to guess your number.\n")
print("Number should lie between (1-100)\n")
limit = input("Have you picked your number? (yes/no)")
if limit.lower() == "yes":
# Start the game with Yes only
gameplay = True
gameon = True
print("\nLet's start the game!")
else:
gameplay = False
gameon = False
# Gameon Condition
while gameon:
# Setting The Range
counts = 0
start = 0
end = 100
# Gameplay Condition
while gameplay:
# Guess Count
counts += 1
# Computer Guess
guess = random.randint(start,end)
print(f"\nComputer Guess: {guess}")
# Condition for start and equal is same
if start == end-2 or end == start+2:
print(f"\n{guess} is the correct answer\n")
gameplay = False
break
# Condition to choose from the desired
while True:
answer = input("Computer guess is ____ (high/low/correct) ")
if answer.lower() in ["high","low","correct"]:
break
else:
print("Incorrect Input")
# Check for correct guess
if answer == "correct":
print(f"\n{guess} is the correct answer\n")
gameplay = False
break
# Condition to adjust range as per the user input
if answer == "low":
start = guess
if answer == "high":
end = guess
# Result and Score
print(f"You took {counts} guesses to get the right answer\n")
# Replay Game
replay = input("Do you wanna play the game again? (yes/no)")
if replay.lower() == "yes":
gameon = True
gameplay = True
print("\n")
else:
gameon = False
break
# Endnote
print("\nThanks for playing the game")
print("We hope to see you soon!\n") |
7abb552522a2e8b68db231f1b6ebac06078b644f | Praveen-ghostProtocol/Class11-12 | /Program13.py | 606 | 4.25 | 4 | # Write a program that reads a limit and stores the Fibonacci series in a list and display. Input
# the index N within the limit and find the corresponding Fibonacci number.
n = int(input("Enter the value of 'n': "))
fiblist = []
a = 0
b = 1
sum = 0
count = 1
# print("Fibonacci Series: ", end = " ")
while(count <= n):
# print(sum, end = " ")
fiblist.append(sum)
count += 1
a = b
b = sum
sum = a + b
print('The series within the limit ',n,' is ')
print(fiblist)
index = int(input('Enter the index of the number to be searched : '))
print('The number at index ',index,' is = ',fiblist[index])
|
a8306588afcfb114e1653e079d7a2186ad0ce7d9 | Dongtengwen/7-12-practice | /19.py | 376 | 3.6875 | 4 | height=int(input('请输入身高(cm)'))
price=int(input('请输入身价'))
score=int(input('请输入颜值分'))
if height>180 and price>1000000 and score>99:
print('高富帅')
elif price>1000000 and score>99:
print('富帅')
elif score>99:
print('帅')
elif price<100 and score<60 and height<160:
print('矮穷挫')
else:
print('你是个普通人')
|
f91d47047a5b5bf2aace76fee32407c1d6c13818 | AnkitNigam1985/Data-Science-Projects | /Courses/DataFlair/pandas_pipe.py | 2,450 | 4.3125 | 4 | import numpy as np
import pandas as pd
#Pipe() used to apply any operation on all elements of series or dataframe
#Creating a function to be applied using pipe()
def adder(ele1, ele2):
return ele1+ele2
#Series
print("\nSeries:\n")
dataflair_s1 = pd.Series([11, 21, 31, 41, 51])
print("Original :\n",dataflair_s1)
print("After pipe():\n", dataflair_s1.pipe(adder, 3))
"""
Original :
0 11
1 21
2 31
3 41
4 51
dtype: int64
After pipe():
0 14
1 24
2 34
3 44
4 54
dtype: int64
"""
#DataFrame
dataflair_df1 = pd.DataFrame(
6*np.random.randn(6, 3), columns=['c1', 'c2', 'c3'])
print("Original Dataframe :\n", dataflair_df1)
print("After pipe():\n", dataflair_df1.pipe(adder, 3))
"""
Original Dataframe :
c1 c2 c3
0 7.846747 -2.022487 -4.943301
1 -0.857617 -3.749087 7.165374
2 12.145709 11.951062 4.020946
3 1.778519 5.065232 -12.122106
4 -4.958476 -7.021716 -4.242996
5 0.358903 -3.543973 4.067560
After pipe():
c1 c2 c3
0 10.846747 0.977513 -1.943301
1 2.142383 -0.749087 10.165374
2 15.145709 14.951062 7.020946
3 4.778519 8.065232 -9.122106
4 -1.958476 -4.021716 -1.242996
"""
=======
import numpy as np
import pandas as pd
#Pipe() used to apply any operation on all elements of series or dataframe
#Creating a function to be applied using pipe()
def adder(ele1, ele2):
return ele1+ele2
#Series
print("\nSeries:\n")
dataflair_s1 = pd.Series([11, 21, 31, 41, 51])
print("Original :\n",dataflair_s1)
print("After pipe():\n", dataflair_s1.pipe(adder, 3))
"""
Original :
0 11
1 21
2 31
3 41
4 51
dtype: int64
After pipe():
0 14
1 24
2 34
3 44
4 54
dtype: int64
"""
#DataFrame
dataflair_df1 = pd.DataFrame(
6*np.random.randn(6, 3), columns=['c1', 'c2', 'c3'])
print("Original Dataframe :\n", dataflair_df1)
print("After pipe():\n", dataflair_df1.pipe(adder, 3))
"""
Original Dataframe :
c1 c2 c3
0 7.846747 -2.022487 -4.943301
1 -0.857617 -3.749087 7.165374
2 12.145709 11.951062 4.020946
3 1.778519 5.065232 -12.122106
4 -4.958476 -7.021716 -4.242996
5 0.358903 -3.543973 4.067560
After pipe():
c1 c2 c3
0 10.846747 0.977513 -1.943301
1 2.142383 -0.749087 10.165374
2 15.145709 14.951062 7.020946
3 4.778519 8.065232 -9.122106
4 -1.958476 -4.021716 -1.242996
"""
|
74578d9bd2d52f06eb3bac8cf499a78e990f7fe7 | ivan-yosifov88/python_oop_june_2021 | /testing/vehicle/test/test_vehicle.py | 3,177 | 3.828125 | 4 | import unittest
from project.vehicle import Vehicle
class TestVehicle(unittest.TestCase):
def test_class_attributes__should_default_fuel_consumption_to_be_set(self):
default_fuel_consumption = 1.25
self.assertEqual(default_fuel_consumption, Vehicle.DEFAULT_FUEL_CONSUMPTION)
def test_init_method_should_set_attributes(self):
fuel = 10
horse_power = 100
test_vehicle = Vehicle(fuel, horse_power)
capacity = 10
fuel_consumption = 1.25
self.assertEqual(fuel, test_vehicle.fuel)
self.assertEqual(horse_power, test_vehicle.horse_power)
self.assertEqual(capacity, test_vehicle.capacity)
self.assertEqual(fuel_consumption, test_vehicle.fuel_consumption)
def test_drive__if_fuel_is_less_then_needed_should_raise_Exeption(self):
fuel = 10
horse_power = 100
fuel_consumption = 1.25
kilometers = 9
test_vehicle = Vehicle(fuel, horse_power)
with self.assertRaises(Exception) as message:
test_vehicle.drive(kilometers)
self.assertEqual("Not enough fuel", str(message.exception))
def test_drive__if_fuel_is_greater_then_needed_should_reduce_fuel(self):
fuel = 112.5
horse_power = 100
fuel_consumption = 1.25
kilometers = 10
test_vehicle = Vehicle(fuel, horse_power)
test_vehicle.drive(kilometers)
expect = fuel - (kilometers * fuel_consumption)
self.assertEqual(expect, test_vehicle.fuel)
def test_drive__if_fuel_is_equal_then_needed_should_reduce_fuel(self):
fuel = 12.5
horse_power = 100
fuel_consumption = 1.25
kilometers = 10
test_vehicle = Vehicle(fuel, horse_power)
test_vehicle.drive(kilometers)
expect = fuel - (kilometers * fuel_consumption)
self.assertEqual(expect, test_vehicle.fuel)
def test_refuel__when_fuel_with_added_fuel_is_greater_then_capacity__should_raise_Exception(self):
fuel = 10
horse_power = 100
fuel_to_add = 10
test_vehicle = Vehicle(fuel, horse_power)
with self.assertRaises(Exception) as message:
test_vehicle.refuel(fuel_to_add)
self.assertEqual("Too much fuel", str(message.exception))
def test_refuel__when_fuel_with_added_fuel_is_less_then_capacity__should_add_fuel(self):
fuel = 10
horse_power = 100
fuel_to_add = 9
capacity = 20
test_vehicle = Vehicle(fuel, horse_power)
test_vehicle.capacity = capacity
expect = fuel + fuel_to_add
test_vehicle.refuel(fuel_to_add)
self.assertEqual(expect, test_vehicle.fuel)
def test_str_when_correct__should_return_string(self):
fuel = 10
horse_power = 100
fuel_consumption = 1.25
test_vehicle = Vehicle(fuel, horse_power)
test_vehicle.fuel_consumption = fuel_consumption
expect = f"The vehicle has {horse_power} " \
f"horse power with {fuel} fuel left and {fuel_consumption} fuel consumption"
self.assertEqual(expect, test_vehicle.__str__())
if __name__ == "__main__":
unittest.main() |
96ec91de2e55573f80fd0eb8dc89f9a1752d026c | katolikyan/Walking-Marvin | /Marvin.py | 9,444 | 3.625 | 4 | import gym
import sys
import math
import matplotlib.pyplot as plt
import numpy as np
import time
import random
from colors import *
env = gym.make('Marvin-v0')
actions_len = 20 # number of actions each Marvin has
population = 20 # number of marvin in each generation
generations = 500 # number of generations
train_steps = 4000 # steps Marvin can make while training
walk_maxsteps = 10000 # maximum steps Marvin can make while walking
selection_percent = 0.25 # top 25% Marvins survives each generation
mutation_chance = 0.1 # chance to be changed for single action in a single marvin
highest_fitness = 1 # current highest fitness
flags = {} # privided flags
class Marvin:
def __init__(self, actions_len):
self.actions = np.asarray([env.action_space.sample() for _ in range(actions_len)])
self.fitness = 0
def genetic_algorithm(the_crowd):
for generation in range(generations):
print(color("\n Generation: ", bg='#555555'), color(" " + str(generation) + " ", bg='#555555'), "\n")
the_crowd = fitness(the_crowd)
if 'L' in flags:
print_generation_log(the_crowd)
the_crowd = selection(the_crowd)
the_crowd = crossover(the_crowd)
the_crowd = mutation(the_crowd)
if any(marvin.fitness >= 300 for marvin in the_crowd):
break
return the_crowd
def print_generation_log(the_crowd):
the_fitnesses = np.asarray(sorted([marvin.fitness for marvin in the_crowd], reverse=True)).T
print ("Population fitnesses :\n", the_fitnesses, "\n")
print ("The best actions : ", the_crowd[0].actions[0], " ... ", the_crowd[0].actions[-1])
print ("The best act hash : ", sum(map(sum, the_crowd[0].actions)))
print ("fitness average : ", sum(the_fitnesses) / len(the_crowd))
print ("fitness max : ", max(the_fitnesses))
print ("\n")
def init_crowd(population):
return [Marvin(actions_len) for _ in range(population)]
def fitness(the_crowd):
for marvin in the_crowd:
observation = env.reset()
for t in range(train_steps):
observation, reward, done, info = env.step(marvin.actions[t % actions_len])
marvin.fitness = marvin.fitness + reward
if done:
break
check_actions(marvin)
return the_crowd
def check_actions(marvin):
global highest_fitness
global flags
if marvin.fitness > highest_fitness:
highest_fitness = marvin.fitness
if 's' in flags:
print(color(" The best weights resaved ", bg='#117a40'), \
color(" New best fitness: ", bg='#117a40'), \
color(" " + str(highest_fitness) + " ", bg='#117a40'))
np.save("actions", marvin.actions)
def selection(the_crowd):
the_crowd = sorted(the_crowd, key=lambda marvin: marvin.fitness, reverse=True)
the_crowd = the_crowd[:int(selection_percent * len(the_crowd))]
for marvin in the_crowd:
marvin.fitness = 0
return the_crowd
def crossover(the_crowd):
offspring = []
for _ in range(int(((population - len(the_crowd)) / 2))):
parent_1 = random.choice(the_crowd)
parent_2 = random.choice(the_crowd)
child_1 = Marvin(actions_len)
child_2 = Marvin(actions_len)
split = random.randint(0, actions_len)
child_1.actions = np.concatenate((parent_1.actions[0:split], parent_2.actions[split:]))
child_2.actions = np.concatenate((parent_2.actions[0:split], parent_1.actions[split:]))
offspring.append(child_1)
offspring.append(child_2)
the_crowd.extend(offspring)
return (the_crowd)
# The_crowd is always sorted by the fitness, the best Marvin always at index 0.
# A Marvin with the best fitness never mutate and remain all the weights.
def mutation(the_crowd):
for marvin in the_crowd[1:]:
for idx, param in enumerate(marvin.actions):
if random.uniform(0.0, 1.0) <= mutation_chance:
marvin.actions[idx] = np.asarray(env.action_space.sample())
return the_crowd
def walk(the_crowd):
global highest_fitness
for marvin in the_crowd:
observation = env.reset()
for t in range(walk_maxsteps):
env.render()
observation, reward, done, info = env.step(marvin.actions[t % actions_len])
marvin.fitness = marvin.fitness + reward
if 'wl' in flags:
print(color("\n Marvin: ", bg='#555555'), color(" " + str(the_crowd.index(marvin)) + " ", bg='#555555'), "\n",
#"observation : ", observation, "\n",
"reward : ", reward, "\n",
"fitness : ", marvin.fitness, "\n")
if done:
break
return the_crowd
#--------------------FLAGS-----------------------------------------------------
def display_help():
print(color("\n Available commands: ", fg='#000000', bg='#bbbbbb'), "\n")
print (color(" –-walk ", bg='#444444'), " or ", color(" -w ", bg='#444444'), \
" Display only walking process.", "\n", sep='')
print (color(" –-help ", bg='#444444'), " or ", color(" -h ", bg='#444444'), \
" Display available commands.", "\n", sep='')
print (color(" –-load ", bg='#444444'), " or ", color(" -l ", bg='#444444'), \
" File Load weights for Marvin agent from a file. Skip training process if this option is specified.", "\n", sep='')
print (color(" –-logs ", bg='#444444'), " or ", color(" -L ", bg='#444444'), \
" Display training logs.", "\n", sep='')
print (color(" –-save ", bg='#444444'), " or ", color(" -s ", bg='#444444'), \
" File Save weights to a file after running the program.", "\n", sep='')
print (color(" –-walking-logs ", bg='#444444'), " or ", color(" -wl ", bg='#444444'), \
" Display logs while walking.", "\n", sep='')
print (color("\n Example: ", fg='#000000', bg='#bbbbbb'), "\n")
print (color(" python3 Marvin.py -L -l actions.npy -s ", bg='#444444'), \
" Will load weights from file, continue training based on that weights and save new best performing weights", "\n", sep='')
def parse_flags(flags):
args = sys.argv[1:]
f = 0;
for arg in args:
# HELP
if arg == '-h' or arg == '--help':
if len(sys.argv) != 2:
print (color("\n Error: Too many arguments ", bg='#7a1124'), "\n")
sys.exit(1)
display_help()
sys.exit(1)
# WALK
elif arg == '-w' or arg == '--walk':
key = 'w'
if key in flags:
print (color("\n Error: Flag " + str(arg) + " was lready provided ", bg='#7a1124'), "\n")
display_help()
sys.exit(1)
flags[key] = ''
# LOAD
elif arg == '-l' or arg == '--load':
key = 'l'
if key in flags:
print (color("\n Error: Flag " + str(arg) + " was lready provided ", bg='#7a1124'), "\n")
display_help()
sys.exit(1)
try:
flags[key] = sys.argv[sys.argv.index(arg) + 1]
f = 1;
except:
print (color("\n Error: No file provided ", bg='#7a1124'), "\n")
display_help()
sys.exit(1)
# SAVE
elif arg == '-s' or arg == '--save':
if arg in flags:
print (color("\n Error: Flag " + str(arg) + " was lready provided ", bg='#7a1124'), "\n")
display_help()
sys.exit(1)
flags['s'] = ''
# TRAINING LOGS
elif arg == '-L' or arg == '--logs':
key = 'L'
if key in flags:
print (color("\n Error: Flag " + str(arg) + " was lready provided ", bg='#7a1124'), "\n")
display_help()
sys.exit(1)
flags[key] = ''
# WALKING LOGS
elif arg == '-wl' or arg == '--walking-logs':
key = 'wl'
if key in flags:
print (color("\n Error: Flag " + str(arg) + " was lready provided ", bg='#7a1124'), "\n")
display_help()
sys.exit(1)
flags[key] = ''
# NOT A FLAG
else:
if f:
f = 0
continue
print (color("\n Error: Flag does not exist ", bg='#7a1124'), "\n")
display_help();
sys.exit(0);
if __name__ == '__main__':
the_crowd = init_crowd(population)
parse_flags(flags)
if 'l' in flags:
try:
actions = np.load(flags['l'])
for marvin in the_crowd:
marvin.actions = actions
except:
print (color("\n Eroor: File does not exist ", bg='#7a1124'), "\n")
sys.exit(2)
if 'w' in flags:
walk(the_crowd)
else:
the_crowd = genetic_algorithm(the_crowd)
walk(the_crowd)
|
65924c5b9a611a0abd633bdaea0ef6e9679cdc3f | bookstein/Exercise7 | /word_count.py | 813 | 3.90625 | 4 | def main():
script, filename = argv
print_and_sort_file(read_file(filename))
def read_file(filename):
word_count = {}
text = open(filename)
for line in text:
line = line.rstrip().lower()
for punc in string.punctuation:
line= line.replace(punc," ")
words = line.split()
# for loop by line: checking for words, adding to dictionary
for word in words:
if not word_count.get(word):
word_count[word] = 1
else:
word_count[word] += 1
return word_count
# print word_count
def print_and_sort_file(d):
# print key and value pairs
for key in sorted(d.keys()):
print "%s, %d" % (key, d[key])
from sys import argv
import string
if __name__ == "__main__":
main() |
8bb255d42a37da386dfdf3459d4dd8077d217075 | ITBOX-ITBOY/learningRepository | /官网pythoni学习/python介绍/test/code.py | 248 | 4.125 | 4 | '''
用户手动输入,来计算用户所输入值
num1=input("请输入num1");
num2=input("请输入num2");
sum=float(num1)+float(num2);
print("{0}和{1}的总和是{2}".format(num1,num2,sum));
'''
#for循环
for i in range(0,20):
print(i); |
3e1d1bd843eccfe472873236ac0c3d88503be440 | rodrigosantosti01/LingProg | /Exercicio3/atv10.py | 1,192 | 4.09375 | 4 |
# 10.
# Faça um Programa para um caixa eletrônico. O programa deverá perguntar ao usuário a valor do saque e
# depois informar quantas notas de cada valor serão fornecidas. As notas disponíveis
# serão as de 1, 5, 10, 50 e 100 reais. O valor mínimo é de 10 reais e o máximo de 600 reais.
# O programa não deve se preocupar com a quantidade de notas existentes na máquina.
# - Exemplo 1: Para sacar a quantia de 256 reais, o programa fornece duas notas de
# 100, uma nota de 50, uma nota de 5 e uma nota de 1;
# - Exemplo 2: Para sacar a quantia de 399 reais, o programa fornece três notas de
# 100, uma nota de 50, quatro notas de 10, uma nota de 5 e quatro notas de 1.
saque = int(input("Informe o valor a ser sacado: "))
if saque >= 10 and saque <= 600:
n100 = saque // 100
resto = saque % 100
print(f'{n100} notas de 100 reais;')
n50 = resto // 50
resto = resto % 50
print(f'{n50} notas de 50 reais;')
n10 = resto // 10
resto = resto % 10
print(f'{n10} notas de 10 reais;')
n5 = resto // 5
resto = resto % 5
print(f'{n5} notas de 5 reais;')
print(f'{resto} notas de 1 real.')
else:
print("Valor não permitido.") |
04db278b9792401e6647aa48c1e018643e8bbff0 | kitrix/my_homeworks | /Python_hw_6/hw6_var3.py | 3,677 | 3.75 | 4 | import random
# открывает файл, разбивает на строки
def open_file():
f = open("words.txt", 'r', encoding = "utf-8")
text = f.readlines()
f.close()
return(text)
# находит строку с нужной категорией слов, составляет массив
def find_words(word,text):
for i in range(len(text)):
line = []
line = text[i].split()
for l, w in enumerate(line):
line[l] = w.strip('.,!?();:*/\|<>-_%&#№@')
if line[0] == word:
words = []
for j in range(len(line)):
if j > 0:
words.append(line[j])
return(words)
# возвращает случайное существительное
def noun():
find = 'существительное'
nouns = find_words(find, text)
return random.choice(nouns)
# возвращает случайный глагол в повелительном наклонении
def imperative():
find = 'императив'
imper = find_words(find, text)
return random.choice(imper)
# возвращает случайное наречие, ставит его перед императивом
def adverb(imp):
find = 'наречие'
adverbs = find_words(find, text)
return random.choice(adverbs) + ' ' + imp
# возвращает случайный глагол
def verb():
find = 'глагол'
verbs = find_words(find, text)
return random.choice(verbs)
# возвращает случайное прилагательное
def adjective():
find = 'прилагательное'
adj = find_words(find, text)
return random.choice(adj)
# возвращает случайное вопросительное слово
def question_word():
find = 'вопрос'
quest = find_words(find, text)
return random.choice(quest)
# составляет утвердительное преложение
def pos_sentence():
sentence = adjective() + ' ' + noun() + ' ' + verb() +\
' ' + adjective() + ' ' + noun() + '.'
sentence = sentence.capitalize()
return(sentence)
# составляет отрицательное преложение
def neg_sentence():
sentence = adjective() + ' ' + noun() + ' не ' + verb() +\
' ' + adjective() + ' ' + noun() + '.'
sentence = sentence.capitalize()
return(sentence)
# составляет вопросительное преложение
def quest_sentence():
sentence = question_word()+ ' ' + adjective() + ' ' + noun() +\
' ' + verb() + ' ' + adjective() + ' ' + noun() + '?'
sentence = sentence.capitalize()
return(sentence)
# составляет повелительное преложение
def imper_sentence():
sentence = adverb(imperative()) + ' ' + noun() + '!'
sentence = sentence.capitalize()
return(sentence)
# составляет условное преложение
def if_sentence():
sentence = 'если бы ' + noun() + ' ' + verb() + ' ' + noun() +\
', то ' + noun() + ' ' + verb() + ' бы ' + noun() + '.'
sentence = sentence.capitalize()
return(sentence)
# выводит 5 предложений случайным образом
def random_print():
spisok = [pos_sentence(), neg_sentence(), quest_sentence(),\
imper_sentence(), if_sentence()]
random.shuffle(spisok)
for i in range(len(spisok)):
print(spisok[i], end = ' ')
text = open_file()
random_print()
|
6b5a82c26ff8f1f79df3b4874f63b7a810233c75 | tcbongers/mathematics | /project-euler/65.py | 442 | 3.609375 | 4 | from fractions import Fraction as frac
# Generate the representation
repr = [1]
for j in range(1, 40):
repr += [2*j, 1, 1]
#print(repr[0:20])
one = frac(1, 1)
current = frac(repr[-1], 1)
conv = 100
for r in repr[conv - 3::-1]:
current = one/current + frac(r, 1)
current = one/current + one + one
print(f'Convergent {conv}: {current}')
ds = sum([int(a) for a in str(current.numerator)])
print(f'Digit sum = {ds}') |
94b339f7433d6843fbbe941856bf2ec561720c89 | ryosuke071111/algorithms | /AtCoder/ABC/addition_n_sub.py | 88 | 3.53125 | 4 | a,b,c = input().split()
a,c = int(a),int(c)
if b =='-':
print(a-c)
else:
print(a+c)
|
b8db265fbfad658e0ec6eba74c3036d888f85eb5 | alicesilva/P1-Python-Problemas | /repeticao7.py | 121 | 3.921875 | 4 | #coding: utf-8
numeros = []
for i in range(5):
numero = float(raw_input())
numeros.append(numero)
print max(numeros)
|
60969dd44b1374cde9d7fe71571ad23b91806a95 | krristi427/TicTacToeAI | /TicTacToe02.py | 4,905 | 3.875 | 4 | class TicTacToe:
def __init__(self):
self.board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
self.playerSymbol = ""
self.playerPosition = []
self.aiSymbol = ""
self.aiPosition = []
self.winner = None
self.scoreBoard = None
self.turn = 0
self.optimalMove = int()
def drawBoard(self):
print(self.board[0] + " | " + self.board[1] + " | " + self.board[2])
print("___" + "___" + "___")
print(self.board[3] + " | " + self.board[4] + " | " + self.board[5])
print("___" + "___" + "___")
print(self.board[6] + " | " + self.board[7] + " | " + self.board[8])
def choice(self):
answer = input("What do you want to play as? (type x or o) ")
if answer.upper() == "X":
self.playerSymbol = "X"
self.aiSymbol = "O"
else:
self.playerSymbol = "O"
self.aiSymbol = "X"
self.scoreBoard = {
self.playerSymbol: -1,
self.aiSymbol: 1,
"tie": 0
}
def availableMoves(self):
moves = []
for i in range(0, len(self.board)):
if self.board[i] == " ":
moves.append(i)
return moves
def won_print(self):
self.won()
if self.winner == self.aiSymbol:
print("AI wins :(")
exit(0)
elif self.winner == self.playerSymbol:
print("Player Wins :)")
exit(0)
elif self.winner == "tie":
print("Guess it's a draw")
exit(0)
def won(self):
winningPositions = [{0, 1, 2}, {3, 4, 5}, {6, 7, 8},
{0, 4, 8}, {2, 4, 6}, {0, 3, 6},
{1, 4, 7}, {2, 5, 8}]
for position in winningPositions:
if position.issubset(self.playerPosition):
self.winner = self.playerSymbol
return True
elif position.issubset(self.aiPosition):
self.winner = self.aiSymbol
return True
if self.board.count(" ") == 0:
self.winner = "tie"
return True
self.winner = None
return False
def set_i_ai(self, i):
self.aiPosition.append(i)
self.board[i] = self.aiSymbol
def set_clear_for_ai(self, i):
self.aiPosition.remove(i)
self.board[i] = " "
def set_i_player(self, i):
self.playerPosition.append(i)
self.board[i] = self.playerSymbol
def set_clear_for_player(self, i):
self.playerPosition.remove(i)
self.board[i] = " "
def findOptimalPosition(self):
bestScore = float("-Infinity")
elements = {} # desperate times call for desperate measures
for i in self.availableMoves():
self.set_i_ai(i)
score = self.minimax(False)
if score > bestScore:
bestScore = score
elements[i] = bestScore
self.set_clear_for_ai(i)
if bestScore == 1:
print("you fucked up larry")
elif bestScore == 0:
print("hm")
else:
print("whoops kristi made a prog. error")
return max(elements, key=lambda k: elements[k])
def minimax(self, isMaximizing):
if self.won():
return self.scoreBoard[self.winner]
if isMaximizing:
bestScore = float("-Infinity")
for i in self.availableMoves():
self.set_i_ai(i)
bestScore = max(self.minimax(False), bestScore)
self.set_clear_for_ai(i)
return bestScore
else:
bestScore = float("Infinity")
for i in self.availableMoves():
self.set_i_player(i)
bestScore = min(self.minimax(True), bestScore)
self.set_clear_for_player(i)
return bestScore
def play(self):
self.choice()
while not self.won_print():
if self.turn % 2 == 0:
pos = int(input("Where would you like to play? (0-8) "))
self.playerPosition.append(pos)
self.board[pos] = self.playerSymbol
self.turn += 1
self.drawBoard()
else:
aiTurn = self.findOptimalPosition()
self.aiPosition.append(aiTurn)
self.board[aiTurn] = self.aiSymbol
self.turn += 1
print("\n")
print("\n")
self.drawBoard()
else:
print("Thanks for playing :)")
if __name__ == '__main__':
tictactoe = TicTacToe()
tictactoe.play()
|
8aed16d883586bd52cdd2de2b3ddb3e248790022 | hfgem/Computational_Neuroscience | /Hodgkin_Huxley_Model/HH_Example.py | 2,676 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: hannahgermaine
This code calculates the membrane potential and gating variable dynamics,
in a Hodgkin-Huxley model simulation, given a set of conditions. The code
outputs a plot of the applied current and resulting membrane potential to
the user's desktop.
"""
import Hodgkin_Huxley as hh
import matplotlib.pyplot as plt
import numpy as np
import os
desktop = os.environ["HOME"] + "/Desktop/"
#Variables:
#time vector
t_max = 0.35 #0.35 seconds
t_step = 2*10**(-6) #timestep
t_vector = np.arange(0,t_max,t_step) #vector of time values
#conductances
g_leak = 30*10**(-9) #30 nS leak conductance
max_g_na = 12*10**(-6) #12 microS maximum sodium conductance
max_g_k = 3.6*10**(-6) #3.6 microS maximum delayed rectifier conductance
#reversal potentials
e_na = 45*10**(-3) #45 mV sodium reversal potential
e_k = -82*10**(-3) #-82 mV potassium reversal potential
e_l = -60*10**(-3) #-60 mV leak reversal potential
c_m = 100*10**(-12) #100 pF membrane capacitance
#membrane potential vector
v_vector = np.zeros(len(t_vector)) #vector of membrane potentials
v_vector[0] = e_l + 0.01 #initializing membrane potential to slightly above leak reversal potential
#applied current vector
i_app = np.zeros(len(t_vector)) #vector of applied currents
i_base = 0.65*10**(-9) #base applied current of 0.65 nA
i_app += i_base
t_start = int((100*10**(-3))/t_step) #increase applied current at 100 ms
dur_applied = t_start #duration of applied current - 100 ms
indices_i_app_increase = np.arange(0,dur_applied) + t_start #indices to increase applied current
np.add.at(i_app, indices_i_app_increase, 0.22*10**(-9)) #Increase the applied current to 0.22 nA
#gating variable vectors
m = np.zeros(len(t_vector)) #m - sodium activation vector
h = np.zeros(len(t_vector)) #h - sodium inactivation vector
n = np.zeros(len(t_vector)) #n - potassium activation vector
#Run Hodgkin-Huxley simulation for above variables
v_calculated, m_calculated, h_calculated, n_calculated = hh.hod_hux(m, h, n, t_step, t_vector, v_vector, i_app, g_leak, max_g_na, max_g_k, e_na, e_k, e_l, c_m)
#Plot results of simulation
plt.figure(1, figsize=(10,10))
plt.subplot(211)
plt.plot(t_vector, i_app)
plt.xlabel("Time (in seconds)")
plt.ylabel("Current (in Amperes)")
plt.title("Applied Current")
plt.subplot(212)
plt.plot(t_vector, v_calculated)
plt.xlabel("Time (in seconds)")
plt.ylabel("Membrane Potential (in Volts)")
plt.title("Membrane Potential in Hodgkin Huxley")
plt.subplots_adjust(top=1.0, bottom=0.1, left=0.1, right=1.0, hspace=0.5,
wspace=0.5)
plt.savefig(desktop + "HH_simulation_figure.png", bbox_inches='tight')
plt.show()
|
50bcb61c949430771521264a538cd95794a1ae9c | balaji-senthil/program1_part1 | /project1_funs.py | 3,301 | 3.671875 | 4 | '''
Programming Assignment 1 - Part1
Submitted by Balaji Senthilkumar
'''
#The funtion to load the board (.txt to 2Dlist/array)
def loadBoard(board):
inputFile = open(board, 'r')
myBoard = []
for row in inputFile:
myBoard.append(row.split())
return myBoard
#THE FUNCTION TO PRINT 'myBoard'
def printBoard(myBoard):
for row in myBoard:
print (" ".join(map(str,row)))
# print('****'+myBoard[2][3])
def possibleMoves(currentPosition,myBoard):
#So here I have used a graph based approach, for figuring out the solution,
# using x_co_ordinates and y_co_oridinates as the positional arguments.
x_co_ordinate,y_co_ordinate = currentPosition #spreading operation
possibleMovesArray=[]
limit=len(myBoard) # ensuring that the program does not cause an outOfBounds or any negative array positioning
if(x_co_ordinate+1<limit and y_co_ordinate<limit): #left to right
possibleMovesArray.append((x_co_ordinate+1,y_co_ordinate))
if(x_co_ordinate<limit and y_co_ordinate+1<limit): #Top-Bottom
possibleMovesArray.append((x_co_ordinate,y_co_ordinate+1))
if(x_co_ordinate+1<limit and y_co_ordinate+1<limit): #diagonal 1
possibleMovesArray.append((x_co_ordinate+1,y_co_ordinate+1))
if(x_co_ordinate+1<limit and ((y_co_ordinate-1<limit)and y_co_ordinate-1>=0)): #diagonal 2
possibleMovesArray.append((x_co_ordinate+1,y_co_ordinate-1))
if(((x_co_ordinate-1<limit)and x_co_ordinate-1>=0) and ((y_co_ordinate-1<limit)and y_co_ordinate-1>=0)): #diagonal 3
possibleMovesArray.append((x_co_ordinate-1,y_co_ordinate-1))
if(((x_co_ordinate-1<limit)and x_co_ordinate-1>=0) and (y_co_ordinate+1<limit)): #diagonal 4
possibleMovesArray.append((x_co_ordinate-1,y_co_ordinate+1))
if(((x_co_ordinate-1<limit)and x_co_ordinate-1>=0) and y_co_ordinate<limit): #right to left
possibleMovesArray.append((x_co_ordinate-1,y_co_ordinate))
if(x_co_ordinate<limit and ((y_co_ordinate-1<limit)and y_co_ordinate-1>=0)): #Bottom Up
possibleMovesArray.append((x_co_ordinate,y_co_ordinate-1))
#print(set(possibleMovesArray))
return(set(possibleMovesArray))
def legalMoves(possibleMovesArg,pathArg):
legalMovesArray=[] #creating a list to store the legal moving positions(co_ordinates)
for pos in possibleMovesArg:
if pos not in legalMovesArray: #checking for non-repetion of positions, to comply the rules of the game
legalMovesArray.append(pos)
return(set(legalMovesArray))
def examineState(myBoard,currentPosition,path,myDict):
wordList = []
for i in path:
x_co_ordinate, y_co_ordinate = i #spreading x_co_ordinate and y_co_ordinate out of the path
wordList.append(myBoard[x_co_ordinate][y_co_ordinate])
x_co_ordinate, y_co_ordinate = currentPosition
wordList.append(myBoard[x_co_ordinate][y_co_ordinate])
finalList = ''.join([str(i) for i in wordList])
# print(finalList)
if finalList.lower() in myDict: #Checking whether the word is in the given dicionary
outputTuple=(finalList.lower(),'Yes')
print(outputTuple)
else:
outputTuple=(finalList.lower(),'No')
print(outputTuple)
|
207b0b8d682652eb10cebda5a5e0b817f7279f7f | AruIbu/ADV-152 | /ADV-152.py | 709 | 3.703125 | 4 | from tkinter import *
root=Tk()
root.title("Multidimensional Arrays")
root.geometry("500x500")
label= Label(root)
array_1d = ["John", "James" ," Thomsan"]
print( array_1d[0] )
array_2d = [["john","A"], ["james", "B"],["Thomson","C"]]
print(array_2d[0][1])
array_3d = [[["John","A+","Excellent"],["James","A","Very Good"],["Thomson","B","Good"]]]
print(array_3d[0][0][2])
def report():
label["text"] = array_3d[0][1][0] + " got grade " + array_3d[0][1][1] +" and he is doing "+array_3d[0][1][2]
btn = Button(root, text= "show report", command = report)
btn.place(relx = 0.5, rely =0.5, anchor = CENTER)
label.place(relx = 0.5, rely =0.6, anchor = CENTER)
root.mainloop()
|
ac097d2e55f9d21a7f51382e1a0d71db32fcb2df | shelvaldes/PlatziCodingChallenge | /rpsls.py | 3,262 | 4.21875 | 4 | """
Rock, Paper, Scissors, Lizard, Spock.
Scissors cut paper,
paper covers rock,
rock crushes lizard,
lizard poisons Spock,
Spock smashes scissors,
scissors decapitates lizard,
lizard eats paper,
paper disproves Spock,
Spock vaporizes rock,
and —as it always has— rock crushes scissors.
"""
import random
print("\nRock, Paper, Scissors, Lizard, Spock.\n\nScissors cut paper,\npaper covers rock,\nrock crushes lizard,\nlizard poisons Spock,\nSpock smashes scissors,\nscissors decapitates lizard,\nlizard eats paper,\npaper disproves Spock,\nSpock vaporizes rock,\nand —as it always has— rock crushes scissors.\n\nRock = 1 | Paper = 2 | Scissors = 3 | Lizard = 4 | Spock = 5\n")
win = "It seems that you've won this time.\n"
lose = "Oh... I win\n"
even = "We're even\n"
""" def print_win():
print(win)
def print_lose():
print(lose)
def print_even():
print(even) """
user = int(input("Choose wisely... "))
def sheldon_play():
global sheldon
sheldon = int(random.randrange(1, 5))
sheldon_play()
results = 0
def play(user, sheldon):
if user == 1 and sheldon == 1:
print(even)
elif user == 1 and sheldon == 2:
print(lose)
elif user == 1 and sheldon == 3:
print(win)
elif user == 1 and sheldon == 4:
print(win)
elif user == 1 and sheldon == 5:
print(lose)
#paper
elif user == 2 and sheldon == 1:
print(win)
elif user == 2 and sheldon == 2:
print(even)
elif user == 2 and sheldon == 3:
print(lose)
elif user == 2 and sheldon == 4:
print(lose)
elif user == 2 and sheldon == 5:
print(win)
#scissors
elif user == 3 and sheldon == 1:
print(lose)
elif user == 3 and sheldon == 2:
print(win)
elif user == 3 and sheldon == 3:
print(even)
elif user == 3 and sheldon == 4:
print(win)
elif user == 3 and sheldon == 5:
print(lose)
#Lizard
elif user == 4 and sheldon == 1:
print(lose)
elif user == 4 and sheldon == 2:
print(win)
elif user == 4 and sheldon == 3:
print(lose)
elif user == 4 and sheldon == 4:
print(even)
elif user == 4 and sheldon == 5:
print(win)
#Spock
elif user == 5 and sheldon == 1:
print(win)
elif user == 5 and sheldon == 2:
print(lose)
elif user == 5 and sheldon == 3:
print(win)
elif user == 5 and sheldon == 4:
print(lose)
elif user == 5 and sheldon == 5:
print(even)
user1, user2, user3, user4, user5 = "Rock", "Paper", "Scissors", "Lizard", "Spock"
sheldon1, sheldon2, sheldon3, sheldon4, sheldon5 = "Rock", "Paper", "Scissors", "Lizard", "Spock"
def UX(user, sheldon):
print("\nYou choosed: ")
if user == 1:
print(user1)
elif user == 2:
print(user2)
elif user == 3:
print(user3)
elif user == 4:
print(user4)
elif user == 5:
print(user5)
print("and I ")
if sheldon == 1:
print(sheldon1)
elif sheldon == 2:
print(sheldon2)
elif sheldon == 3:
print(sheldon3)
elif sheldon == 4:
print(sheldon4)
elif sheldon == 5:
print(sheldon5)
print("\n")
UX(user, sheldon)
play(user, sheldon) |
30d1ced5ce9df313b3cb8d27cbaf09eb587991ed | allenling/my_leetcode | /easy_level/invert_binary_tree.py | 895 | 4.21875 | 4 | # coding=utf-8
'''
翻转二叉树
'''
import binary_tree_utils
def invert_binary_tree(root):
if not root:
return root
nodes = [root]
while nodes:
node = nodes.pop()
if node:
node.left, node.right = node.right, node.left
nodes.extend([node.left, node.right])
return root
def main():
r = binary_tree_utils.generate_binary(by_depth=3)
binary_tree_utils.show_binary_tree(r)
print '----------------------'
invert_binary_tree(r)
binary_tree_utils.show_binary_tree(r)
print '#####################################'
input_v = [4, 2, 7, 1, 3, 6, 9]
input_r = binary_tree_utils.generate_binary(input_v)
binary_tree_utils.show_binary_tree(input_r)
print '----------------------'
invert_binary_tree(input_r)
binary_tree_utils.show_binary_tree(input_r)
if __name__ == '__main__':
main()
|
24eb744cfc3e8ae7bb8fe6e6a35f70ded97f5af6 | BHSB/chess | /position.py | 406 | 3.6875 | 4 | class Position:
def __init__(self, position=(0,0)):
self.position = self.inside_board(position)
def inside_board(self, position):
if all(x >= 0 for x in position) and all(x <=7 for x in position):
return (position)
else:
print("Position: Invalid move")
def update_position(self, position):
self.position = self.inside_board(position)
|
e7d077a6f6b5e97d4298d141e1bf35963ab75265 | AgamGhotra19/Calculator-Python | /Calculator.py | 7,538 | 3.515625 | 4 | from tkinter import *
def center(win):
win.update_idletasks()
width = win.winfo_width()
frm_width = win.winfo_rootx() - win.winfo_x()
win_width = width + 2 * frm_width
height = win.winfo_height()
title_bar_height = win.winfo_rooty() - win.winfo_y()
win_height = height + title_bar_height + frm_width
x = win.winfo_screenwidth() // 2 - win_width // 2
y = win.winfo_screenheight() // 2 - win_height // 2
win.geometry('{}x{}+{}+{}'.format(width, height, x, y))
win.deiconify()
def click(event):
string = sc_value.get()
if string == "Error":
sc_value.set("")
screen.update()
text = event.widget.cget("text")
if text == "=":
try:
if sc_value.get().isdigit():
value = float(sc_value.get())
else:
value = eval(screen.get())
sc_value.set(value)
screen.update()
except Exception as e:
print(e)
sc_value.set("Error")
screen.update()
elif text == "C":
if string == "Error":
sc_value.set("")
screen.update()
else:
s = string[0: len(string) - 1]
sc_value.set(s)
screen.update()
elif text == "AC":
sc_value.set("")
screen.update()
elif text == "×":
sc_value.set(sc_value.get() + "*")
elif text == "÷":
sc_value.set(sc_value.get() + "/")
elif text == "+/-":
value = sc_value.get()
if value.isdigit() or value.isdecimal():
value = int(value)
value *= -1
sc_value.set(value)
screen.update()
else:
try:
value = float(value)
value *= -1
sc_value.set(value)
screen.update()
except Exception as e:
print(e)
try:
idx = 0
ans: str = ""
for i in range(len(string)-1, 0-1, -1):
if value[i] != '/' and value[i] != '*' and value[i] != '+' and value[i] != '-':
ans = value[i] + ans
else:
idx = i
break
a = float(ans)
a *= -1
if idx != 0:
sc_value.set(value[0:idx + 1] + "(" + str(a) + ")")
else:
sc_value.set(value[0:idx] + "(" + str(a) + ")")
except Exception as e:
print(e)
else:
sc_value.set(sc_value.get() + text)
screen.update()
if __name__ == '__main__':
root = Tk()
root.geometry("450x550")
root.title("Calculator")
root.resizable(False, False)
root.wm_iconbitmap("Calculator_Icon.ico")
center(root)
sc_value = StringVar()
sc_value.set("")
screen = Entry(root, textvar=sc_value, font="Arial 25 normal", fg="Red", state=DISABLED)
screen.pack(fill=X, ipadx=8, pady=25, padx=25)
Button_1 = Button(text="C", font="Arial 25 normal", height=1, width=3, bg="Orange")
Button_1.pack(padx=7, pady=5)
Button_1.bind("<Button-1>", click)
Button_1.place(x=30, y=100)
Button_2 = Button(text="AC", font="Arial 25 normal", height=1, width=3, bg="Orange")
Button_2.pack(padx=7, pady=5)
Button_2.bind("<Button-1>", click)
Button_2.place(x=115, y=100)
Button_3 = Button(text="+/-", font="Arial 25 normal", height=1, width=3, bg="Orange")
Button_3.pack(padx=7, pady=5)
Button_3.bind("<Button-1>", click)
Button_3.place(x=195, y=100)
Button_4 = Button(text="(", font="Arial 25 normal", height=1, width=3, bg="Orange")
Button_4.pack(padx=7, pady=5)
Button_4.bind("<Button-1>", click)
Button_4.place(x=275, y=100)
Button_5 = Button(text=")", font="Arial 25 normal", height=1, width=3, bg="Orange")
Button_5.pack(padx=7, pady=5)
Button_5.bind("<Button-1>", click)
Button_5.place(x=355, y=100)
Button_6 = Button(text="1", font="Arial 25 normal", height=1, width=4, bg="Light Gray")
Button_6.pack(padx=7, pady=5)
Button_6.bind("<Button-1>", click)
Button_6.place(x=30, y=180)
Button_7 = Button(text="2", font="Arial 25 normal", height=1, width=4, bg="Light Gray")
Button_7.pack(padx=7, pady=5)
Button_7.bind("<Button-1>", click)
Button_7.place(x=130, y=180)
Button_8 = Button(text="3", font="Arial 25 normal", height=1, width=4, bg="Light Gray")
Button_8.pack(padx=7, pady=5)
Button_8.bind("<Button-1>", click)
Button_8.place(x=230, y=180)
Button_9 = Button(text="+", font="Arial 25 normal", height=1, width=4, bg="Orange")
Button_9.pack(padx=7, pady=5)
Button_9.bind("<Button-1>", click)
Button_9.place(x=330, y=180)
Button_10 = Button(text="4", font="Arial 25 normal", height=1, width=4, bg="Light Gray")
Button_10.pack(padx=7, pady=5)
Button_10.bind("<Button-1>", click)
Button_10.place(x=30, y=260)
Button_11 = Button(text="5", font="Arial 25 normal", height=1, width=4, bg="Light Gray")
Button_11.pack(padx=7, pady=5)
Button_11.bind("<Button-1>", click)
Button_11.place(x=130, y=260)
Button_12 = Button(text="6", font="Arial 25 normal", height=1, width=4, bg="Light Gray")
Button_12.pack(padx=7, pady=5)
Button_12.bind("<Button-1>", click)
Button_12.place(x=230, y=260)
Button_13 = Button(text="-", font="Arial 25 normal", height=1, width=4, bg="Orange")
Button_13.pack(padx=7, pady=5)
Button_13.bind("<Button-1>", click)
Button_13.place(x=330, y=260)
Button_14 = Button(text="7", font="Arial 25 normal", height=1, width=4, bg="Light Gray")
Button_14.pack(padx=7, pady=5)
Button_14.bind("<Button-1>", click)
Button_14.place(x=30, y=340)
Button_15 = Button(text="8", font="Arial 25 normal", height=1, width=4, bg="Light Gray")
Button_15.pack(padx=7, pady=5)
Button_15.bind("<Button-1>", click)
Button_15.place(x=130, y=340)
Button_16 = Button(text="9", font="Arial 25 normal", height=1, width=4, bg="Light Gray")
Button_16.pack(padx=7, pady=5)
Button_16.bind("<Button-1>", click)
Button_16.place(x=230, y=340)
Button_17 = Button(text="×", font="Arial 25 normal", height=1, width=4, bg="Orange")
Button_17.pack(padx=7, pady=5)
Button_17.bind("<Button-1>", click)
Button_17.place(x=330, y=340)
Button_18 = Button(text=".", font="Arial 25 normal", height=1, width=4, bg="Light Gray")
Button_18.pack(padx=7, pady=5)
Button_18.bind("<Button-1>", click)
Button_18.place(x=30, y=420)
Button_19 = Button(text="0", font="Arial 25 normal", height=1, width=4, bg="Light Gray")
Button_19.pack(padx=7, pady=5)
Button_19.bind("<Button-1>", click)
Button_19.place(x=130, y=420)
Button_20 = Button(text="=", font="Arial 25 normal", height=1, width=4, bg="Orange")
Button_20.pack(padx=7, pady=5)
Button_20.bind("<Button-1>", click)
Button_20.place(x=230, y=420)
Button_21 = Button(text="÷", font="Arial 25 normal", height=1, width=4, bg="Orange")
Button_21.pack(padx=7, pady=5)
Button_21.bind("<Button-1>", click)
Button_21.place(x=330, y=420)
root.mainloop()
|
c6d1369dc3d8f9ff033b7efbf6a5b9ec8aab0ecc | xmlhh/pystudy | /1.python基础/4.高级变量类型/字符串/string_base.py | 5,136 | 4.09375 | 4 | #! /usr/bin/python3
#-*- coding:utf-8 -*-
"""
#文件名称:string_base.py
#编写人员:LHH
#项目组:系统组
#创建日期:2020/07/02
#功能描述:字符串的基础、基本操作、切片
#修改描述:
#备注:
"""
repeat_num = 45
print("****************1.字符串的基础*****************")
"""
字符串的定义:
可以使用双引号"",单引号''定义一个字符串;
如果字符串内部需要使用", 则可用''定义字符串;
如果字符串内部需要使用', 则可用""定义字符串;
区分大小写
"""
str1 = "hello python"
str2 = '我的名字是 "LHH"'
print(str1)
print(str2)
print(str2[7])
print('遍历字符串,单个字符输出:')
for ch in str2:
print(ch)
print("%s\n" % ('-' * repeat_num))
print("****************2.字符串的基本操作*****************")
#1)统计
print('str1字符串的长度:\t', len(str1))
print('str2字符串的长度:\t', len(str2))
print('HH在字符串的次数:\t', str2.count('HH'))
print('HH在字符串中的位置:\t', str2.index('HH'))
# 注意,使用index方法,如果传递的字符或字符串不存在,会报错
# print('HH在字符串中的位置:\t', str2.index('Hi'))
#2)判断方法
str_space = ' \t\n\r'
print('判断是否是空白字符:\t', str_space.isspace())
#以下三个方法都不能判断小数
num_str = "1.1"
#unicode 字符串
# num_str = "\u00b2"
#中文数字
# num_str = "二零二零"
print(num_str)
print(num_str.isdecimal())
print(num_str.isdigit())
print(num_str.isnumeric())
#3)字符串的查找和替换
#index方法,如果指定的字符串不存在,会报错
#find方法,如果指定的字符串不存在,会返回-1;如存在,则返回开始的索引
print('index: \t', str2.index('HH'))
print('find: \t', str2.find('HH'))
print('find: \t', str2.find('hh'))
print('替换:\t', str2.replace('LHH', 'PYTHON'))
print("%s\n" % ('-' * repeat_num))
#4)文本对齐和去空白字符
tang_poem = [' 唐伯虎点秋香',
' 周星驰 ',
' 别人笑我太疯癫;',
' 我笑他人看不穿。',
' 不见武陵豪杰墓; ',
' 无花无酒锄作田。 ']
for str_poem in tang_poem:
#print(str_poem.lstrip()) #去左边空白字符
#print(str_poem.rstrip()) #去右边空白字符
#print(str_poem.strip()) #去两边空白字符
str_poem = str_poem.strip()
# print('|\t%s\t\t|' % str_poem.center(10, ' ')) #半角空格
print('|\t%s\t|' % str_poem.center(10, ' ')) #全角空格
# print('|%s|' % str_poem.ljust(10, ' '))
# print('|%s|' % str_poem.rjust(10, ' '))
print("%s\n" % ('-' * repeat_num))
#5)拆分和拼接
string_poem = '\t\n 登鹳雀楼 \t \n &&王之涣\t白日依山尽; \n\n \t黄河入海流。\t\t\t欲穷千里目;\t 更上一层楼。\t\t\n'
print(string_poem)
poem_list = string_poem.split() #split()默认以\t、\r、\n、空格分割字符串
print('字符串默认分割得到的列表:\n%s\n' % poem_list)
# poem_list = string_poem.split('&&')
# print('字符串按&&分割得到的列表:\n%s\n' % poem_list)
string_poem_ret = '|'.join(poem_list)
print('列表+"|"合并得到的字符串:\n%s\n' % string_poem_ret)
string_poem_ret = string_poem_ret.split('&&')
print('字符串按&&分割得到的列表:\n%s\n' % string_poem_ret)
string_poem_ret = ''.join(string_poem_ret)
print('列表合并得到的字符串:\n%s\n' % string_poem_ret)
print("%s\n" % ('-' * repeat_num))
print("****************3.字符串的切片*****************")
"""
切片:
适用于字符串、列表、元祖,不能对字典切片
格式:字符串[开始索引:结束索引:步长]
顺序:0、1、2、...n
倒序:-n、-n+1、... -2、-1
左闭右开
开始索引、结束索引、数字均可省略,冒号:不能省略
"""
num_str = "0123456789"
#截取完整字符串
print('完整字符串[:]: \t\t%s' % num_str[:])
#截取从2到5位置的字符串
print('[2-5]: \t\t\t\t%s' % num_str[2:6])
print('[2-5): \t\t\t\t%s' % num_str[2:5])
print('(2-5]: \t\t\t\t%s' % num_str[3:6])
print('(2-5): \t\t\t\t%s' % num_str[3:5])
#截取从开始到5位置的字符串
print('从开始到5,[:6]: \t\t%s' % num_str[:6])
#截取从2到末尾的字符串
print('从2到末尾,[2:]: \t\t%s' % num_str[2:])
#截取从2到末尾-1的字符串
print('从2到末尾-1,[2:-1): \t%s' % num_str[2:-1])
#从开始位置,每隔一个字符截取
print('间隔一个字符,[::2]: \t%s' % num_str[::2])
#从索引1开始,每隔一个字符截取
print('间隔一个字符,[1::2]: \t%s' % num_str[1::2])
#截取字符串末尾3个字符串
print('末尾3个字符串,[:]: \t%s' % num_str[-3:])
#字符串的逆序
print('逆序:\t\t\t\t%s' % num_str[-1::-1])
print('逆序:\t\t\t\t%s' % num_str[::-1])
print("%s\n" % ('-' * repeat_num))
|
cc85d28f57cb9d8971c50a22e02f30404b844595 | ztw11ll/data-mining | /Numeric Data Analysis.py | 4,950 | 3.84375 | 4 | ######################################## BM489E HW NO.1 ##############################################
## ALi KARATANA ##
## 121180043 ##
######################################################################################################
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math
float_formatter = lambda x: "%.3f" % x # creating float formatter to use when showing float data
np.set_printoptions(formatter={'float_kind': float_formatter}) # setting up the formatter we created
data = np.loadtxt("magic_04.txt", delimiter=",", usecols=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)) # getting data from .txt and creating matrix
print("OUr data------------------------\n",data)
col_number = np.size(data, axis=1) # finding column number of dataset matrix
row_number = np.size(data, axis=0) # finding row number of dataset matrix
mean_vector = np.mean(data, axis=0).reshape(col_number, 1) # computing the mean vector
print("Mean Vector--------------------\n", mean_vector, "\n")
t_mean_vector = np.transpose(mean_vector)
centered_data_matrix = data - (1 * t_mean_vector) # computing the centered data matrix
print("Centered Data Matrix-------------------\n", centered_data_matrix, "\n")
t_centered_data_matrix = np.transpose(centered_data_matrix) # computing the transpose of the centered data matrix
covariance_matrix_inner = (1 / row_number) * np.dot(t_centered_data_matrix, centered_data_matrix) # description below in print function as a string
print(
"The sample covariance matrix as inner products between the columns of the centered data matrix ----------------------------------------\n",
covariance_matrix_inner, "\n")
def sum_of_centered_points(): # finding the sum of centered data points
sum = np.zeros(shape=(col_number, col_number))
for i in range(0, row_number):
sum += np.dot(np.reshape(t_centered_data_matrix[:, i], (-1, 1)),
np.reshape(centered_data_matrix[i, :], (-1, col_number)))
return sum
covariance_matrix_outer = (1 / row_number) * sum_of_centered_points() # description below in print function as a string
print(
"The sample covariance matrix as outer product between the centered data points ----------------------------------------\n",
covariance_matrix_outer, "\n")
vector1 = np.array(centered_data_matrix[:, 1])
vector2 = np.array(centered_data_matrix[:, 2])
def unit_vector(vector): # computing unit vectors for attribute vectors
return vector / np.linalg.norm(vector)
def angle_between(v1, v2): # calculating the angle between to attribute vectors
v1_u = unit_vector(v1)
v2_u = unit_vector(v2)
return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
correlation = math.cos(angle_between(vector1, vector2)) # computing th correlation between attributes
print(" The correlation between Attributes 1 and 2: %.5f" % correlation, "\n")
variance_vector = np.var(data, axis=0) # creating variance vector
max_var = np.max(variance_vector) # finding max variance
min_var = np.min(variance_vector) # finding min variance
for i in range(0, col_number): # finding index of max variance
if variance_vector[i] == max_var:
max_var_index = i;
for i in range(0, col_number): # finding index of min variance
if variance_vector[i] == min_var:
min_var_index = i
print(" Max variance = %.3f ( Attribute %d )" % (max_var, max_var_index))
print(" Min variance = %.3f ( Attribute %d )\n" % (min_var, min_var_index))
covariance_matrix = np.cov(data, rowvar=False) # computing covariance matrix
max_cov=np.max(covariance_matrix) # finding max value in covariance matrix
min_cov=np.min(covariance_matrix) # finding min value in covariance matrix
for i in range(0, col_number): # the loop to find the index of max and min values
for j in range(0, col_number):
if covariance_matrix[i, j] == max_cov:
max_cov_atrr1=i
max_cov_attr2=j
for i in range(0, col_number): # the loop to find the index of max and min values
for j in range(0, col_number):
if covariance_matrix[i, j] == min_cov:
min_cov_atrr1 = i
min_cov_attr2 = j
print("Max Covariance = %.3f (Between Attribute %d and %d)" %(max_cov,max_cov_atrr1,max_cov_attr2)) # finding index of max covariance
print("Min Covariance = %.3f (Between Attribute %d and %d)\n" %(min_cov,min_cov_atrr1,min_cov_attr2)) # finding index of min covariance
df = pd.DataFrame(data[:, 1]) # creating data frame for plotting
plt.show(plt.scatter(data[:, 1], data[:, 2], c=("red", "yellow"))) # plotting the scatter plot between attributes
plt.show(df.plot(kind='density')) # plotting probability density function
|
40f27688e885a4f1bb54e3f1ce68638f0f233a89 | tlima1011/python3-curso-em-video | /ex113_solucao_guanabara.py | 1,004 | 3.84375 | 4 | def leiaInt(msg):
while True:
try:
n = int(input(msg))
except (ValueError, TypeError):
print('\033[31mERRO: por favor, digite um número inteiro válido.\033[m')
continue
except (KeyboardInterrupt):
print('\033[31mEntrada de dados interrompida pelo usuário.\033[m')
return 0
else:
return n
def leiaFloat(msg):
while True:
try:
n = float(input(msg))
except (ValueError, TypeError):
print('\033[31mERRO: por favor, digite um número real válido.\033[m')
continue
except (KeyboardInterrupt):
print( '\033[31mSaída do usuário.\033[m')
return 0
else:
return n
num = leiaInt('Informe um valor inteiro válido.: ')
num1 = leiaFloat('Informe um valor real válido.: ')
print(f'O valor inteiro válido digitado foi {num} e o valor real digitado foi {num1}')
|
6a3b90ccd373ae78707026453b30d41266d7eba5 | Kaushal196/python-practice | /oop/class.py | 600 | 3.9375 | 4 | class Employee:
def __init__(self, fname, lname, age):
#instance var unique for each instance
self.fname = fname
self.lname = lname
self.email = self.fname + '.' + self.lname + '@company.com'
self.age = age
def fullName(self):
return f'{self.fname} {self.lname}'
emp1 = Employee('Kaushal','Pandey', 25)
emp2 = Employee('Test','User', 30)
#emp1 and and emp2 are two diff instance of Employee class
print(emp1.email)
print(emp2.age)
print(emp1.fullName())
print(Employee.fullName(emp1)) #if we use this way we need to pass instance |
107db592ed941d5b89c10cb6ff4692bb84b83568 | kil23levrai/kil23levrai.github.io | /scripts/sierpinski.py | 1,028 | 3.609375 | 4 | import turtle
turtle.tracer(0,0)
turtle.screensize(2000,2000)
turtle.pu()
turtle.goto(-500,0)
turtle.pd()
def dessiner(courbe, longueur, angle):
print("chaine finale " + courbe)
for caractere in courbe:
if caractere == '+': turtle.left(angle)
elif caractere == '-': turtle.right(angle)
elif caractere in ['F', 'G']: turtle.forward(longueur)
def sierpinski(chaine):
nouvelleChaine = ''
for lettre in chaine:
if lettre == 'F':
nouvelleChaine = nouvelleChaine + 'F-G+F+G-F'
elif lettre == 'G':
nouvelleChaine = nouvelleChaine + 'GG'
else :
nouvelleChaine = nouvelleChaine + lettre
print("chaine en cours " + nouvelleChaine)
return nouvelleChaine
def courbeSier(motifInitial, niter):
courbe = motifInitial
for i in range(niter):
courbe = sierpinski(courbe)
return courbe
longueur = 10
angle = 120
niter = 2
dessiner(courbeSier('F', niter), longueur, angle)
turtle.update()
turtle.exitonclick() |
e68428b8f1940a06f3fb934012da7cbff9899103 | charliealpha094/Introduction-to-Python-Programming-for-Business-and-Social-Sciences-Applications | /Chapter_2/End_of_chapter_2/2_1.py | 249 | 4.03125 | 4 | # Done by Carlos Amaral (2020/09/17)
value = input("Please, enter an integer between 1 and 100: ")
def number(value):
return (int(value))
print("The entered value is: ", number(value), ".", "The square of entered value is: ", number(value)**2)
|
fd76226d22bb9d3d1fe3b590f173ffac5a0f6fc0 | smileyoung1993/python_practice | /practice01_2.py | 254 | 3.65625 | 4 | ##q2
num = input("수를 입력하세요:")
try:
num = int(num)
if isinstance(num,int):
if num % 2 == 0:
print("짝수")
else:
print("홀수")
except ValueError:
print("정수가 아닙니다.")
|
675cab25b795ce494e4e3881ea8802b07bb45574 | JackyXiong8/Dojo_Assignments | /Python/dictionaryBasics.py | 178 | 4.125 | 4 |
info = {"Name":"Jacky","Age":"19","Country of birth":"China","favorite language":"Python"}
print (info.items())
for key, data in info.items():
print ("My",key,"is",data) |
3a6a2079749eda524dca598a35a84c24dfa7f4bc | pronob1010/Data_Science_Project_with_Edu_data | /problem solve/venv/hkch9.py | 204 | 3.53125 | 4 | student_marks = {}
for i in range(int(input())):
n = input().split()
scores = list(map(float, n[1:]))
student_marks[n[0]] = sum(scores)/float(len(scores))
print("%.2f"%student_marks[input()]) |
4c17c718374acbeee6cce24d5d8f2c45e5e0b886 | jeffsnguyen/Python | /Level_5/Homework/Section_5_2_Decorators/Exercise_3/loan/loan_base.py | 14,710 | 3.71875 | 4 | # Type: Homework
# Level: 5
# Section: 5.1: Date/Time
# Exercise: 6
# Description: This contains Loan class methods, modified to handle exception
# Modify your Loan classes to take a loan start date and loan end (maturity) date instead of a term
# parameter. Create a term method that calculates and returns the loan term (in months) from the
# two dates. Assume that a month is 30 days and that you round the fractional month to the nearest integer.
# Importing packages
from asset.asset import Asset
from utils.timer import Timer
from utils.memoize import Memoize
import logging
#######################
#######################
# loan class
# This class object takes on the arguments asset, face, rate, term
class Loan(object):
# Initialization function with asset, face, rate, maturity start and end date
# Also included in this function is ability to set the arguments to 0 if they don't already exists
def __init__(self, notional, rate, maturity_start, maturity_end, asset):
# Main attributes
self._notional = notional
self._rate = rate
self._maturity_start = maturity_start
self._maturity_end = maturity_end
if not isinstance(asset, Asset):
logging.error('Something wrong with parameters type.') # Log the error prior to raising it
raise ValueError('asset must be of Asset type.')
else:
self._asset = asset
# Wrapper to display
def __repr__(self):
return f'{self.__class__.__name__}({self._notional}, {self._rate}, ' \
f'{self._maturity_start}, {self._maturity_end}, {self._asset})'
##########################################################
# Decorators to define and set values for instance variables
# Decorator to create a property function to define the attribute notional
@property
def notional(self):
return self._notional
# Decorator to set notional value
@notional.setter
def notional(self, inotional):
self._notional = inotional # Set instance variable notional from input
# Decorator to create a property function to define the attribute rate
@property
def rate(self):
return self._rate
# Decorator to set interest rate
@rate.setter
def rate(self, irate):
self._rate = irate # Set instance variable rate from input
# Decorator to create a property function to define the attribute asset
@property
def asset(self):
return self._asset
# Decorator to set loan asset value
@asset.setter
def asset(self, iasset):
self._asset = iasset # Set instance variable asset from input
# Decorator to create a property function to define the attribute maturity_start
@property
def maturity_start(self):
return self._maturity_start
# Decorator to set loan maturity start datetime value
@maturity_start.setter
def maturity_start(self, imaturity_start):
self._maturity_start = imaturity_start # Set instance variable maturity_start from input
# Decorator to create a property function to define the attribute maturity_end
@property
def maturity_end(self):
return self._maturity_end
# Decorator to set loan maturity end datetime value
@maturity_end.setter
def maturity_end(self, imaturity_end):
self._maturity_end = imaturity_end # Set instance variable maturity_end from input
##########################################################
##########################################################
# Add instance method functionalities to loan class
# Instance method to return timedelta of start date and end datetime parameters
def term(self):
time_delta = abs(self._maturity_start - self._maturity_end)
logging.debug(f'Calculated time_delta = {time_delta}')
# Lookup dict in terms of microseconds
dT_dictMS = {'months': 2592000000000,
'days': 86400000000,
'hours': 3600000000,
'minutes': 60000000,
'seconds': 1000000,
'microseconds': 1}
# Calculate total microseconds as the base
total_microseconds = time_delta.days * dT_dictMS['days'] + time_delta.seconds * dT_dictMS['seconds'] + time_delta.microseconds
logging.debug(f'Total base microseconds = {total_microseconds}')
return round(total_microseconds / dT_dictMS['months'])
# Instance method to return timedelta of start date and end datetime parameters
# Instance method to calculate monthly payments
# Now modified to delegate to calcMonthlyPmt() which is a class method
# Add dummy period argument to handle exceptions where some loan type
# can have monthly payment dependent on the period
def monthlyPayment(self, period=None):
# Calculate payment using the formula pmt = (r * P * (1 + r)**N) / ((1 + r)**N - 1)
# r = monthly rate, P = notional value, N = term in months
# DIV/0 exception handling: print and warning message and return value of None
try:
# Capture step/job done to debug
logging.debug('Step: Trying to calculate monthlyPayment')
return self.calcMonthlyPmt(self._notional, self.getRate(period), self.term())
except ZeroDivisionError:
raise ZeroDivisionError('Term value cannot be 0. Division by 0 exception. Not possible to calculate')
# Instance method to calculate total payments
def totalPayments(self):
# Calculate total payment using the formula total = monthlyPayment * term * 12
# r = monthly rate, P = notional value, N = term in months
try:
# Capture step/job done to debug
logging.debug('Step: Trying to calculate totalPayments using monthlyPayments and term')
return self.monthlyPayment() * self.term()
except ZeroDivisionError:
raise ZeroDivisionError('Term value cannot be 0. Division by 0 exception. Not possible to calculate')
# Instance method to calculate total interest over the entire loan
def totalInterest(self):
# Calculate payment using the formula total_interest = totalpayment = notional value
try:
# Capture step/job done to debug
logging.debug('Step: Trying to calculate totalInterest using totalPayments and notional')
return self.totalPayments() - self._notional
except ZeroDivisionError:
raise ZeroDivisionError('Term value cannot be 0. Division by 0 exception. Not possible to calculate')
# Instance method to calculate interest due at time t
# This method use the given formula
def interestDue(self, t):
if t > self.term()/12:
logging.info('t value is greater than term')
# Calculate payment using the formula interestDue = r * loan balance bal
# r = monthly rate, P = notional value, N = term in months
# Capture step/job done to debug
logging.debug('Step: Trying to calculate totalInterest using totalPayments and notional')
return self.monthlyRate(self.getRate(t)) * self.balance(t - 1)
# Instance method to calculate principal due at time t
# This method use the given formula
def principalDue(self, t):
if t > self.term()/12:
logging.info('t value is greater than term')
# Calculate payment using the formula principalDue = monthlyPayment - interestDue
# r = monthly rate, P = notional value, N = term in months
# Capture step/job done to debug
logging.debug('Step: Trying to calculate principalDue using monthlyPayments and interestDue')
return self.monthlyPayment(t) - self.interestDue(t)
# Instance method to calculate remaining loan balance due at time t
# This method use the given formula
# Modified to delegate to calcBalance(face, rate, term, period)
# Notional is equivalent to face
def balance(self, t):
if t > self.term()/12:
logging.info('t value is greater than term')
# Calculate payment using the formula bal = P(1+r)**n - pmt*[((1+r)**n -1)/r]
# r = monthly rate, P = notional value, N = term in months
# Capture step/job done to debug
logging.debug('Step: Trying to calculate balance using calcBalance')
return self.calcBalance(self._notional, self.getRate(t), self.term(), t)
# Instance method to calculate interest due at time t
# This method use the recursive function
@Memoize
def interestDueRecursive(self, t):
# Warn user when running a recursive function
# Capture step/job done to debug
logging.warning('Step: You are running a recursive function. This will take a long time.')
if t > self.term()/12:
logging.info('t value is greater than term')
# Calculate payment using recursive functions
if t == 1:
# Capture step/job done to debug
logging.debug('Step: Trying to calculate interestDueRecursive, return notional * monthlyRate if term = 1')
return self._notional * self.monthlyRate(self.getRate(t))
else:
# Capture step/job done to debug
logging.debug('Step: Trying to calculate interestDueRecursive, '
'return balanceRecursive(t-1) * monthlyRate if term != 1')
return self.balanceRecursive(t - 1) * self.monthlyRate(self.getRate())
# Instance method to calculate principal due at time t
# This method use the recursive function
@Memoize
def principalDueRecursive(self, t):
# Warn user when running a recursive function
# Capture step/job done to debug
logging.warning('Step: You are running a recursive function. This will take a long time.')
if t > self.term()/12:
logging.info('t value is greater than term')
# Calculate payment using recursive functions
# Capture step/job done to debug
logging.debug('Step: Trying to calculate principalDueRecursive, return monthlyPayment - interestDueRecursive')
return self.monthlyPayment() - self.interestDueRecursive(t)
# Instance method to calculate remaining loan balance due at time t
# This method use the recursive function
@Memoize
def balanceRecursive(self, t):
# Warn user when running a recursive function
# Capture step/job done to debug
logging.warning('Step: You are running a recursive function. This will take a long time.')
if t > self.term()/12:
logging.info('t value is greater than term')
# Calculate payment using recursive functions
if t == 1:
# Capture step/job done to debug
logging.debug('Step: Trying to calculate balanceRecursive, '
'return notional - principalDueRecursive if term = 1')
return self._notional - self.principalDueRecursive(t)
else:
# Capture step/job done to debug
logging.debug('Step: Trying to calculate interestDueRecursive, '
'return balanceRecursive(t-1) - principalDueRecursive if term != 1')
return self.balanceRecursive(t - 1) - self.principalDueRecursive(t)
# Instance method to get interest rate from Loan object.
def getRate(self, period=None):
# Capture step/job done to debug
logging.debug('Step: Trying to get rate by simply returning rate parameters.')
return self._rate
# Instance method to return the current asset value for the given period times a recovery multiplier of .6
def recoveryValue(self, t):
# Capture step/job done to debug
logging.debug('Step: Trying to calculate recoveryValue by asset.value(t) * .6.')
if t > self.term()/12:
logging.info('t value is greater than term')
return self._asset.value(t) * .6
# Instance method to return the available equity (current asset value less current loan balance)
def equity(self, t):
# Capture step/job done to debug
logging.debug('Step: Trying to calculate equity by asset.value(t) - balance(t).')
if t > self.term()/12:
logging.info('t value is greater than term')
return self._asset.value(t) - self.balance(t)
##########################################################
##########################################################
# Add class method functionalities to loan class
# Class method to calculate the monthly payment of the given loan
# Calculate payment using the formula pmt = (r * P * (1 + r)**N) / ((1 + r)**N - 1)
# r = monthly rate, P = notional value, N = term in months
@classmethod
def calcMonthlyPmt(cls, face, rate, term):
try:
# Capture step/job done to debug
logging.debug('Step: Trying to calculate calcMonthlyPmt')
return (cls.monthlyRate(rate) * face * (1 + cls.monthlyRate(rate)) **
term) / (((1 + cls.monthlyRate(rate)) ** term) - 1)
except ZeroDivisionError:
logging.error('Something went wrong. Division by 0.') # Log the error prior to raising it
raise ZeroDivisionError('Term value cannot be 0. Division by 0 exception. Not possible to calculate')
# Class method to calculate outstanding balance of the given loan at given period
# Calculate payment using the formula bal = P(1+r)**n - pmt*[((1+r)**n -1)/r]
# r = monthly rate, P = notional value, N = term in months
@classmethod
def calcBalance(cls, face, rate, term, period):
# Capture step/job done to debug
logging.debug('Step: Trying to calculate calcBalance')
return face * ((1 + cls.monthlyRate(rate)) ** period) - \
(cls.calcMonthlyPmt(face, rate, term) *
(((1 + cls.monthlyRate(rate)) ** period - 1) / cls.monthlyRate(rate)))
##########################################################
# Add static method functionalities to loan class
@staticmethod
def monthlyRate(annual_rate):
# Capture step/job done to debug
logging.debug('Step: Trying to calculate monthlyRate')
return annual_rate / 12
# Static method to return annual rate for a passed in monthly rate
# Annual rate = Monthly Rate * 12
@staticmethod
def annualRate(monthly_rate):
# Capture step/job done to debug
logging.debug('Step: Trying to calculate annualRate')
return monthly_rate * 12
##########################################################
|
028f094cab468d133674b6854822b1a06ec6b860 | brufino/YHack-Chug2Puff | /water_vis_app_skeleton.py | 1,381 | 3.875 | 4 | import time
def calc_water_goal():
# Calculate the water goal
# return water_goal
# If a water value is entered into the GUI, store value
def water_input(ml):
current_intake += ml
return current_intake
# Changes the puffer fish image depending on water intake
def fish_change(water_goal, current_intake):
if(0.33*water_goal >= current_intake >= 0):
#use fish image 1
elif(0.33*water_goal < current_intake <= 0.66*water_goal):
#use fish image 2
else():
#use fish image 3
# resets counters and pushes final value on day change
def daily_reset():
#push water counter to array
current_intake = 0
# Line below means "ONLY run this code below when I call the current file"
# If you include this file in another script the code below will not run
if __name__ == "__main__":
calc_water_goal()
current_day=strftime("%d")
current_intake = 0
while True:
# activates if a value is passed in from the GUI
if ( //a GUI value is entered// ):
water_input(val_from_GUI)
fish_change(water_goal, current_intake)
# activates if the date does not match the one
# initialized in the beginning of the script
if(current_day != strftime("%d"))
daily_reset():
current_day = strftime("%d")
else():
continue
|
d5b09854525690c951348dc2f883d53e87bbd5fe | Riley-Kilgore/IrisDataSet | /main.py | 699 | 3.515625 | 4 | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
import numpy as np
'''The following is the training of a logistic regression model upon the iris dataset. Only 70% of the data
is used and there are no predictions made within this file.'''
data = pd.read_csv("iris.data", names=["Sepal Length", "Sepal Width", "Petal Length", "Petal Width", "Type"])
data = data.sample(frac=1).reset_index(drop=True)
train, test = train_test_split(data, train_size=.7, test_size=.3)
model = LogisticRegression()
train_X, train_y = np.split(train,[-1],axis=1)
model.fit(train_X, train_y)
test_X, test_y = np.split(test, [-1], axis=1) |
f3ef56322a500563561dd7dfe3e40b4897d41019 | jiangh2/01-IntroductionToPython | /src/m6_your_turtles.py | 1,736 | 3.65625 | 4 | """
Your chance to explore Loops and Turtles!
Authors: David Mutchler, Dave Fisher, Vibha Alangar, Amanda Stouder,
their colleagues and Hao Jiang.
"""
###############################################################################
# TODO: 1.
# On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name.
###############################################################################
###############################################################################
# TODO: 2.
# You should have RUN the m5e_loopy_turtles module and READ its code.
# (Do so now if you have not already done so.)
#
# Below this comment, add ANY CODE THAT YOU WANT, as long as:
# 1. You construct at least 2 rg.SimpleTurtle objects.
# 2. Each rg.SimpleTurtle object draws something
# (by moving, using its rg.Pen). ANYTHING is fine!
# 3. Each rg.SimpleTurtle moves inside a LOOP.
#
# Be creative! Strive for way-cool pictures! Abstract pictures rule!
#
# If you make syntax (notational) errors, no worries -- get help
# fixing them at either this session OR at the NEXT session.
#
# Don't forget to COMMIT-and-PUSH when you are done with this module.
###############################################################################
import rosegraphics as rg
window = rg.TurtleWindow()
bryan = rg.SimpleTurtle('turtle')
bryan.pen = rg.Pen('midnight blue', 3)
bryan.speed = 20
size1 = 100
liw4 = rg.SimpleTurtle('turtle')
liw4.pen = rg.Pen('green', 3)
liw4.speed = 20
size2 = 100
for k in range(25):
bryan.draw_square(size1)
bryan.pen_up()
bryan.right(45)
bryan.forward(10)
bryan.right(45+k)
bryan.pen_down()
liw4.draw_circle(size2)
liw4.right(14.4)
size1 = size1 - 2
window.close_on_mouse_click() |
6fac13bc2aca27233aadb3546ff629a9448784c9 | eun2ce/TIL | /algo/recurrence_relation.py | 508 | 3.921875 | 4 | def factorial1(n):
if n == 0 :
return 1
else:
return n * factorial1(n-1)
def recursive0(n):
if n == 0 :
return 1
else:
# reference loop0.py
loop3(n)
return n*n*recursive0(n-1)
def recursive1(n):
if n == 0 :
return 1
else:
loop3(n)
return n*recursive1(n-1)*recursive1(n-1)
def recursive2(n):
if n == 0:
return 1
else:
a = factorial1(n)
return a*recursive2(n/2)*recursive2(n/2)
|
c61d3b8f54c6c5300d9bbd9f1c983efb7ce5eec0 | mahalakshmima/python1 | /g4.py | 110 | 3.953125 | 4 | ma1=input()
if(ma1 >='a' and ma1 <='z') or (ma1 >='A' and ma1 <='Z'):
print("Alphabet")
else:
print("No")
|
847a916a086113a0904eae26b8fcbef98ba8c61c | lpmg11/ejercicios_python | /sumaYMedia.py | 338 | 3.953125 | 4 | suma = 0
c = 0
def numeros(suma, c):
n = int(input("Ingrese un numero: "))
if n !=0:
suma = suma + n
c = c + 1
numeros(suma,c)
else:
print("La suma de los numeros ingresados es: ", suma)
print("La media de los numeros es: ", suma/c)
if __name__ == "__main__":
numeros(suma , c)
|
3e37382832e6d9ea23efeb6508716a25b1b411ae | CutiePizza/holbertonschool-higher_level_programming | /0x10-python-network_0/6-peak.py | 522 | 3.859375 | 4 | #!/usr/bin/python3
"""
Find peak
"""
def find_peak(list_of_integers):
"""
method to find peak
"""
if len(list_of_integers) == 0:
return (None)
peak = list_of_integers[0]
for i in range(1, len(list_of_integers)):
try:
if (list_of_integers[i] > list_of_integers[i + 1] and
list_of_integers[i] > list_of_integers[i - 1]
):
peak = list_of_integers[i]
except IndexError:
pass
return (peak)
|
1997edf45ae984c10dd2edec0042c04e5a2200ca | willbaschab/COOP_2018 | /Chapter03/U03_EX09_TriangleSideArea.py | 1,107 | 4.375 | 4 | # U03_EX09_TriangleSideArea.py
#
# Author: Will Baschab
# Course: Coding for OOP
# Section: A2
# Date: 27 Sep 2018
# IDE: PyCharm
#
# Assignment Info
# Exercise: 09
# Source: Python Programming
# Chapter: 03
#
# Program Description
# Determines the area of a triangle given the side lengths inputted by the user.
#
#
#
# Algorithm (pseudocode)
# 1. import math
# 2. print introduction
# 3. get a, b, and c from user input
# 4. assign s to (a + b + c)/2
# 5. calculate area using formula: (sqrt(s * (s - a) * (s - b) * (s - c))
# 6. print area in complete sentence
#
import math
def main():
print("This program determines the area of a triangle",
"\ngiven the side lengths inputted by the user.")
a = float(input("\nEnter first side length of triangle: "))
b = float(input("\nEnter second side length of triangle: "))
c = float(input("\nEnter third side length of triangle: "))
s = (a + b + c)/2
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
print("\nThe area of a triangle with side lengths", str(a) + ",", str(b) + ",", c, "is", area)
main()
|
1bd4b6b20a5c0db89bffa592e64f685af7d614e4 | AaronYXZ/PyFullStack | /Leetcode/leetcode/editor/en/[915]Partition Array into Disjoint Intervals.py | 959 | 3.5 | 4 | #Given an array A, partition it into two (contiguous) subarrays left and right so that:
#
#
# Every element in left is less than or equal to every element in right.
# left and right are non-empty.
# left has the smallest possible size.
#
#
# Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.
#
#
#
# Example 1:
#
#
#Input: [5,0,3,8,6]
#Output: 3
#Explanation: left = [5,0,3], right = [8,6]
#
#
#
# Example 2:
#
#
#Input: [1,1,1,0,6,12]
#Output: 4
#Explanation: left = [1,1,1,0], right = [6,12]
#
#
#
#
#
# Note:
#
#
# 2 <= A.length <= 30000
# 0 <= A[i] <= 10^6
# It is guaranteed there is at least one way to partition A as described.
#
#
#
#
#
# Related Topics Array
#leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def partitionDisjoint(self, A: List[int]) -> int:
#leetcode submit region end(Prohibit modification and deletion)
|
8d92c3b5aa62b0046c955649f954c6526a6bb48e | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/word-count/fe243d8f65ef4a898a512fe9da9744ef.py | 211 | 3.765625 | 4 | from collections import Counter
def word_count(text):
stripped_text = ''.join([c for c in text.lower()
if c.isalnum() or c.isspace()])
return Counter(stripped_text.split())
|
0a52118a705597fc8a7f157ac73264ac5e9155fc | maleksal/holbertonschool-higher_level_programming | /0x01-python-if_else_loops_functions/5-print_comb2.py | 246 | 3.734375 | 4 | #!/usr/bin/python3
def two_digit(num):
if num <= 9:
return 0
return ""
def space(num):
if num == 99:
return "\n"
return ", "
for i in range(100):
print("{}{}{}".format(two_digit(i), i, space(i)), end="")
|
6cbf8b5115cb0a054edeaf127471a223913574cf | rniemeyer07/public | /ipython_notebooks/rbm_find_grid_cell.py | 746 | 3.78125 | 4 | #!/usr/local/anaconda/bin/python
#script to enter a lat/lon and program will return lat/lon of grid cell that point resides in
# run the code like this: ./rbm_find_grid_cell.py 35.011301 -85.697354
import numpy as np
import os
import sys
def find_125_grid_Maurer(lat, lon):
'''Find the 1/8 grid cell that a (lat, lon) point falls in
(the 1/8 grid cells are Maurer's grids) Input arguments: lat, lon (can be single number or np array)
Return: lat_grid, lon_grid
Module requred: import numpy as np
'''
lat_grid = np.around(8.0*lat-0.5)/8.0 + 0.0625
lon_grid = np.around(8.0*lon-0.5)/8.0 + 0.0625
return lat_grid, lon_grid
lat_lon = find_125_grid_Maurer(float(sys.argv[1]),float(sys.argv[2]))
print(lat_lon)
|
31fead7baa2506702627cc3aab1e931c6ae689e5 | fearlessdinosaur/Algorithms | /Python/Sorts.py | 653 | 3.90625 | 4 | def Bubble(x):
print (x)
for i in range(0,len(x)):
y = []
#checks if changes have stopped
if( y == x):
break
y = x
#bubble sort loop
for j in range(1,len(x)):
if(x[j-1] > x[j]):
temp = x[j]
x[j] = x[j-1]
x[j-1] = temp
print(x)
def insertion(x):
print(x)
for i in range(1,len(x)):
y = x[i]
print("key:"+str(y))
z = i-1
while(z >=0 and x[z] > y):
x[z+1] = x[z]
z = z - 1
x[z+1] = y
print(x)
|
6634c0f5455ebecc6dc74d99a55b30f5960f3d16 | DIRT-X/dirtx | /codes/example_solver.py | 4,171 | 3.609375 | 4 | """This is the example_solver.py script for solving 1D hydraulics."""
import math as m
def calc_discharge(b, h, m_bank, S, k_st=None, n_m=None, D_90=None):
"""
Calulate discharge in SI units. Provide one of the optional parameters k_st, n_m, or D_90.
Arguments:
b (float): width (m)
h (float): depth (m)
m_bank (float): bank slope (-)
S (float): slope (-)
k_st (float): Strickler roughness (optional)
n_m (float): Manning roughness (optional)
D_90 (float): D90 for roughness (optional)
Returns:
``float`` of discharge in CMS
"""
if n_m:
k_st = 1 / n_m
elif D_90:
k_st = 26 / (D_90 ** (1/6))
A = h * (b + h * m_bank)
P = b + 2 * h * (m_bank ** 2 + 1) ** 0.5
return k_st * m.sqrt(S) * (A / P) ** (2 / 3) * A
def interpolate_h(Q, b, S0, m_bank=1.0, n_m=0.04, prec=0.001, **kwargs):
"""
Inverse calculation of normal water depth for a given discharge and channel geometry
uses Raphson-Newton Algorithm
Arguments:
Q (float): of target discharge in (m3/s)
b (float): of channel base width in (m)
S0 (float): of channel (energy) slope is (m/m)
m_bank (float): of channel bank inclination (dimensionless), default=1.0
n_m (float): of Manning's n, default=0.04
prec (float): of result precision (don't be too picky)
kst (float): of Strickler value supersedes n_m
d90 (float): of surface grain size supersedes n_m
Returns:
``float`` of flow depth in M
"""
# parse keyword arguments
for k in kwargs.items():
if "kst" in k[0]:
try:
n_m = 1 / float(k[1])
except TypeError:
print("ERROR: Provided kst value (%s) is not a number." % str(k[1]))
return None
except ZeroDivisionError:
print("ERROR: Provided kst value must not be zero.")
return None
if "d90" in k[0]:
try:
n_m = float(k[1])**(1/6) / 26.0
except TypeError:
print("ERROR: Provided kst value (%s) is not a number." % str(k[1]))
return None
# use for interpolation of flow depth
stability_exit = int(1/prec) # no iteration should need 10000 steps...
stability_counter = 0
h_n = 10.0 * prec
err = 1.0
while err > prec:
A = b * h_n + m_bank * h_n ** 2
P = b + 2 * h_n * m.sqrt(m_bank ** 2 + 1)
Qk = A ** (5 / 3) * m.sqrt(S0) / (n_m * P ** (2 / 3))
dA_dh = b + 2 * m_bank * h_n # correction factor for flow cross section
dP_dh = 2 * m.sqrt(m_bank ** 2 + 1) # correction factor for wetted perimeter
_f = n_m * Q * P ** (2 / 3) - A ** (5 / 3) * m.sqrt(S0) # correction factor
df_dh = 2 / 3 * n_m * Q * P ** (-1 / 3) * dP_dh - 5 / 3 * A ** (2 / 3) * m.sqrt(S0) * dA_dh
h_n = abs(h_n - _f / df_dh) # compute new value for flow depth
err = abs(Q - Qk) / Q
stability_counter += 1
if stability_counter > stability_exit:
print("WARNING: No convergence reached. Interpolation break.")
h_n = None
break
msg0 = "\nInterpolated water depth: %0.5f m." % h_n
msg1 = "\nTarget discharge: %0.5f m3/s." % Q
msg2 = "\nYielded discharge: %0.5f m3/s." % Qk
print("Finished interpolation." + msg0, msg1, msg2)
return h_n
if __name__ == '__main__':
# -- START MODIFICATION BLOCK: MODIFY INPUT PARAMETERS HERE
# Q = 15.5 # discharge in (m3/s)
b = 5.1 # bottom channel width (m)
h_init = 1.55 # flow depth for discharge calculation (m)
m_bank = 2.5 # bank slope
k_st = 20 # Strickler value
n_m = 1 / k_st # Manning's n
S_0 = 0.005 # channel slope
# -- END MODIFICATION BLOCK
Q = calc_discharge(b, h_init, m_bank, S_0, k_st=k_st)
print("Calculated discharge = %0.3f m3/s for flow depth = %.3f m." % (Q, h_init))
# call the solver with user-defined channel geometry and discharge
h_n = interpolate_h(Q, b, n_m=n_m, m_bank=m_bank, S0=S_0, prec=10**-5)
|
770375871053b9e8ffc9ec196045490a6e2b098a | andre-williamson/the-FizzBuzz-game.py | /main.py | 228 | 3.96875 | 4 | #Write your code below this row 👇
nums = 0
for nums in range(0,101):
print(nums)
if nums % 3 == 0 and nums % 5 ==0:
print("fizzbuzz")
if nums % 5 == 0:
print("buzz")
if nums % 3 == 0:
print("fizzbuzz") |
b47408b342fefb753fc30041e9d41d49c06057a9 | kosemMG/gb-python-basics | /1/1.py | 370 | 4.1875 | 4 | print('Hello world!')
first_name = input('Enter your name: ')
surname = input('Enter your surname: ')
print(f'Hello, {first_name} {surname}! I am happy to meet you!')
age = int(input('How old are you? '))
if age < 18:
print('I am sorry, you are not allowed to buy cigarettes.')
else:
print('You can buy cigarettes. But smoking is dangerous for your health!')
|
372733844f4725aae9a41467877a646b0ee4aad4 | achntj/2-semesters-of-python-in-HS | /same tuple.py | 403 | 4.25 | 4 | #Write a program to input a tuple and check if it contains all elements as same.
n=int(input("Enter number of characters in tuple: "))
t=(tuple())
for i in range(0,n):
a=int(input("Enter value for tuple: "))
t+=(a,)
c=t[1]
count=0
for k in range(0,len(t)):
if t[k]==c:
count+=1
if count==len(t):
print("All the elements are same")
else:
print("All elements aren't the same")
|
b33e49a14e1e0ecbbf9ca87aafc2566bebf572ba | brenuvida/cursoemvideo | /Aula10/exercicio_30.py | 218 | 3.96875 | 4 | from time import sleep
num = int(input('Digite um número inteiro: '))
num = num % 2
print('Analisando o número digitado')
sleep(3)
print('O número digitado é PAR'if num == 0 else 'O número digitado é IMPAR')
|
625868fef52804bff95d2071754d3cc10c864767 | DevBaki/Python_Examples_Basic | /25_PersonInstance.py | 215 | 3.9375 | 4 | class Person:
name = "Person"
def __init__(self, name=None):
self.name = name
baki = Person("Bake")
print(Person.name, baki.name)
issa = Person()
issa.name = "Issa"
print(Person.name, issa.name)
|
369def91ed15352d48060c55741b48bf34d1d307 | jeengland/Data-Structures | /lru_cache/lru_cache.py | 2,208 | 3.84375 | 4 | from doubly_linked_list.doubly_linked_list import DoublyLinkedList
"""
Our LRUCache class keeps track of the max number of nodes it
can hold, the current number of nodes it is holding, a doubly-
linked list that holds the key-value entries in the correct
order, as well as a storage dict that provides fast access
to every node stored in the cache.
"""
class LRUCache:
def __init__(self, limit=10):
self.limit = limit
self.length = 0
self.storage = DoublyLinkedList()
"""
Retrieves the value associated with the given key. Also
needs to move the key-value pair to the end of the order
such that the pair is considered most-recently used.
Returns the value associated with the key or None if the
key-value pair doesn't exist in the cache.
"""
def get(self, key):
current = self.storage.head
while current is not None:
if current.value[0] == key:
self.storage.move_to_front(current)
return current.value[1]
current = current.next
return None
"""
Adds the given key-value pair to the cache. The newly-
added pair should be considered the most-recently used
entry in the cache. If the cache is already at max capacity
before this entry is added, then the oldest entry in the
cache needs to be removed to make room. Additionally, in the
case that the key already exists in the cache, we simply
want to overwrite the old value associated with the key with
the newly-specified value.
"""
def set(self, key, value):
current = self.storage.head
replaced = False
while current is not None and replaced is not True:
if current.value[0] == key:
current.value[1] = value
self.storage.move_to_front(current)
replaced = True
current = current.next
if self.length == self.limit and replaced is not True:
self.storage.remove_from_tail()
self.storage.add_to_head([key, value])
elif replaced is not True:
self.storage.add_to_head([key, value])
self.length = self.storage.length
|
9bc9e958fca5a0bbf0bae45066d7b1753518b5c0 | buwangkehan/CS132 | /hwk6code/hwk6.py | 6,819 | 3.984375 | 4 | import numpy as np
import sys
import matplotlib as mp
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import obj2clist as obj
####################################################
# modify the following 5 functions
# all functions assume homogeneous coordinates in 3D
####################################################
def project(d):
"""
returns the projection matrix corresponding to having the viewpoint at (0,0,d)
and the viewing plane at z=0 (the xy plane).
"""
# your code here
return(np.array([[1,0,0,0],[0,1,0,0],[0,0,0,0],[0,0,-1/d,1]]))
def moveTo(start, end):
"""
returns the matrix corresponding to moving an obj from position 'start' to position 'end.'
positions are given in 3D homogeneous coordinates.
"""
# your code here
# calculate the distance the ball need travel
distance1 = end[0] - start[0]
distance2 = end[1] - start[1]
distance3 = end[2] - start[2]
return np.array([[1,0,0,distance1], [0,1,0,distance2], [0,0,1, distance3], [0,0,0,1]])
def rotate(x,y,z,loc):
"""
returns the matrix corresponding to first rotating a value 'x' around the x-axis,
then rotating 'y' around the y-axis, and then 'z' around the z-axis. All angles
are in radians. The center of rotation is at point given by 'loc' (3D homogeneous coord).
"""
# your code here
# start = loc, end = np.array 0,0,0,0, run moveTo
all_zeros = np.array([0,0,0,0])
move1 = moveTo(loc, all_zeros)
move2 = moveTo(all_zeros, loc) #move back to original position
# rotate entire coordinate system
xaxis = np.array([[1,0,0,0], [0,np.cos(x),-np.sin(x),0], [0,np.sin(x),np.cos(x),0], [0,0,0,1]])
yaxis = np.array([[np.cos(y),0,np.sin(y),0], [0,1,0,0], [-np.sin(y),0,np.cos(y),0], [0,0,0,1]])
zaxis = np.array([[np.cos(z),-np.sin(z),0,0], [np.sin(z),np.cos(z),0,0], [0,0,1,0], [0,0,0,1]])
result = np.dot(xaxis,yaxis).dot(zaxis)
return np.dot(move2, result).dot(move1)
def ballTransform(i,loc):
"""
returns the appropriate transformation matrix for the ball. The center of the ball
before transformation is given by 'loc'. The appropriate transformation depends on the
timestep which is given by 'i'.
"""
# replace the following with your code
# setting default projection
defaultmatrix = project(100)
tempLoc = loc.copy()
# for each timestep from 0 through 49, the ball moves 1/2 foot toward the observer,
if(i >= 0 and i <= 49):
tempLoc[2] = tempLoc[2] + .5*i
# calculate radians
radians = 2.0 * np.pi * (i/100)
rotation = rotate(radians,0,0,tempLoc)
# for timesteps 50 through 64, the ball moves 2 feet in the negative x direction (starting from where the ball was at time i = 50.)
elif(i >= 50 and i <= 64):
tempLoc[0] = tempLoc[0] + -2*(i-50) #2 feet in the negative x direction
tempLoc[2] = tempLoc[2] + 24
radians = 2.0 * np.pi * ((i-50)/100)
rotation = rotate(0,0,radians,tempLoc)
#for timesteps i 65-149, rotate camera around origin, completing one full circle while pointing toward the origin
elif(i >= 65 and i <= 149):
tempLoc[0] = tempLoc[0] - 28 # -2*(64-50)
tempLoc[2] = tempLoc[2] + 24
#radians that needed in order to do one full circle
radians = ((-2 * np.pi)/84) * (i - 65)
rotation = rotate(0,radians,0,np.array([0.,0.,0.,0.]))
newMartix = moveTo(loc, tempLoc)
return np.dot(defaultmatrix, rotation).dot(newMartix)
def houseTransform(i,loc):
"""
returns the appropriate transformation matrix for the house. The center of the house
before transformation is given by 'loc'. The appropriate transformation depends on the
timestep which is given by 'i'.
"""
# replace the following with your code
defaultmatrix = project(100) # set the defaultmatrix
if(i >= 65 and i <= 149):
#radians that needed in order to do one full circle
radians = ((-2 * np.pi)/84) * (i - 65)
rotation = rotate(0,radians,0,np.array([0.,0.,0.,0.]))
return np.dot(defaultmatrix,rotation)
#return projection matrix if i not i >= 65 and i <= 149
return defaultmatrix
#######################################
# No need to change any code below here
#######################################
def scale(f):
"""
returns a matrix that scales a point by a factor f
"""
return(np.array([[f,0.,0,0],[0,f,0,0],[0,0,f,0],[0,0,0,1]]))
# This function implements the animation. It will be called automatically if you
# run this entire file in the python interpreter. Or you call call runShow() directly from the
# interpreter prompt if you wish.
def runShow():
# read house data
# house is 10*houseScale feet high
with open('basicHouse.obj','r') as fp:
house = obj.obj2flist(fp)
house = obj.homogenize(house)
houseScale = 3.0
S = scale(houseScale)
d = np.array([-5., 4., 3., 1]) - obj.objCenter(house)
M = np.array([[1.,0,0,d[0]],[0,1,0,d[1]],[0,0,1,d[2]],[0,0,0,1]])
house = [S.dot(M).dot(f) for f in house]
# read ball data
# ball has radius equal to ballScale feet
with open('snub_icosidodecahedron.wrl','r') as fp:
ball = obj.wrl2flist(fp)
ball = obj.homogenize(ball)
ballScale = 2.0
S = scale(ballScale)
d = np.array([10.0, -0.5, 0., 1]) - obj.objCenter(ball)
M = np.array([[1.,0,0,d[0]],[0,1,0,d[1]],[0,0,1,d[2]],[0,0,0,1]])
ball = [S.dot(M).dot(f) for f in ball]
# set up drawing region
fig = plt.figure()
ax = plt.axes(xlim=(-50,50),ylim=(-50,50))
plt.plot(-40,-40,'')
plt.plot(40,40,'')
plt.axis('equal')
# create drawables
ballLines = []
for b in ball:
ballLines += ax.plot([],[],'b')
houseLines = []
for h in house:
houseLines += ax.plot([],[],'r')
# this is the drawing routine that will be called on each timestep
def animate(i):
M = ballTransform(i,obj.objCenter(ball))
for b,l in zip(ballLines, ball):
n = M.dot(l)
b.set_data(n[0]/n[3],n[1]/n[3])
M = houseTransform(i,obj.objCenter(house))
for b,l in zip(houseLines, house):
n = M.dot(l)
b.set_data(n[0]/n[3],n[1]/n[3])
fig.canvas.draw()
return houseLines,ballLines
# instantiate the animator.
# we are animating at max rate of 25Hz
# about the slowest that gives a sense of continuous motion
# but this will slow down if the scene takes too long to draw
anim = animation.FuncAnimation(fig, animate,
frames=150, interval=1000/25, repeat=False, blit=False)
plt.show()
if __name__ == "__main__":
runShow()
|
a8ef368dd368cf9556a49719830768c44611fec7 | hazharaziz/algorithmus-prime | /1-sorting/insertion_sort/python/test_insertion_sort.py | 1,069 | 3.671875 | 4 | import unittest
from unittest import result
from insertion_sort import *
class TestInsertionSort(unittest.TestCase):
def test_empty_list(self):
numbers = []
insertion_sort(numbers)
self.assertIsNotNone(numbers)
self.assertEqual(0, len(numbers))
def test_single_element_list(self):
numbers = [1]
insertion_sort(numbers)
self.assertIsNotNone(numbers)
self.assertEqual(1, len(numbers))
self.assertEqual(1, numbers[0])
def test_list_of_numbers(self):
numbers_1 = [4, 2, 5, 1]
numbers_2 = [31, 41, 59, 26, 41, 58]
insertion_sort(numbers_1, False)
self.assertIsNotNone(numbers_1)
self.assertEqual(4, len(numbers_1))
self.assertListEqual([5, 4, 2, 1], numbers_1)
insertion_sort(numbers_2)
self.assertIsNotNone(numbers_2)
self.assertEqual(6, len(numbers_2))
self.assertListEqual([26, 31, 41, 41, 58, 59], numbers_2)
if __name__ == '__main__':
unittest.main() |
a0b37deb29c1a16ca1c1f547e5467ea96d1a5412 | ifscher/python-library | /aweefa.py | 437 | 3.875 | 4 | '''
USER INPUT e FORMAT
'''
# nome = input('Digite seu nome: ')
# n1 = int(input('Número 1: '))
# n2 = int(input('Número 2: '))
# t = n1 + n2
# print('Vsf, {1}. Azar. {0}'.format(nome, t))
'''
ORDEM DE PRECEDËNCIA
1. ()
2. ** (potëncia)
3. * / // % (últimos são divisão real e e resto)
4. + -
'''
pqp = 10 / 3
print(f'Imprimir um número float com só 2 caracteres depois da vírgula {pqp:.2f}', end='. VSF. ')
print('AH')
|
60d5c3fa275689796deb4ed8fcaaef7a689b7958 | OctavianusAvg/Donny | /43.py | 1,593 | 3.53125 | 4 | '''
Задано два натуральних числа a і b. Змінній w привласнити значення
істина, якщо в одновимірному цілочисельному масиві є хоча б один елемент, кратний а
і не кратний b.
Виконав : Канюка Р. 122В
'''
import numpy as np
import random
def numUserInput(arr, message):
'''Ініціалзіцая масиву дійсних чисел користувачем.
Приймає масив та загальне повідомлення.
'''
print(message)
while True:
try:
for i in range(len(arr)):
arr[i] = int(input(f'Введіть {i+1} елемент : '))
break
except ValueError :
print('Введіть число!')
return arr
while True:
#Ініціалізація масиву
while True:
try:
n = int(input(f'Введіть кількість елементів: '))
a = int(input(f'Введіть число a: '))
b = int(input(f'Введіть число b: '))
break
except ValueError :
print('Введіть число!')
X = numUserInput(np.empty(n),'Ініціалізація масиву')
#Знаходження результату
w = False
for i in X:
if i % a == 0 and i % b:
w = True
print('w =',w)
quest = input('Завершити програму? Y/N : ')
if(quest == 'Y' or quest == 'y'):
break
|
bc4109711eea49ded422877d3360313e4fd5cc68 | CHANDUVALI/Python_Assingment | /python2.py | 180 | 4.28125 | 4 | #Implement a program for finding a square of a number. (without using standard api)
num = float(input("Enter number: "))
mul = float(num*num)
print("Square of the number:",mul)
|
3973932e2f02a967fe86d89c8309fede51fc921a | Shalini-dixit/PythonRepository | /ListAssignment/functions/ThreeIntegerNumber.py | 285 | 3.9375 | 4 | def add(num1, num2):
return num1+num2
def subtract(num1, num2):
return num1-num2
def add_and_subtract(num1, num2, num3):
temp=add(num1,num2)
return subtract(temp,num3)
print(add_and_subtract(23,6,10))
print(add_and_subtract(1,17,30))
print(add_and_subtract(42,58,100)) |
bc926b95d2e450f384c167a83bd0c78b3e42d4ab | OlegSudakov/Programming-Problems | /hackerrank/coding_interview/strings_anagrams.py | 733 | 3.765625 | 4 | # https://www.hackerrank.com/challenges/ctci-making-anagrams
def number_needed(a, b):
aLetters = {}
bLetters = {}
for char in a:
if char in aLetters:
aLetters[char] += 1
else:
aLetters[char] = 1
for char in b:
if char in bLetters:
bLetters[char] += 1
else:
bLetters[char] = 1
dif = 0
for char in aLetters:
if char in bLetters:
dif += abs(aLetters[char] - bLetters[char])
else:
dif += aLetters[char]
for char in bLetters:
if char not in aLetters:
dif += bLetters[char]
return dif
a = input().strip()
b = input().strip()
print(number_needed(a, b))
|
d97a859623ad0af1ee130c77bb83a8be8fceda27 | BiYuqi/daily-practice | /Python/Python-Base-Practice/oop-high-level/use__slots__.py | 1,171 | 4 | 4 | # coding=UTF-8
# 继承方法
class MyMethod(object):
def __init__(self, options=None):
self.options = options
def is_object(self, t):
if isinstance(t, dict):
return 'yes'
obj = MyMethod()
L = {
"name": "test"
}
print(obj.is_object(L))
def get_list(*kw):
for i in kw:
print(i)
MyMethod.get_list = get_list
newObj = MyMethod()
newObj.get_list(1, 2, 3)
print('-------------------slots---------------')
"""
但是,如果我们想要限制实例的属性怎么办?比如,只允许对Student实例添加name和age属性。
为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class实例能添加的属性:
"""
# 用tuple定义允许绑定的属性名称
class Student(object):
__slots__ = ('name', 'age')
o = Student()
o.name = 'biyuqi'
print(o.name)
# 报错 'Student' object has no attribute 'score'
o.score = 90
# 由于'score'没有被放到__slots__中,所以不能绑定score属性
# 使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的: |
eccf2a66b9a15a994e85fd0d2b0259b0db73b937 | Ilyalya/learning | /lesson_003/01_days_in_month.py | 1,275 | 4.0625 | 4 | # -*- coding: utf-8 -*-
# (if/elif/else)
# По номеру месяца вывести кол-во дней в нем (без указания названия месяца, в феврале 28 дней)
# Результат проверки вывести на консоль
# Если номер месяца некорректен - сообщить об этом
# Номер месяца получать от пользователя следующим образом
user_input = input("Введите, пожалуйста, номер месяца от 1 до 12: ")
month = int(user_input)
months = [["Январь", 31],
["Февраль", 28],
["Март", 31],
["Апрель", 30],
["Май", 31],
["Июнь", 30],
["Июль", 31],
["Август", 31],
["Сентябрь", 30],
["Октябрь", 31],
["Ноябрь", 30],
["Декабрь", 31],
]
if 1 <= month <= 12:
print('Вы ввели', month)
print("Это", months[month-1][0])
print("В этом месяце", months[month-1][1], "день/дней")
else:
print("Вы ввели неверное значение! Введите число от 1 до 12")
|
df0d51c15b652a780c56e720a010c04c7a2be403 | anberns/TSP---Christofides | /submittedFiles/Archive/twoOpt/twoOPT.py | 5,731 | 3.75 | 4 | import sys
import math
import time
#code is influenced and inspired by this sites java implementation.
#http://www.technical-recipes.com/2017/applying-the-2-opt-algorithm-to-traveling-salesman-problems-in-java/
#as well as this site
#http://on-demand.gputechconf.com/gtc/2014/presentations/S4534-high-speed-2-opt-tsp-solver.pdf
#Create city class. TO store city data
class City:
def __init__(city, number, xCoord, yCoord):
city.cityName = number
city.x = xCoord
city.y = yCoord
#http://www.technical-recipes.com/2017/applying-the-2-opt-algorithm-to-traveling-salesman-problems-in-java/
#for finding distance algorithm
#distance between two cities. Gets called all the time
def distance(x1,y1,x2,y2):
distanceX = x2 - x1
distanceY = y2 - y1
twoCitiesDistance = int(round(math.sqrt(distanceX*distanceX + distanceY*distanceY)))
return twoCitiesDistance
#shoutout to this sites slideshow for 2opt code. I based mine off of the pseudo code found there.
##http://on-demand.gputechconf.com/gtc/2014/presentations/S4534-high-speed-2-opt-tsp-solver.pdf
def twoOPT(cityArray, tour):
minchange = -1 #minchange variable tracks wether or not change has occured.
while minchange <0:
minchange = 0
swap = False
#cycles through the tour
for i in range(len(tour)-2):
for j in range(i+2, len(tour)-1):
#change gets the result of the calculation (distance between node i to node J + the distance between the node after i and j
#then subtract the distance between node i and the node after it + the distance between J and the node after it)
#if the value in change is less than that in minchange we perform a swap. if value of change is smaller than
#minchange we have a more efficient route to switch to.
change = distance(cityArray[tour[i]].x, cityArray[tour[i]].y, cityArray[tour[j]].x, cityArray[tour[j]].y)+ distance(cityArray[tour[i+1]].x, cityArray[tour[i+1]].y, cityArray[tour[j+1]].x, cityArray[tour[j+1]].y) - distance(cityArray[tour[i]].x, cityArray[tour[i]].y, cityArray[tour[i+1]].x, cityArray[tour[i+1]].y)- distance(cityArray[tour[j]].x, cityArray[tour[j]].y, cityArray[tour[j+1]].x, cityArray[tour[j+1]].y)
if minchange > change: #if true aka 1 we must swap the paths
swap = 1
minchange = change
minI = i
minJ = j
#simple swap algo
if swap == 1:
temp = tour[minJ]
tour[minJ] = tour[minI+1]
tour[minI+1] = temp
return tour
#based on the algorithm presented in the assignment prompt.
def tourDistance(cityArray, tour):
dist = 0
for i in range(len(cityArray)-1):
dist += distance(cityArray[tour[i]].x,cityArray[tour[i]].y,cityArray[tour[i+1]].x, cityArray[tour[i+1]].y)
#find the distance from the first to last city and add it to total distance for a complete distance measurement of the tour.
dist += distance(cityArray[tour[0]].x, cityArray[tour[0]].y, cityArray[tour[-1]].x, cityArray[tour[-1]].y)
return dist
def main():
fileName = sys.argv[1]
file = fileName + '.txt'
with open(file) as data:
cityArray = []
for line in data:
line = line.split() # this gets fixes issues with blank
if line: #if there is a value in the line, put it in the array
cityInfo = []
for value in line:
cityInfo.append(value) # put each value into city info
#the city identifyer, x coord and y coord
city = City(int(cityInfo[0]), int(cityInfo[1]), int(cityInfo[2])) #create a new object and apply the details we recieve from txt file
cityArray.append(city) #append the object to the array of cities
start = time.perf_counter()
#create tours for possible start points
#builds a tour of cities array based on nearest neighbor.
for p in range(len(cityArray)):
tourArray = [p]
x = 0
while x != len(cityArray)-1:
i = tourArray[-1]
lastDistance = float('inf')
for j in cityArray:
#if city is not in the tour, find the distance to the city
#if the distance is less than or equal to the most recent distance
#make that distance most recent and make j.cityname the current city to travel from next
#this makes sure we only travel to the next nearest neighbor.
if j.cityName not in tourArray:
d = distance(cityArray[i].x, cityArray[i].y, j.x, j.y)
if d <= lastDistance:
lastDistance = d
currentCity = j.cityName
tourArray.append(currentCity)
x += 1
#call twoOPT as tour parameter for function because that gives us the optimal tour to work with
totalDistance = tourDistance(cityArray, twoOPT(cityArray, tourArray))
end = time.perf_counter()
timeElapsed = end - start
print(timeElapsed) #prints total time elapsed so we can track it for comp
#for file output, we just print a list from the optimal tour of the city array
#starting with the total distance on line 0
file = fileName + '.txt' + '.tour'
with open(file, 'w') as outPutFile:
outPutFile.write("%s" % totalDistance)
outPutFile.write("\n")
for val in twoOPT(cityArray, tourArray):
num = str(val)
outPutFile.write(num + "\n")
if __name__ == "__main__":
main() |
fbb50c60a18a2ac14463c9b4fef1b16c05edf481 | akshay-sahu-dev/PySolutions | /DS ALGO/Linked List/FInding the kth element from last.py | 1,281 | 3.9375 | 4 | ## FInd the kth element from last
class Node:
def __init__ (self, data = None):
self.data = data
self.next = None
class linked_list:
def __init__(self):
self.head = Node()
def push(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def find_k_from_last(self,k,):
first = org_head = self.head
second = self.head
count = 0
while self.head:
if count > k:
second = second.next
first = first.next
count += 1
self.head = self.head.next
self.head = org_head
print(f"\nThe kth element '{k}' from last is {second.data}")
def display(self):
temp = org_head = self.head
if not self.head:
print("Linked list is Empty")
return
while temp.next:
print(f"{temp.data} --> ", end = "")
temp = temp.next
# self.head = org_head
if __name__ == "__main__":
my_list = linked_list()
my_list.push(4)
my_list.push(5)
my_list.push(3)
my_list.push(7)
my_list.push(8)
my_list.push(43)
my_list.push(9)
my_list.display()
my_list.find_k_from_last(4)
|
11f5ce4487042ff6383e443d548f5f6942e5c18e | FisicaComputacionalOtono2018/20180816-clase-diagramadeflujoparprimo-jordetm5 | /test.py | 267 | 3.71875 | 4 | #Jorge Dettle Meza Dominguez
#16 de agosto del 2018
#
s=12
p=input("dame un numero :")
a=0
m=1
while s==0:
while p<s:
s=s*p
p=p+2
if p%2==0:
p=p+1
else :
while a<(p-1):
a=a+1
r=p%a
if r==0:
m=0
if m==0:
s=s-1
print(p)
|
3f531645ddad044b4d531539e4aef5db942c58ad | Timi-chen/TestDemo | /homework5.py | 351 | 3.546875 | 4 | import random
x=eval(input(""))
y=random.randint[0,30]
i=0
while(x!=y):
if(x<y):
print("遗憾!太小了")
i+=1
x=eval(input(""))
else:
print("遗憾!太大了")
i+=1
x=eval(input(""))
else:
print("预测{}次,你猜中了!".format(i))
print("I like zhbit")
print("我是大帅哥")
|
b6353eff9e1b91d62de897a4cbfc8931626f8b29 | 22Rahul22/Hackerrank | /Lists.py | 413 | 3.609375 | 4 | t = int(input())
b = []
for _ in range(t):
a = input().split()
s = a[0]
arr = a[1:]
if s == 'insert':
b.insert(int(arr[0], 10), int(arr[1], 10))
elif s == 'print':
print(b)
elif s == 'append':
b.append(arr[0])
elif s == 'remove':
b.remove(arr[0])
elif s == 'sort':
b.sort()
elif s == 'pop':
b.pop()
else:
b.reverse()
|
58a3527773f959036753865fbce0339de9a64edd | anu-coder/Basics-of-Python | /scripts/L2Q15_mathstring.py | 392 | 3.96875 | 4 | '''
Question: Write a program that computes
the value of a+aa+aaa+aaaa
with a given digit as the value of a.
Suppose the following input is supplied to the program:
9
Then, the output should be:
11106
'''
def mathstring(a):
s = 0
for i in range(1, 5):
s = s + int(a*i)
return s
if __name__=='__main__':
a = input('Enter any number: ')
print(mathstring(a)) |
88eb086f37a158134a204b8a4716f7e2fdc6c578 | abhishek2829/Python | /DictionaryExercise.py | 518 | 4.03125 | 4 | #Create a Dictionary and take input from the user and return the meaning of the word from the dictionary
d1={"abandon":"give up completely",
"Immutable":"Something that cannot be changed",
"Mutable":"Something that can be changed",
"RPA":"Robotic Process Automation"}
print("Please Input Your word from the given Dictionary")
print(d1.keys())
inpword = input("Please Input Your word from the given Dictionary: ")
print(inpword)
outmeaning = d1[inpword]
print(d1[inpword])
print(outmeaning)
|
9675d1c1ec03153aafa3db65b2f765e029ecd4ed | cielavenir/procon | /codingame/old/onboarding.py | 241 | 3.515625 | 4 | #!/usr/bin/python
import sys
if sys.version_info[0]>=3: raw_input=input
while 1:
n=int(raw_input())
mi=9999999
name=''
for i in range(n):
enemy,dist=raw_input().split()
if mi>float(dist):
mi=float(dist)
name=enemy
print(name) |
5665d46e0080a141052b521715d70bfc414c4bef | joaquimbermudes/ProjectEulerPython | /Problema2.py | 252 | 3.53125 | 4 | # Problema 2
# Encontrar a soma de todos os valores pares de uma sequencia de Fibonacci até 4.000.000
x1 = 1
x2 = 1
x = 0
s = 0
while x < 4000000:
x = x1 + x2
x2 = x1
x1 = x
if x % 2 == 0:
s = s + x
print(s)
|
e8ba941914d7f69388f8a16cf23e87d384f4c885 | romrell4/470-AI | /Reversi/Square.py | 1,653 | 3.71875 | 4 | import Enums
from Enums import Color, Direction
class Square:
def __init__(self, x, y, value):
self.x = x
self.y = y
self.value = value
self.piece = Color.EMPTY
self.neighbors = [None, None, None, None, None, None, None, None]
def canFlip(self, color, direction):
#Recursively check if can flip in given direction
neighborInDirection = self.neighbors[direction]
if self.piece != Color.opp[color] or neighborInDirection is None:
return False
return neighborInDirection.piece == color or neighborInDirection.canFlip(color, direction)
def flip(self, color, direction):
if self.piece == color:
return
self.neighbors[direction].flip(color, direction)
self.piece = color
def isPlayable(self, color):
#Can flip in at least one direction
if self.piece != Color.EMPTY:
return False
for i in range(len(self.neighbors)):
neighbor = self.neighbors[i]
if neighbor is None:
continue
if neighbor.canFlip(color, i):
return True
return False
def play(self, color):
#flip in every possible direction
if self.piece != Color.EMPTY:
return
self.piece = color
for i in range(len(self.neighbors)):
neighbor = self.neighbors[i]
if neighbor is None:
continue
if neighbor.canFlip(color, i):
neighbor.flip(color, i)
def __str__(self):
return "(" + str(self.x) + "," + str(self.y) + ")"
|
f4b8f6fd676c6c5f6970c98261e50f65cce6b925 | ThorsteinnAdal/webcrawls_in_singapore_shippinglane | /db_to_file_helpers/test_textLines_to_file.py | 3,247 | 3.546875 | 4 | __author__ = 'thorsteinn'
import unittest
from textLines_to_file import line_in_file, remove_line_from_file, add_unique_line_to_file
class Test_textLines_to_file(unittest.TestCase):
def setUp(self):
with open('unit_test_file.txt','w') as f:
f.write('this is the first line\n')
f.write('this line is repeated twice\n')
f.write('\n')
f.write('this line is repeated twice\n')
f.write('this line \"has quotation marks\"\n')
f.write('this is the last line\n')
def test_line_in_file(self):
self.assertTrue(line_in_file('this is the first line', 'unit_test_file.txt'), msg='FIRST LINE NOT FOUND')
self.assertTrue(line_in_file('this is the last line', 'unit_test_file.txt'), msg='LAST LINE NOT FOUND')
self.assertFalse(line_in_file('this line should not be found', 'unit_test_file.txt'), msg="A LINE THAT WASN'T THERE WAS FOUND")
self.assertTrue(line_in_file('', 'unit_test_file.txt'), msg="A BLANK WAS FOUND")
self.assertTrue(line_in_file('\n', 'unit_test_file.txt'), msg="A SIMPLE RETURN FAILED")
def test_remove_line_from_file(self):
self.setUp()
self.assertFalse(remove_line_from_file('this line is not in the file', 'unit_test_file.txt'), msg = "A LINE WAS REMOVED THAT DIDNT EXIST")
self.assertTrue(remove_line_from_file('this is the first line', 'unit_test_file.txt'), msg="THE FIRST LINE WAS NOT REMOVED")
self.assertFalse(remove_line_from_file('this is the first line', 'unit_test_file.txt'), msg="THE FIRST LINE WAS REMOVED TWICE")
self.assertTrue(remove_line_from_file('this is the last line', 'unit_test_file.txt'), msg="FAILED TO REMOVE THE LAST LINE")
self.assertTrue(remove_line_from_file('this line is repeated twice', 'unit_test_file.txt'), msg="A DUPLICATED LINE WAS NOT REMOVED")
self.assertTrue(remove_line_from_file('this line is repeated twice', 'unit_test_file.txt'), msg="THE SECOND DUPLICATED LINE WAS NOT REMOVED")
def test_add_unique_line_to_file(self):
with open('unit_test_file.txt', 'r') as f:
fl1 = len(f.read())
self.assertTrue(add_unique_line_to_file('a new line that is added', 'unit_test_file.txt'), msg="FAILED TO ADD A NEW LINE TO THE FILE")
with open('unit_test_file.txt', 'r') as f:
fl2 = len(f.read())
self.assertEqual(fl1+len('a new line that is added\n'), fl2, msg="THE RESULTING FILE IS OF INCORRECT LENGTH")
self.assertFalse(add_unique_line_to_file('a new line that is added', 'unit_test_file.txt'), msg="ADDED A NEW LINE TWICE TO THE FILE")
with open('unit_test_file.txt', 'r') as f:
fl3 = len(f.read())
self.assertEqual(fl2, fl3, msg="THE RESULTING FILE IS OF INCORRECT LENGTH WHEN NOTHING WAS TO BE ADDED")
self.assertFalse(add_unique_line_to_file('this is the last line', 'unit_test_file.txt'), msg="ADDED A PRE-EXISTING LINE")
def tearDown(self):
import os
os.remove('unit_test_file.txt')
def runTests():
suite = unittest.TestLoader().loadTestsFromTestCase(Test_JSON_to_file)
unittest.TextTestRunner(verbosity=2).run(suite)
if __name__ == '__main__':
unittest.main()
|
52b3dbd9cf16c3e549099e0cfaf2af51cfce7773 | maggielaughter/tester_school_dzien_5 | /list_test1.py | 358 | 4.0625 | 4 | numbers=[1,'foo',62,15,34]
"""for i in range(len(numbers)):
print(numbers[i])
print(' ')
for value in numbers:
print(value)
print(' ')
"""
for i in range(len(numbers)-1,-1,-1):
print(numbers[i])
print(' ')
for value in reversed(numbers):
print(value)
print(' ')
for idx, value in enumerate(reversed(numbers)):
print(idx, value)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.