blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
a986b19083aadd6d87d4499340f5c04b585c5a0f | v1ctor/advent-of-code-2019 | /day15/run.py | 4,973 | 3.78125 | 4 | import sys
from computer import Computer
class Droid:
def __init__(self, memory):
self.x = 0
self.y = 0
self.path = []
self.visited = {}
self.oxygen = None
self.computer = Computer(memory)
def move(self, direction):
self.path.append(direction)
if direction == 1:
self.y -= 1
elif direction == 2:
self.y += 1
elif direction == 3:
self.x -= 1
else:
self.x += 1
def direction(self, source, direction):
if direction == 1:
return (source[0], source[1] - 1)
elif direction == 2:
return (source[0], source[1] + 1)
elif direction == 3:
return (source[0] - 1, source[1])
else:
return (source[0] + 1, source[1])
def target(self, direction):
return self.direction((self.x, self.y), direction)
def backtrack(self):
direction = self.path[-1]
if direction == 1:
self.move(2)
self.path = self.path[:-2]
return 2
elif direction == 2:
self.move(1)
self.path = self.path[:-2]
return 1
elif direction == 3:
self.move(4)
self.path = self.path[:-2]
return 4
else:
self.move(3)
self.path = self.path[:-2]
return 3
def __dfs(self):
min_path = None
# The idea is to implement DFS with backtracking and keeping a minimum path
# The droid cannot do BFS because it has to return to the starting position anyway
for i in range(1, 5):
target = self.target(i)
if target in self.visited:
continue
self.computer.send(i)
self.computer.run()
status = self.computer.receive()
self.visited[target] = status
print("target {} direction {} status {} path {}".format(target, i, status, self.path))
if status != 0:
self.move(i)
# oxygen
if status == 2:
# if we found oxygen it means tha none of the neighbours of this node can have a shorter path
self.oxygen = target
min_path = len(self.path)
break
# moved
if status != 0:
result = self.__dfs()
if result != None and (min_path is None or result < min_path):
min_path = result
direction = self.backtrack()
self.computer.send(direction)
self.computer.run()
if self.computer.receive() == 0:
print("Error!")
return None
return min_path
def search_oxygen(self):
self.visited = {}
return self.__dfs()
def draw_map(self):
maxX = 0
minX = 0
maxY = 0
minY = 0
for key in self.visited.keys():
if key[0] < minX:
minX = key[0]
if key[0] > maxX:
maxX = key[0]
if key[1] < minY:
minY = key[1]
if key[1] > maxY:
maxY = key[1]
sizeX = abs(minX) + maxX + 1
sizeY = abs(minY) + maxY + 1
result = [[]] * sizeY
for y in range(sizeY):
result[y] = ["."] * sizeX
for x in range(sizeX):
pos = (x - abs(minX), y - abs(minY))
if pos in self.visited:
status = self.visited[pos]
if status == 0:
result[y][x] = "#"
if status == 2:
result[y][x] = "o"
print(''.join(result[y]))
def fill_oxygen(self):
if self.oxygen is None or self.oxygen not in self.visited or self.visited[self.oxygen] != 2:
return None
visited = {}
queue = []
time = 0
queue.append((self.oxygen, 0))
while len(queue) > 0:
current = queue[0][0]
time = queue[0][1]
queue = queue[1:]
for i in range(1, 5):
direction = self.direction(current, i)
if direction not in visited and direction in self.visited and self.visited[direction] == 1:
visited[direction] = True
queue.append((direction, time + 1))
return time
def main():
filename = "input.txt"
play = False
if len(sys.argv) > 1:
filename = sys.argv[1]
if len(sys.argv) > 2 and sys.argv[2] == "--play":
play = True
f = open(filename)
s = f.readline()
memory = list(map(int, s.split(",")))
droid = Droid(memory)
source = droid.search_oxygen()
print(source)
droid.draw_map()
time = droid.fill_oxygen()
print(time)
if __name__== "__main__":
main()
|
74b46e64b42bb5d3c980fa47d9fa7ca448ddbe51 | Aleksa21052001/vezbanje2 | /vezba 4/osnovni_zadaci/zadatak6.py | 378 | 3.75 | 4 | """
Napisati program koji pita korisnika da unese nekoliko reči odvojenih razmakom, potom ispisuje iste te
reči, samo što umesto razmaka ih program spoji dvotačkom. Potrebno je koristiti funkcije split i join.
"""
def main():
tekst = input("Unesite reci odvojene razmakom: ")
reci = tekst.split(" ")
novi_tekst = ":".join(reci)
print(novi_tekst)
main()
|
89ac0f2163e23b2562fe734719c3e7916caf96c1 | dwaipayan05/Django-Task | /friends/helper_function.py | 537 | 3.515625 | 4 | from math import radians,degrees,cos,sin,acos
def distance_finder(latitude_1,longitude_1,latitude_2,longitude_2):
latitude_1 = radians(latitude_1)
latitude_2 = radians(latitude_2)
longitude_difference = radians(longitude_1 - longitude_2)
distance = (sin(latitude_1)*sin(latitude_2)+cos(latitude_1)*cos(latitude_2)*cos(longitude_difference))
resToMile = degrees(acos(distance)) * 69.09
resToMt = resToMile / 0.00062137119223733
restokm = resToMt / 1000
return restokm
print(distance_finder(70,5,5,5))
|
246b5786f688257d2d7d58046c4ffa794a1ad5df | B-Benja/Little_Programs | /SpotifyPlaylist_charts/main.py | 1,519 | 3.84375 | 4 | # creates a Charts 100 Playlist in Spotify based on the input date
import requests
from bs4 import BeautifulSoup
import spotipy
from spotipy.oauth2 import SpotifyOAuth
CHARTS = "https://www.billboard.com/charts/hot-100/"
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
scope="playlist-modify-private",
redirect_uri="http://example.com",
client_id="YOUR CLIENT ID",
client_secret="YOUR SECRET",
show_dialog = True,
cache_path = "token.txt"
))
user_id = sp.current_user()["id"]
# ask for a date
user_input = input("Which date do you want to travel to? Type it in the following format: YYYY-MM-DD: ")
# scrape the top 100 songs from that date from billboard.com
response = requests.get(CHARTS + user_input).text
soup = BeautifulSoup(response, "html.parser")
top100 = soup.find_all(name="span", class_="chart-element__information__song text--truncate color--primary")
top100 = [song.getText() for song in top100]
song_uris = []
year = user_input.split("-")[0]
for song in top100:
# use song name and year to get the song on spotify
title = sp.search(q=f"track:{song} year:{year}", type="track")
#print(title)
try:
uri = title["tracks"]["items"][0]["uri"]
song_uris.append(uri)
except IndexError:
print(f"{song} not on Spotify.")
#print(song_uris)
# create a playlist with the date
playlist = sp.user_playlist_create(user=user_id, name=f"{user_input} Top 100", public=False)
sp.playlist_add_items(playlist_id=playlist["id"], items=song_uris) |
cb2e6f687afafeefb435c806d80f4325cb5968f5 | KrolMateusz/Crypto | /Alghoritms/cesar_cipher_more_symbols.py | 1,101 | 4.09375 | 4 | def main():
text = 'This is my secret message.'
print(encryption(text, 13))
print(decryption(encryption(text, 13), 13))
def encryption(plaintext, key):
alphabet = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
cipher = ''
for symbol in plaintext:
if symbol in alphabet:
index = alphabet.find(symbol)
num = index + key
if num >= len(alphabet):
num -= len(alphabet)
cipher += alphabet[num]
else:
cipher += symbol
return cipher
def decryption(cipher, key):
alphabet = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
plaintext = ''
for symbol in cipher:
if symbol in alphabet:
index = alphabet.find(symbol)
num = index - key
if num < 0:
num += len(alphabet)
plaintext += alphabet[num]
else:
plaintext += symbol
return plaintext
if __name__ == '__main__':
main()
|
2ff7976defbe53686db9c9f471a6e7152e9c2e04 | umbs/practice | /IK/sorting/Quicksort.py | 2,334 | 4 | 4 | from random import randint
def swap(arr, i, j):
arr[i], arr[j] = arr[j], arr[i]
def get_pivot_index(start, end):
'''
start and end indices, are both inclusive
'''
return randint(start, end)
def partition(arr, start, end, p_idx):
'''
Use Lumoto's algorithm. When paritioning is done, swap element at 'end'
where pivot is present with 'le'
+----------+-+----------+-+--------------+-+
| <= | | > | | ?? | |
+----------+-+----------+-+--------------+-+
^ ^ ^
le cur end
le = all elements less than or equal to pivot. It points to the next
position an element must go if it is <= pivot
cur = currently examining element
start = Well, start of the array
end = end of the array. This is the pivot element
p_idx = Initially, pivot is here. Swap it to the end, to make it easy to
partition.
'''
swap(arr, end, p_idx)
le, cur, pivot = start, start, arr[end]
while cur < end:
if arr[cur] <= pivot:
swap(arr, le, cur)
le, cur = le+1, cur+1
else:
cur += 1
swap(arr, le, cur)
return le
def test_partition(arr, p_idx):
'''
Given pivot index, confirm that all values before it are less than or equal
and all values later are greater than pivot
'''
for i in range(p_idx+1):
if(arr[i] > arr[p_idx]):
return False
for i in range(p_idx+1, len(arr)):
if(arr[i] <= arr[p_idx]):
return False
return True
def Quicksort(arr, start, end):
if start >= end:
return
p_old = get_pivot_index(start, end)
p_final = partition(arr, start, end, p_old)
Quicksort(arr, start, p_final-1)
Quicksort(arr, p_final+1, end)
def test_quicksort(arr):
'''
Test for ascending array
'''
for i in range(1, len(arr)):
if arr[i-1] > arr[i]:
return False
return True
if __name__ == "__main__":
for i in range(100):
arr_sz = 100
arr = [randint(-15, 15) for _ in range(arr_sz)]
Quicksort(arr, 0, arr_sz-1)
if not test_quicksort(arr):
print("Quicksort Failed")
print(arr)
break
|
24d4ac4ec72f660b95013fde2e2298d7ce5e9fe5 | KMrsR/HMR_python | /PythonTutor/lesson_6_04.py | 736 | 3.921875 | 4 | '''
Условие
В первый день спортсмен пробежал x километров, а затем он
каждый день увеличивал пробег на 10% от предыдущего значения.
По данному числу y определите номер дня, на который пробег
спортсмена составит не менее y километров.
Программа получает на вход действительные числа x и y и
должна вывести одно натуральное число.
'''
#**************************************************
x = input()
y = input()
prob=int(x)
i=1
while prob<int(y):
prob*=1.1
i+=1
print(i) |
db25167b4151fb2b994859a4c6c885ccec49769b | stasvorosh/pythonintask | /BITs/2014/Abdrahmanova_G_I/task_7_1.py | 1,397 | 4.1875 | 4 | #Задача 7. Вариант 1.
#Разработайте систему начисления очков для задачи 6, в соответствии с которой игрок получал бы большее количество баллов за меньшее количество попыток.
import random
guessesTaken=0
print('Компьютер загадал имя одного из трех мушкетеров - товарищей д`Артаньяна. \nТвоя цель отгадать имя загаданного мушкетера.')
musketry=random.choice(["Атос", "Партос", "Арамис"])
while guessesTaken < 2:
print('Загаданное имя мушкетера: ')
guess=input()
guessesTaken=guessesTaken+1
if guess!=musketry:
print('Неверно!')
if guess==musketry:
break
if guess==musketry:
print('Верно! Число использованных попыток: ', guessesTaken)
if guessesTaken==1:
print('Количество заработанных баллов: ', 100)
if guessesTaken==2:
print('Количество заработанных баллов: ', 50)
if guess!=musketry:
print('Попытки кончились')
print('Вы не набрали баллов')
input('Нажмите Enter')
#Abdrahmanova G. I.
#28.03.2016 |
b85ae7232cfb36ed4c028abb2c79011942ab3080 | DaevernGanendrah/ACIP | /Day5/University.py | 1,745 | 3.796875 | 4 | class Person:
def __init__(self,name):
self.Name = name
class Student(Person):
def __init__(self,name,cgpa):
super(Student,self).__init__(name)
self.CGPA = cgpa
class Staff(Person):
def __init__(self,name,salary):
super(Staff,self).__init__(name)
if(salary<1100):
raise Exception("Salary ${} too low!".format(salary))
self.Salary = salary
class Lecturer(Staff):
def __init__(self,name,salary,allowance):
super(Lecturer,self).__init__(name,salary) #Constructor chaining
self.Allowance = allowance
class Clerk(Staff):
def __init__(self,name,salary,otRate):
super(Clerk,self).__init__(name,salary) #Constructor chaining
self.OTRate = otRate
self.OTHours = 0
class Manager(Staff):
def __init__(self,name,salary,carAllowance):
super(Manager,self).__init__(name,salary)
self.CarAllowance = carAllowance
def getMonthlySalary(self):
return (1.0-0.11)*self.Salary + self.CarAllowance
class HRManager(Manager):
def __init__(self,name,salary):
super(HRManager,self).__init__(name,salary,500)
class SalesManager(Manager):
def __init__(self,name,salary,carAllowance,petrolAllowance):
super(SalesManager,self).__init__(name,salary,carAllowance)
self.PetrolAllowance = petrolAllowance
self.MonthlySales = 0.0
m = Manager("Ali",5000,600)
print("Name:{}\tMonthly Salary:${}".format(m.Name,m.getMonthlySalary()))
hrm = HRManager("Ahmad",4000)
print("Name:{}\tMonthly Salary:${}".format(hrm.Name,hrm.getMonthlySalary()))
sm = SalesManager("Abu",5000,600,800)
sm.MonthlySales = 100000
print("Name:{}\tMonthly Salary:${}".format(sm.Name,sm.getMonthlySalary()))
|
dff539e7421fc9aee8a5cbadf9d25411dc3355ef | notesonartificialintelligence/07-01-20 | /chapter_5/toppings_updated.py | 410 | 3.59375 | 4 | #Gabriel Abraham
#notesonartificialintelligence
#Python Crash Course - Chapter 5
requested_topping = ["mushrooms","extra cheese","ground beef"]
if "mushrooms" in requested_topping:
print("Adding Mushrooms")
if "pepperoni" in requested_topping:
print("Adding Pepperoni")
if "extra cheese" in requested_topping:
print("Adding Extra Cheese.")
print("\n Finished making you pizza.")
#Using the not eual operator != |
9cee0e1a8c1b305c0ad63452f892a1986c92ab6e | jarvislam1999/CMSSW-12100-Homework | /pp/coding/santa.py | 2,796 | 3.546875 | 4 | '''
Practice problem for classes
'''
import random
PRESENT_PRODUCTION_TIME = 1.8
class Present(object):
''' Class for representing presents '''
def __init__(self, start_time):
self._production_end_time = start_time + PRESENT_PRODUCTION_TIME
def present_ready(self, current_time):
return current_time >= self._production_end_time
### YOUR ELF CLASS GOES HERE
class Santa(object):
''' Class for representing Santa '''
def __init__(self):
self._total_num_presents = 0
self._total_num_ready_presents = 0
self._elves = []
self._next_elf_index = 0
def get_total_num_presents(self):
return self._total_num_presents
def get_total_num_ready_presents(self):
return self._total_num_ready_presents
def gather_elves(self, num_elves):
self._elves = [Elf() for i in range(num_elves)]
def distribute_presents_to_make(self, num_presents_to_make, current_time):
elf_index = self._next_elf_index
for i in range(num_presents_to_make):
present = Present(current_time)
self._elves[elf_index].add_present(present)
elf_index = (elf_index + 1) % len(self._elves)
self._next_elf_index = elf_index
self._total_num_presents += num_presents_to_make
def collect_ready_presents_from_elves(self, current_time):
total = sum(elf.remove_presents(current_time) for elf in self._elves)
self._total_num_ready_presents += total
class Elf(object):
def __init__(self):
self.presents =[]
def add_present(self, present):
self.presents.append(present)
def remove_presents(self, current_time):
count = 0
new_l = []
for present in self.presents:
if (present.present_ready(current_time)):
count +=1
else:
new_l.append(present)
self.presents = new_l
return count
def simulate_Santa(num_elves, max_time, seed=None):
'''
Simulate Santa's workshop.
'''
if seed:
random.seed(seed)
# initilize
santa = Santa()
santa.gather_elves(num_elves)
for i in range(max_time):
#odd hours, assign work to elves
if i%2:
num_presents_to_make = random.randrange(100, 200)
santa.distribute_presents_to_make(num_presents_to_make, i)
#even hours, collect presents from elves
else:
santa.collect_ready_presents_from_elves(i)
print("Santa has {} presents ready, and {} presents in progress!".format
(santa.get_total_num_presents(),
santa.get_total_num_presents() - santa.get_total_num_ready_presents()))
if __name__ == "__main__":
simulate_Santa(100, 100)
simulate_Santa(200, 1000)
|
c6324a2477616cd751ab36a2a13cb5cf6ee6bc29 | coy0725/leetcode | /python/029_Divide_Two_Integers.py | 1,295 | 3.546875 | 4 | # class Solution(object):
# def divide(self, dividend, divisor):
# """
# :type dividend: int
# :type divisor: int
# :rtype: int
# """
import math
class Solution(object):
def divide(self, dividend, divisor):
if divisor == 0:
return MAX_INT
if dividend == 0:
return 0
isPositive = (dividend < 0) == (divisor < 0)
m = abs(dividend)
n = abs(divisor)
# ln and exp
res = math.log(m) - math.log(n)
res = int(math.exp(res))
if isPositive:
return min(res, 2147483647)
return max(0 - res, -2147483648)
# def divide(self, dividend, divisor):
# # (dividend >= 0) ^ (divisor < 0)
# isPositive = (dividend < 0) == (divisor < 0)
# dividend, divisor, result = abs(dividend), abs(divisor), 0
# while dividend >= divisor:
# n, nb = 1, divisor
# # fast minus
# while dividend >= nb:
# dividend, result = dividend - nb, result + n
# n, nb = n << 1, nb << 1
# if isPositive:
# return min(result, 2147483647)
# return max(-result, -2147483648)
if __name__ == '__main__':
s = Solution()
print s.divide(1, 1)
|
efadb2e1e080cdd45adebccc096cdf8f59e7b9e4 | abdullahalmamun0/Python_Full_Course | /05_flow_control.py | 1,272 | 3.984375 | 4 | # =============================================================================
# Flow Control
# =============================================================================
#If - statement
a = "Chocolate"
b = "Cadfdfke"
c = "Shinchan"
if a=="Chocolate":
print("Home work done")
if c == "Doraemon":
print("Eat food")
else:
print("Not eating")
elif b == "Cake":
print("Home work done")
else:
print("Home work not finished")
print("codinglaugh")
#while - loop
i = 1
while i<=5:
print("okk")
i += 1 # i = i+1 #1,2,3,4,5,6
#while - loop
while True:
print("okkey")
#while - nested loop
i = 1
j = 1
while i<=5:
while j<=5:
print("i=",i," j=",j,sep="")
j += 1
else:
print("j is end")
i += 1
j = 1
#for loop
a = "codinglaugh"
#tuple,list,set,dictionary,string
for i in a:
print(i)
#range for loop
for i in range(1,11,3): #start,end,step
print(i)
#nested loop
for i in range(1,6):
for j in range(1,6):
print("i=",i," j=",j,sep="")
else:
print("j is end")
# break
for i in range(1,6):
pass
i = 1
while i<=5:
if i == 3:
pass
print(i)
i += 1
a = 5
a = None
print(type(20>2))
|
0925c64567a9ca5a195c853ff32e677df0ddd44e | alphatamago/gopatterns | /examples/find_frequent_patterns.py | 3,648 | 3.640625 | 4 | """
Example program that uses PatternIndex to find most often occurring patterns
in a SGS collection.
"""
import fnmatch
import os
import sys
import numpy as np
import pandas as pd
from gopatterns.common import *
from gopatterns.indexer import PatternIndex, BLACK, WHITE
def main(argv):
description = "Identifying patterns in a collection of SGF files."
usage = ("%s <sgf dir> <pattern height>"
" <pattern width> <min_stones> <max_stones>"
" <max_num_moves>") % argv[0]
pathname = ""
pattern_dim1 = 0
pattern_dim2 = 0
min_stones_in_pattern = 0
max_stones_in_pattern = 0
max_moves = 0
only_corners = False
try:
pathname = argv[1]
pattern_dim1 = int(argv[2])
pattern_dim2 = int(argv[3])
min_stones_in_pattern = int(argv[4])
max_stones_in_pattern = int(argv[5])
max_moves = int(argv[6])
only_corners = (argv[7].lower()=='true')
except:
print(description)
print(usage)
sys.exit(1)
output_fname = None
if len(argv) == 9:
output_fname = argv[8] + ".txt"
if os.path.isfile(output_fname):
print("File already exisits, specify a new name:", output_fname)
sys.exit(1)
pd_output_fname = argv[8]
print("pathname:", pathname)
print("pattern size:", pattern_dim1, "x", pattern_dim2)
print("min_stones_in_pattern:", min_stones_in_pattern)
print("max_stones_in_pattern", max_stones_in_pattern)
print("max_moves per game:", max_moves)
print("only_corner:", only_corners)
index = PatternIndex(pat_dim=(pattern_dim1, pattern_dim2),
min_stones_in_pattern=min_stones_in_pattern,
max_stones_in_pattern=max_stones_in_pattern,
max_moves=max_moves,
only_corners=only_corners)
num_games = 0
matches = []
for root, dirnames, filenames in os.walk(pathname):
for filename in fnmatch.filter(filenames, '*.sgf'):
path = os.path.join(root, filename)
print("Processing", path)
index.find_patterns_in_game(path)
num_games += 1
sorted_patterns = index.get_frequent_patterns()
print ("Number patterns found:", len(index.index_), "number of games:",
num_games)
print ("Examples:")
num_show = 25
print("Most popular", num_show)
for v in sorted_patterns[:num_show]:
print ("Number matches:", len(v.matches))
pretty_print (v.pattern)
if index.num_patterns() > num_show:
print()
print("... skipping", index.num_patterns() - num_show, "patterns")
if output_fname is not None:
sys.stdout = open(output_fname, "w")
print ("#patterns :", len(index.index_), "#games :", num_games)
matches = []
patterns = []
num_matches = []
for v in sorted_patterns:
matches.append(','.join(v.matches))
num_matches.append(len(v.matches))
patterns.append(np_pattern_to_string(v.pattern))
print ("#matches :", len(v.matches))
pretty_print (v.pattern)
print()
df = pd.DataFrame(data={'pattern' : patterns,
# 'matched_sgf': matches}
'frequency' : num_matches})
df.to_csv(path_or_buf = "collection_%s_numgames_%s_numpatterns_%s.csv" %
(pd_output_fname, num_games, len(sorted_patterns)),
index = False)
if __name__ == '__main__':
main(sys.argv)
|
78936e2d334ab9714c226ce0ed413ec7b10ecac2 | psinguyen/Phansinguyen---C4T6 | /Shoppy.py | 1,137 | 3.875 | 4 | list = []
while True:
command = input("Welcome to our shop, what do you want (C, R, U, D)? ")
if command == "C":
new = input("Enter new item: ")
list.append(new)
for c in list:
print("*", c)
if command == "R":
for c in list:
print("*", c)
if command == "U":
update = int(input("Update position? "))
trade = input("Enter new item: ")
n = 1
listed = list
for c in list:
list.remove(c)
list.append(n)
n=n+1
for e in list:
if e==update:
list.remove(e)
list.append(trade)
for m in listed:
for n in list:
if n == trade:
list.remove(n)
list.append(trade)
else:
list.remove(n)
list.append(m)
for y in list:
print("*", y)
list=listed
if command == "D":
remove = input("Delete position? ")
list.remove(remove)
for c in color_list:
print("*", c)
|
130e0125f85a2f518aff72816650a43ca936af3a | Shashank-Bandi/Py-Practice | /list14.py | 126 | 3.90625 | 4 | l=eval(input("Enter list values to see if its empty :"))
if not l:
print("Empty")
else:
print("Contains Value:")
|
28cb69c1d50b79a810aef5b7eeb35cbc2ab824d6 | mucheniski/curso-em-video-python | /Mundo2/003EstruturasDeRepeticao/071SimuladorCaixaEletronico.py | 585 | 3.671875 | 4 | valor = int(input('Qual valor deseja sacar? '))
total = valor
cadulaAtual = 50
contCedulas = 0
while True:
if total >= cadulaAtual:
total -= cadulaAtual
contCedulas += 1
else:
if contCedulas > 0:
print(f'{contCedulas} cedulas de R${cadulaAtual}')
if cadulaAtual == 50:
cadulaAtual = 20
elif cadulaAtual == 20:
cadulaAtual = 10
elif cadulaAtual == 10:
cadulaAtual = 1
contCedulas = 0
if total == 0:
break
print('Finalizado')
|
aa657c5ab4c7cc7990f0344ed633c1e364c351f6 | SethHWeidman/algorithms_python | /01_interview_questions/01_ctci/02_Chapter_2/04_partition.py | 1,397 | 4.09375 | 4 | from data_structures import Node, UnorderedList
def partition_linked_list(u: UnorderedList, x: int) -> Node:
"""
Passes in an unordered list.
Returns the head of a list that has been "paritioned" around x
Input: 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1 (partition: 5)
Output: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8
"""
before_start = None
before_end = None
after_start = None
after_end = None
node = u.head
while node:
next_node = node.get_next()
node.set_next(None)
if node.get_data() < x:
if not before_start:
before_start = node
before_end = before_start
else:
before_end.set_next(node)
before_end = node
else:
if not after_start:
after_start = node
after_end = after_start
else:
after_end.set_next(node)
after_end = node
node = next_node
if not before_start:
return after_start
before_end.set_next(after_start)
return before_start
if __name__ == "__main__":
u = UnorderedList()
u.add(3)
u.add(5)
u.add(8)
u.add(5)
u.add(10)
u.add(2)
u.add(1)
print(u)
new_head = partition_linked_list(u, 5)
while new_head:
print(new_head)
new_head = new_head.get_next()
|
956acca70a2f7a8c85bddeb741f5168c41970772 | Hegemony/Python-Practice | /LeetCode practice/Top 100/206.Reverse List.py | 578 | 3.796875 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
p = head
res = []
while p != None:
res.append(p.val)
p = p.next
if len(res) == 0:
return None
res.reverse()
head1 = ListNode(res[0])
q = head1
for i in range(1, len(res)):
q.next = ListNode(res[i])
q = q.next
return head1 |
aee456fe260896bbc80d4db393f0a18f87c76bcd | MXS-PICHUY/EVIDENCIA_3-S3 | /PANDA DATAFRAME ACCESO A ELEMENTOS.py | 665 | 3.53125 | 4 | import pandas as pd
import random
SEPARADOR=('*'*20)+'\n'
diccionario_notas_aleatorias={\
'crescencio':[random.randrange(60,101) for x in range(3)],\
'domitila':[80,100,57], 'rutilio':[80,70,57], 'panfilo':[20,100,100],\
'ludoviko':[100,100,100]}
notas_diccionario=pd.DataFrame(diccionario_notas_aleatorias)
notas_diccionario.index=['programacion','base de datos','contabilidad']
print(notas_diccionario['domitila'])
print()
print(notas_diccionario.domitila)
print(SEPARADOR)
print(notas_diccionario.loc['programacion'])
print()
print(notas_diccionario.loc['bases de datos'])
print()
print(notas_diccionario.loc['contabilidad'])
|
954c1544de5a9a616469f2946784531c50b73037 | garderobin/Leetcode | /leetcode_python2/lc923_3sum_with_multiplicity.py | 2,440 | 3.828125 | 4 | # coding=utf-8
import itertools
from abc import ABCMeta, abstractmethod
from collections import Counter
class ThreeSumWithMultiplicity:
__metaclass__ = ABCMeta
@abstractmethod
def three_sum_multi(self, A, target):
"""
:type A: List[int]
:type target: int
:rtype: int
"""
class ThreeSumWithMultiplicityImplCountingSort(ThreeSumWithMultiplicity):
def three_sum_multi(self, A, target):
c = Counter(A)
res = 0
for i, j in itertools.combinations_with_replacement(c, 2):
# 不用担心c[i] == 1的情况,因为接下来乘出来会是0
k = target - i - j
if i == j == k:
res += c[i] * (c[i] - 1) * (c[i] - 2) / 6
elif i == j != k:
res += c[i] * (c[i] - 1) / 2 * c[k]
elif k > i and k > j:
res += c[i] * c[j] * c[k]
return res % (10 ** 9 + 7)
class ThreeSumWithMultiplicityImplCounter(ThreeSumWithMultiplicity):
"""
Time: O(n ^ 2)
Space: O(n)
"""
def three_sum_multi(self, A, target):
orig_res = 0
counter = Counter(A)
counts = sorted(counter.items()) # sort这一步不能少
m = len(counts)
for i, (key, count) in enumerate(counts):
if key + key + key > target:
break
# use of this element only once
for j in xrange(i + 1, m):
j_key, j_count = counts[j]
new_target = target - key - j_key
if new_target < j_key:
break
# use j_key for twice
if j_count > 1 and new_target == j_key:
orig_res += count * j_count * (j_count - 1) / 2
# use j_key for once
elif new_target > j_key and new_target in counter:
orig_res += count * j_count * counter[new_target]
# use this element twice
new_target = target - key
if count > 1 and new_target - key in counter:
if new_target - key > key:
left = count * (count - 1) / 2
orig_res += counter[new_target - key] * left
# use this element 3 times
if count > 2 and key * 3 == target:
orig_res += count * (count - 1) * (count - 2) / 6
return orig_res % 1000000007
|
48299ba972821abd2c821b86486ed0eefc42cab9 | siddacool/py-test-2017 | /python_gui_cookbook/ch1/res1_first-gui.py | 443 | 3.65625 | 4 | import tkinter as tk
from tkinter import ttk
win = tk.Tk()
win.title('Sid\'s GUI')
#win.resizable(0, 0)
# Label
aLabel = ttk.Label(win, text="Just Something")
aLabel.grid(column=0, row=0)
# Button Click()
def clickMe():
action.configure(text=" You Clicked! ")
aLabel.configure(text="Dude", foreground='red')
# Add a Button
action = ttk.Button(win, text="Do Not Press", command=clickMe)
action.grid(column=1, row=0)
win.mainloop() |
0cd9679ca4dbc5d425c4322b0fe0d26cd9950d37 | mingxoxo/Algorithm | /baekjoon/2110.py | 693 | 3.625 | 4 | # 공유기 설치
# 22.08.03
# https://www.acmicpc.net/problem/2110
# https://www.acmicpc.net/board/view/8301
import sys
input = sys.stdin.readline
def binary_search(C, cor):
start, end = 1, cor[-1] - cor[0]
result = 1
while start <= end:
mid = (start + end) // 2
tmp = cor[0]
cnt = 1
for i in range(1, len(cor)):
if cor[i] - tmp >= mid:
tmp = cor[i]
cnt += 1
if cnt < C:
end = mid - 1
else:
result = mid
start = mid + 1
return result
N, C = map(int, input().split())
cor = sorted([int(input()) for _ in range(N)])
print(binary_search(C, cor))
|
76676f195147b37a5c07cd8dff74f2e40d6f56a3 | henrypigg/GroceryListGenerator | /classes.py | 2,333 | 3.703125 | 4 |
class Meal:
def __init__(self, name, ingredients):
self.name = name
self.ingredients = ingredients
def __repr__(self):
nl = '\n '
return (f"{self.name}:{nl}"
f"{nl.join([ingredient['amount'] + ' ' + ingredient['units'] + ' ' + ingredient['name'] for ingredient in self.ingredients])}")
class UnitConverter:
dry_conversions = {
"cup": 1,
"oz": 8,
"tbs": 16,
"tsp": 48,
"gram": 225,
}
liquid_conversions = {
"pint": 0.5,
"cup": 1,
"oz": 8,
"tbs": 16,
"tsp": 48,
"ml": 237,
}
def convert_unit(self, convert_from, convert_to, amount, liquid=False):
if liquid is True:
if convert_from in self.liquid_conversions:
return float(self.liquid_conversions[convert_from]) / float(self.liquid_conversions[convert_to]) * float(amount)
else:
print(f"ERROR: {convert_from} not in liquid conversions")
return 0
else:
if convert_from in self.dry_conversions:
return float(self.dry_conversions[convert_from]) / float(self.dry_conversions[convert_to]) * float(amount)
else:
print(f"ERROR: {convert_from} not in dry conversions")
return 0
class GroceryList:
ingredients = {}
unit_converter = UnitConverter()
def __repr__(self):
display_list = "Groceries:\n"
nl = '\n'
for key, ingredient in self.ingredients.items():
display_list += f" {ingredient['amount']} {ingredient['units']} {key + nl}"
return display_list
def add_meal(self, meal, count):
for ingredient in meal.ingredients:
key = ingredient['name']
if key in self.ingredients:
converted_amount = self.unit_converter.convert_unit(
ingredient['units'],
self.ingredients[key]['units'],
ingredient['amount']
)
self.ingredients[key]['amount'] += converted_amount * count
else:
self.ingredients[key] = {
'amount': float(ingredient['amount']) * count,
'units': ingredient['units']
}
|
c36e06dab986704261cbab56266e027b24fdafda | A-Why-not-fork-repositories-Good-Luck/challenge-python-web-scrapper | /day_fin/exporter.py | 321 | 3.703125 | 4 | import csv
def save_to_file(jobs, job_name):
print(f"SAVE TO FILE: {job_name}.csv")
file_name = job_name+".csv"
file = open(f"{job_name}.csv", mode="w")
writer = csv.writer(file)
writer.writerow(["title", "company", "link"])
for job in jobs:
writer.writerow(list(job.values()))
return |
2d035bcd1cad683a5fe823c4f5ad333acfa521f0 | aksh45/pow-2 | /pow2.py | 103 | 4.09375 | 4 | n = int(input())
if n & n-1 !=0:
print("Num is not power of 2")
else:
print("Num is power of 2")
|
46a5981dc7ee31f5e2760fd19526e347b52d66d9 | cybelewang/leetcode-python | /code812LargestTriangleArea.py | 914 | 4.21875 | 4 | """
812 Largest Triangle Area
You have a list of points in the plane. Return the area of the largest triangle that can be formed by any 3 of the points.
Example:
Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
Output: 2
Explanation:
The five points are show in the figure below. The red triangle is the largest.
Notes:
3 <= points.length <= 50.
No points will be duplicated.
-50 <= points[i][j] <= 50.
Answers within 10^-6 of the true value will be accepted as correct.
"""
import itertools
class Solution:
def largestTriangleArea(self, points):
"""
:type points: List[List[int]]
:rtype: float
"""
def area(p, q, r):
return .5 * abs(p[0]*q[1]+q[0]*r[1]+r[0]*p[1]
-p[1]*q[0]-q[1]*r[0]-r[1]*p[0])
return max(area(*triangle)
for triangle in itertools.combinations(points, 3)) |
e15938f2292d0226a9b27fa00f04758fbb7c8391 | arunraman/Code-Katas | /Interview/Backtracking/generate_paranthesis.py | 589 | 3.5625 | 4 | class Solution():
def generateParenthesis(self, n):
result = []
self.generateparenthesisRecursive(result, "", n , n)
print result
def generateparenthesisRecursive(self, result, current, left, right):
if left == 0 and right == 0:
result.append(current)
return result
if left > 0:
self.generateparenthesisRecursive(result, current + "(", left - 1, right)
if left < right:
self.generateparenthesisRecursive(result, current + ")", left, right - 1)
S = Solution()
S.generateParenthesis(3) |
06e4d9047bab3245301a369b239c59d79975b567 | jadenpadua/Data-Structures-and-Algorithms | /bruteforce/mean.py | 127 | 3.578125 | 4 | #given a list of numbers, calculate the mean rounded to one decimal place
def mean(nums):
return round(sum(nums)/len(nums),1)
|
fe622c20adf94a15bfaee3417444b141fcc555d4 | jactive/demo | /python/lang/dip/ch05/special_class_methods.py | 1,179 | 3.59375 | 4 | class X:
def __setitem__(self, k, v):
print '%s.__setitem__ is invoked, k="%s", v="%s"' % (self, k, v)
def __getitem__(self, k):
print '%s.__getitem__ is invoked, k="%s"' % (self, k)
return "__getitem__ always return this string"
def __delitem__(self, k):
print '%s.__delitem__ is invoked, k="%s"' % (self, k)
# The return value is not visible in caller
return "__delitem__ always return this string"
def __len__(self):
print '%s.__len__ is invoked. int must be returned' % self
#! TypeError: __len__() should return an int
#! return '__len__ always return 13'
return 13
def __str__(self):
ret = object.__str__(self)
print '# __str__ is invoked. %s will be returned' % ret
return ret
def __repr__(self):
ret = object.__repr__(self)
print '# __repr__ is invoked. %s will be returned' % ret
return ret
def __cmp__(self, other):
print '%s.__cmp__ is invoked.' % self
return 1
if '__main__' == __name__:
x = X()
x['my key'] = 'my val'
print x['my key']
print len(x)
print x
x2 = X()
b = x == x2
print b
del x['my key1']
|
ee0b71b6e8fe4f6a569cda05f97b42da25d25819 | rafaeltorrez/Ejerciciospropuestos_02 | /18460697_Ejercicios_python02/condiciones/Ejercicio_04.py | 799 | 4.09375 | 4 | print("===========================================")
print(" Ejercicio 04 condiciones ")
print("===========================================")
multiplo=0
numero1=int(input("Ingresa el valor numero 1 "))
numero2=int(input("Ingresa el valor numero 2 "))
if numero1>numero2:
multiplo=numero1%numero2
if multiplo==0:
print(f"el numero {numero1} es multiplo de {numero2}")
else:
print(f"el numero {numero1} No es multiplo de {numero2}")
elif numero2>numero1:
multiplo=numero2%numero1
if multiplo==0:
print(f"el numero {numero2} es multiplo de {numero1}")
else:
print(f"el numero {numero2} No es multiplo de {numero1}")
elif numero1==numero2:
print(f"el numero {numero1} es igual a {numero2}")
|
96e8f074a49128c50ea88443cacb5ce1dc103f25 | wondervvall/python_hw | /hw2.py | 198 | 3.890625 | 4 | x=int(input('x='))
if(100>=x>=90):
print('A')
elif(x>=80):
print('B')
elif(x>=70):
print('C')
elif(0<x<70):
print('F') |
42eadc33b5a66ffe652301bfc62a7e5e5fe758fa | soham-pradhan/OS-Mini-Project-in-Python | /OS PROJECT.py | 9,426 | 3.640625 | 4 | from tkinter import *
import tkinter
import webbrowser
def gui():
top = tkinter.Tk()
top.geometry("550x550")
top.configure(background='pink')
def move():
if message.winfo_x() + message.move >= message.x_limit or message.winfo_x() + message.move < 0:
message.move = -message.move
message.place(x=message.winfo_x() + message.move)
message.after(message.delay, move)
message = Label(top, text = 'THE OS PROJECT')
message.config (fg = 'white',bg='red' ,font=('times','24'))
message.x_limit = 290
message.move = 2
message.delay = 25
message.place(x=1,y=20)
message.after(25, move)
def close_window():
top.destroy()
def gui2():
webbrowser.open('https://en.wikipedia.org/wiki/Page_replacement_algorithm')
label2=tkinter.Label(text="TOPIC -PAGE REPLACEMENT ALGORITHMS",font=("times new roman",12),fg='white',bg='red')
label2.place(x=20,y=80)
label2=tkinter.Label(text="CREDITS :",font=("times new roman",12),fg='white',bg='red')
label2.place(x=20,y=290)
label3=tkinter.Label(text="SOHAM PRADHAN -16102B0003",font=("Times New Roman",12),fg='white',bg='blue')
label3.place(x=20,y=340)
label3=tkinter.Label(text="ABHI KADAM -16102B0004",font=("Times New Roman",12),fg='white',bg='blue')
label3.place(x=20,y=360)
label3=tkinter.Label(text="MAYUR WANVE -16102B0009",font=("Times New Roman",12),fg='white',bg='blue')
label3.place(x=20,y=380)
label3=tkinter.Label(text="ATHARVA JOSHI -16104B0003",font=("Times New Roman",12),fg='white',bg='blue')
label3.place(x=20,y=400)
label4=tkinter.Label(text="ANUPAMA MHATRE -16104B0069",font=("Times New Roman",12),fg='white',bg='blue')
label4.place(x=20,y=420)
label5=tkinter.Label(text="WHAT ARE PAGE REPLACEMENT ALGORITHMS ?",font=("Times New Roman",12),fg='white',bg='green')
label5.place(x=20,y=120)
label6=tkinter.Label(text="I WANT TO SEE HOW THEY WORK",font=("Times New Roman",12),fg='white',bg='green')
label6.place(x=20,y=200)
button1=tkinter.Button(text="CLICK ME",command =gui2,fg='white',bg='green')
button1.place(x=20,y=160)
button1=tkinter.Button(text="CLICK ME",command =close_window,fg='white',bg='green')
button1.place(x=20,y=240)
top.mainloop()
def max1(l):
max2=l[0]
pos=0
for i in range(1,frame):
if max2<l[i]:
max2=l[i]
pos=i
return pos
def search(l,ele):
for i in range(len(l)):
if ele==l[i]:
return 1
return 0
def fifo(n,frame):
outmat=[]
for i in range(frame):
outmat.append([])
sign = "_"
for i in range(frame):
for j in range(n):
outmat[i].append(sign)
temp=[]
hit=0
m=0
for i in range(frame):
temp.append(0)
c=0
for i in range(n):
flag=0
if c==frame:
break
for j in range(len(temp)):
if l[i]==temp[j] and i!=j:
hit+=1
flag=1
break
if flag==0:
temp[c]=l[i]
c+=1
for q in range(len(temp)):
for w in range(n):
if q<=w:
outmat[q][w]=temp[q]
for z in range(i,n):
count=0
for k in range(frame):
if l[z]==temp[count]:
hit+=1
break
else:
count+=1
if count==frame:
u=m%frame
temp[u]=l[z]
m+=1
for itr in range(z,n):
outmat[u][itr]=temp[u]
print()
print("FIFO:")
print()
for dis in range(len(l)):
print(" ",l[dis],end=" ")
print()
for h in range(n):
print("---",end="-")
print()
for x in range(frame):
print("|",end=" ")
for y in range(n):
print(outmat[x][y],end=" | ")
print()
for y in range(n):
print("---",end="-")
print()
print("Hit = ",hit)
hratio=(hit/n)
print("Hit ratio = ",hratio)
return(hit)
def lru(n,frame):
outmat=[]
for i in range(frame):
outmat.append([])
sign = "_"
for i in range(frame):
for j in range(n):
outmat[i].append(sign)
temp=[]
hit=0
m=0
for i in range(frame):
temp.append(0)
c=0
for i in range(n):
flag=0
if c==frame:
break
for j in range(len(temp)):
if l[i]==temp[j]:
hit+=1
flag=1
break
if flag==0:
temp[c]=l[i]
c+=1
for q in range(len(temp)):
for w in range(n):
if q<=w:
outmat[q][w]=temp[q]
for q in range(i,n):
if search(temp,l[q]): #if hit
hit+=1
else:
ctemp=[]
for r in range(frame): #finding lru element
count=0
ctemp.append(0)
for w in range(q-1,-1,-1):
if l[w]!=temp[r]:
count+=1
else:
break
ctemp[r]=count
pos=max1(ctemp)
temp[pos]=l[q]
for itr in range(q,n):
outmat[pos][itr]=temp[pos]
print()
print("LRU:")
print()
for dis in range(len(l)):
print(" ",l[dis],end=" ")
print()
for h in range(n):
print("---",end="-")
print()
for x in range(frame):
print("|",end=" ")
for y in range(n):
print(outmat[x][y],end=" | ")
print()
for y in range(n):
print("---",end="-")
print()
print("Hit = ",hit)
hratio=(hit/n)
print("Hit ratio = ",hratio)
return(hit)
def optimal(n,frame):
outmat=[]
for i in range(frame):
outmat.append([])
sign = "_"
for i in range(frame):
for j in range(n):
outmat[i].append(sign)
temp=[]
hit=0
m=0
for i in range(frame):
temp.append(0)
c=0
for i in range(n):
flag=0
if c==frame:
break
for j in range(len(temp)):
if l[i]==temp[j]:
hit+=1
flag=1
break
if flag==0:
temp[c]=l[i]
c+=1
for q in range(len(temp)):
for w in range(n):
if q<=w:
outmat[q][w]=temp[q]
for q in range(i,n):
if search(temp,l[q]): #if hit
hit+=1
else:
ctemp=[]
for r in range(frame): #finding lru element
count=0
ctemp.append(0)
for w in range(q+1,n):
if l[w]!=temp[r]:
count+=1
else:
break
ctemp[r]=count
pos=max1(ctemp)
temp[pos]=l[q]
for itr in range(q,n):
outmat[pos][itr]=temp[pos]
print()
print("OPTIMAL:")
print()
for dis in range(len(l)):
print(" ",l[dis],end=" ")
print()
for h in range(n):
print("---",end="-")
print()
for x in range(frame):
print("|",end=" ")
for y in range(n):
print(outmat[x][y],end=" | ")
print()
for y in range(n):
print("---",end="-")
print()
print("Hit = ",hit)
hratio=(hit/n)
print("Hit ratio = ",hratio)
return(hit)
def analyze(n,frame):
hits=[]
hits.append(fifo(n,frame))
hits.append(lru(n,frame))
hits.append(optimal(n,frame))
max1=hits[0]
pos=0
for i in range(1,3):
if max1<hits[i]:
max1=hits[i]
pos=i
if max1==hits[0]==hits[1]:
print("Any method can be used to solve the problem")
elif max1==hits[0]:
if max1==hits[1]:
print("FIFO and LRU methods are suitable for these inputs")
elif max1==hits[2]:
print("FIFO and OPTIMAL methods are suitable for these inputs")
elif max1==hits[1]:
print("LRU and OPTIMAL methods are suitable for these inputs")
else:
if pos==0:
print("FIFO is the best suitable method for these inputs")
elif pos==1:
print("LRU is the best suitable method for these inputs")
elif pos==2:
print("OPTIMAL is the best suitable method for these inputs")
gui()
n=int(input("Enter total number of pages to insert:"))
frame=int(input("Enter total number of cache frames:"))
l=[]
for i in range(n):
print("Enter number",i+1,":")
x=int(input())
l.append(x)
while(True):
ch=int(input("Enter choice 1:FIFO 2:LRU 3:OPTIMAL 4:Analyze 5:Exit:"))
if ch==1:
fifo(n,frame)
elif ch==2:
lru(n,frame)
elif ch==3:
optimal(n,frame)
elif ch==4:
analyze(n,frame)
break
elif ch==5:
break
else:
print("Invalid choice")
'''Try these inputs:
number of elements = 10
frames = 4
numbers= 1 5 4 3 1 2 6 7 3 2
Same number of hits'''
|
49970737eb9ba2aad15a4ebd510dab8794d88317 | sun2everyone/python_study | /guess_number.py | 2,177 | 3.734375 | 4 | # объявление функции
import random
def is_valid_int(input):
if input.isdigit() and int(input)>0 and int(input)==float(input):
return True
else:
return False
def is_valid(input, limit):
if is_valid_int(input) and 1<=int(input)<=limit:
return True
else:
return False
def check_bool(input):
if input.lower()=='y':
return 1
elif input.lower()=='n':
return 0
else:
return -1
def gen_random(n=100):
return random.randint(1,n)
print('Добро пожаловать в числовую угадайку')
def get_value():
n = input('Выберите верхнюю границу диапазона чисел:')
while not is_valid_int(n):
print('А может быть все-таки введем целое положительное число?')
n = input('Выберите верхнюю границу диапазона чисел:')
n = int(n)
print('Отгадываем число от 1 до',n)
return n
limit = get_value()
rnd=rnd = random.randint(1,limit)
count=0
while True:
n = input('Введите целое число от 1 до '+str(limit)+' включительно:')
if not is_valid(n, limit):
print('А может быть все-таки введем целое число от 1 до ',limit,'?',sep='')
continue
else:
n=int(n)
count+=1
if n>rnd:
print('Ваше число больше загаданного, попробуйте еще разок')
elif n<rnd:
print('Ваше число меньше загаданного, попробуйте еще разок')
else:
print('Вы угадали, поздравляем! Сделано попыток:',count)
ans=-1
while ans<0:
ans=check_bool(input('Сыграть еще? y/n'))
if not ans:
break
else:
limit = get_value()
rnd = random.randint(1, limit)
count=0
print('Спасибо, что играли в числовую угадайку. Еще увидимся...')
|
f8c5cfc34baa994563c6e2eaa7e533523c71831a | vvalleru/leetcode-solutions | /ExcelSheetColumnTitle.py | 240 | 3.59375 | 4 | class Solution:
# @return a string
def convertToTitle(self, num):
result = ''
while num > 0:
num -= 1
result = chr(65 + num % 26) + result
num /= 26
return result |
fe27590b90809393984d35c5b3074e81b08cf9db | Kunal3Kumar/Assignment | /fibonacci.py | 355 | 4.09375 | 4 | #WAP in python to print fibonacci searis
Last_term = int(input("How many terms? "))
x = 0
y = 1
count = 0
if Last_term == 1:
print("Fibonacci searis upto",Last_term,":")
print(x)
else:
print("Fibonacci searis:")
while count < Last_term:
print(x)
z = x + y
x = y
y = z
count += 1
|
46206639a2a9e25184b8106244adc4c7ac712a15 | tiendong96/Python | /PythonPractice/WeightConverter.py | 374 | 3.75 | 4 |
def converter(weight, metric):
newWeight = 0
if(metric.lower() == 'l'):
newWeight = weight * .45
print(f'You are {newWeight} kgs')
else:
newWeight = weight / .45
print(f'You are {newWeight} lbs')
if __name__ == '__main__':
weight = float(input("Weight: "))
metric = input("(L)bs or (K)g: ")
converter(weight, metric) |
1c27e8641ae57e729746df2b9ed9ca1b7ba21e89 | pinardy/Digital-World | /Week 7/ps7_fact.py | 263 | 3.625 | 4 | def fact(n):
if n == 0:
return 1
elif n == 1:
return 1
else:
start = 1
for i in range(1,n+1):
start *= i
return start
#print fact(3)
#print fact(5)
#print fact(4)
#print fact(1)
|
5f7dcddfe68d2f7c45761d46f64d5d92aa11d77e | achalv/hap.py | /abbreviation.py | 435 | 3.5625 | 4 |
def isAbbr(abbr, str):
abbrLen = len(abbr)
hashtable = {}
for char in xrange(0,abbrLen,1):
try:
abbrCharPos = str.index(abbr[char])
hashtable[char] = abbrCharPos
except:
return False
if ((hashtable.values())==(sorted(hashtable.values()))):
return True
else:
return False
def tests():
print isAbbr("acl", "achal")
print isAbbr("m", "ken")
print isAbbr("bbe", "barbie")
if __name__ == '__main__':
tests() |
0b9803740e18b4b71f7149a7f1180f6820e96f9d | kavigayamini/UdemyCources_Python | /Python workshop/Day 3/ex4.py | 173 | 3.75 | 4 | # Python lists
colors = ['red','green','blue','yellow','orange','purple','brown']
print(colors)
print(type(colors))
numbers = [1,2,'three','four',5.0, 6.0]
print(numbers) |
33d79f1f61e65e1873868cd601db26af3a2190c1 | jpgsaraceni/python | /básico/listas/listas.py | 1,270 | 4.40625 | 4 | """
Lista é um tipo de dado (é um vetor).
Pode ter como elementos qualquer tipo de dados (pode misturar)
Cada elemento está associado a um índice, análogo às str
mesmas regras de fatiamento e range das str
"""
exemplo = ['índice 0', 'índice 1', 'etc.', 'a']
# pode acessar o índice e alterar para qualquer tipo de dado diretamente
# exemplo[1] = 4
# + entre duas listas (mesmo numéricas) é concatenar
# .extend(<lista>) concatena na lista. pode só um termo também.
# .append(<valor>) insere o valor ao final da lista
# .insert(<n>, <v>) insere v no índice n
# .pop() tira o último elemento
# del(<lista>[<range>]) apaga valores
# max(<lista>) e min(<lista>)
# list(range(n,m)) retorna uma lista de n a m-1.
i = 0
for x in exemplo:
print(exemplo[i])
i += 1
# .startswith(<caractere>)
# .lower()
# aceita lista dentro de lista (como matriz)
"""
lista = [1, 2, 3, 4]
a, b, c, d = lista # atribui cada elemento a cada var - desempacotamento
se colocar asterisco antes de uma var cria uma lista com os elementos que sobram.
a, *lista2, d = lista # lista2 recebe 2 e 3.
por convenção usar *_ para não usar os outros elementos da lista.
"""
lista = [1,2,3,4]
a, b, *n = lista # *n pega o resto da lista
print(a, b)
print(*lista) # desempacota
|
a695fafb011949f3d7d8ba845d8f187eb25ae719 | Oleksandr015/Codewars_answers | /codewarce_solutions/iq_test.py | 292 | 3.71875 | 4 | def iq_test(numbers):
l = numbers.split(' ')
even = [i for i in l if int(i)%2==0]
odd = [i for i in l if int(i)%2!=0]
if len(even) == 1:
return l.index(even[0])+1
else:
return l.index(odd[0])+1
if __name__ == '__main__':
print(iq_test("2 4 7 8 10"))
|
2d7cafc6c17aa6af6b97da42d306d770e8028ea7 | klknet/geeks4geeks | /datastructure/array/rearrange.py | 5,084 | 4.03125 | 4 | """
Double the first element and move zero to end.
"""
import functools
def double_and_move(arr):
"""
Double the first element equals to next element and move zeros to end.
:param arr:
:return:
"""
for i in range(len(arr) - 1):
if arr[i + 1] != 0 and arr[i] == arr[i + 1]:
arr[i] <<= 1
arr[i + 1] = 0
count = 0
for i in range(len(arr)):
if arr[i] != 0:
arr[count], arr[i] = arr[i], arr[count]
count += 1
return arr
def reorder_index(arr, idx):
"""
Reorder an array according to given indexes.
:param arr:
:param idx:
:return:
"""
i = 0
while i < len(arr):
if i != idx[i]:
i1 = i
i2 = idx[i]
arr[i1], arr[i2] = arr[i2], arr[i1]
idx[i1], idx[i2] = idx[i2], idx[i1]
else:
i += 1
return arr, idx
def rearrange_pos_neg(arr):
"""
Rearrange positive and negative numbers with constants extra space.
:param arr:
:return:
"""
for i in range(1, len(arr)):
if arr[i] >= 0:
continue
j = i
temp = arr[i]
while j > 0:
if arr[j - 1] > 0:
arr[j] = arr[j - 1]
j -= 1
else:
break
arr[j] = temp
return arr
def rearrange_pos_neg1(arr):
"""
Using merge sort in place sort.
:param arr:
:return:
"""
merge_sort(arr, 0, len(arr) - 1)
return arr
def merge_sort(arr, l, r):
if l < r:
m = int((l + r) / 2)
merge_sort(arr, l, m)
merge_sort(arr, m + 1, r)
merge(arr, l, r, m)
def merge(arr, l, r, m):
i, j = l, m + 1
while i <= m and arr[i] < 0:
i += 1
while j <= r and arr[j] < 0:
j += 1
reverse(arr, i, m)
reverse(arr, m + 1, j - 1)
reverse(arr, i, j - 1)
def reverse(arr, s, e):
while s < e:
arr[s], arr[e] = arr[e], arr[s]
s += 1
e -= 1
def arrange_biggest_num(arr):
"""
Arrange given numbers to form the biggest number.
:param arr:
:return:
"""
arr.sort(key=functools.cmp_to_key(my_cmp), reverse=True)
res = ''
for i in arr:
res += str(i)
return res
def my_cmp(x, y):
if x == y:
return 0
if int(str(x) + str(y)) > int(str(y) + str(x)):
return 1
return -1
def arrange_i_j(arr):
"""
Rearrange an array such thant arr[j] = i if arr[i] = j.
:param arr:
:return:
"""
for i in range(len(arr)):
arr[i] += 1
for i in range(len(arr)):
if arr[i] > 0:
swap_i_j(arr, i, arr[i])
for i in range(len(arr)):
arr[i] = -arr[i] - 1
return arr
def swap_i_j(arr, idx, val):
next_idx = val - 1
if arr[next_idx] > 0:
tmp = arr[next_idx]
arr[next_idx] = -idx - 1
swap_i_j(arr, next_idx, tmp)
def rearrange_wave(arr):
arr.sort(reverse=False)
for i in range(1, len(arr) - 1, 2):
arr[i], arr[i + 1] = arr[i + 1], arr[i]
return arr
def rearrange_wave1(arr):
for i in range(len(arr) - 1):
if i & 1 == 0:
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
else:
if arr[i] < arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
return arr
def replace_mul_prev_next(arr):
"""
Replace every arr element by multiplication of previous and next.
:param arr:
:return:
"""
if len(arr) <= 1:
return arr
prev = arr[0]
arr[0] = arr[0] * arr[1]
for i in range(1, len(arr) - 1):
cur = arr[i]
arr[i] = prev * arr[i + 1]
prev = cur
arr[-1] = arr[-1] * prev
return arr
def segregate_arr(arr):
"""
Segregate even and odd numbers.
:param arr:
:return:
"""
i = j = 0
while j < len(arr):
if arr[j] & 1 == 0:
arr[i], arr[j] = arr[j], arr[i]
i += 1
j += 1
return arr
print("Double the first element equals to next element and move zeros to end.\n",
double_and_move([0, 2, 2, 2, 0, 6, 6, 0, 0, 8]))
print("Reorder an array according to given indexes.\n", reorder_index([50, 40, 70, 60, 90], [3, 0, 4, 1, 2]))
print("arrange positive and negative numbers.\n", rearrange_pos_neg([-12, 11, -13, -5, 6, -7, 5, -3, -6]))
print("arrange positive and negative numbers.\n", rearrange_pos_neg1([-12, 11, -13, -5, 6, -7, 5, -3, -6]))
print("Form the biggest number.\n", arrange_biggest_num([54, 546, 548, 60]))
print("swap arr[i] = j if arr[j] = i.\n", arrange_i_j([1, 3, 0, 2]))
print("swap arr[i] = j if arr[j] = i.\n", arrange_i_j([2, 0, 1, 4, 5, 3]))
print("rearrange arr in wave order.\n", rearrange_wave([6, 4, 2, 1, 8, 3, 10]))
print("rearrange arr in wave order.\n", rearrange_wave1([6, 4, 2, 1, 8, 3]))
print("replace element by multiplication previous and next.\n", replace_mul_prev_next([2, 3, 4, 5, 6]))
print("segregate even and odd numbers.\n", segregate_arr([1, 9, 5, 3, 2, 6, 7, 11]))
|
f95354af3f2295ee80a3dcd0fe74f4ae38e74d38 | jpcorreia99/aws-ML | /comprehend/sentiment.py | 475 | 3.609375 | 4 | # uses amazon comprehend to evaluate the sentiment of a given input
import boto3
text = input("Insert a phrase whose sentiment will be evaluated: ")
client = boto3.client('comprehend')
req_resp = client.detect_sentiment(LanguageCode="en",
Text=text)
print("The detected sentiment was: " + req_resp['Sentiment'])
for sentiment, confidence_value in req_resp['SentimentScore'].items():
print(sentiment + ": " + str(confidence_value))
|
3927206ffe922374d1b4b8638ce841ecadf11f16 | quanewang/public | /reverse_stack.py | 262 | 4.0625 | 4 | def reverse(s):
if not s:
return s
x = s.pop()
reverse(s)
insert(s, x)
return s
def insert(s, x):
if not s:
s.append(x)
else:
y = s.pop()
insert(s, x)
s.append(y)
print reverse([1, 2, 3, 4])
|
b4ea8348ffde4fda27e1578c19269638bcd32024 | davcodee/hacktober | /hello.py | 583 | 3.984375 | 4 | def suma(x,y):
"""Esta funcion hace una suma"""
res=x+y
return res
def resta(x,y):
"""Esta funcion hace una resta"""
return x-y
def division(x,y):
"""Esta funcion hace una division"""
div = x/y
return div
def multiplicacion(x,y):
"""Esta funcion hace una multiplicacion"""
m = x*y
return m
def modulo(x,y):
"""Esta funcion hace una suma"""
def potencia(x,n):
return x ** n
def factorial(n):
if n == 1:
return n
else:
return n * factorial(n-1)
print(potencia(5,2))
if __name__ == "__main__":
print(division(10,5))
print(factorial(5))
|
3f739547b63e185ab21002abd68768ce7ef60dd0 | arkch99/CodeBucket | /CSE_Lab_Bucket/IT Workshop-Python/Day 10/prog15/prog15.py | 895 | 3.765625 | 4 | import module_fun as mf
while(1):
print("Press i to access function number i(eg:-1 for fun1)\nPress 6 to exit")
c=int(input())
if c==1:
print("Enter x and y:")
x,y=input().split()
x=int(x)
y=int(y)
print("Result=",mf.f1(x,y))
elif c==2:
print("Enter n and r:")
n,r=input().split()
n=int(n)
r=int(r)
print("Result=",mf.f2(n,r))
elif c==3:
n=int(input("Enter n:"))
print("Result=",mf.f3(n))
elif c==4:
print("Enter m and n")
m,n=input().split()
m=int(m)
n=int(n)
print("Result=",mf.f4(m,n))
elif c==5:
print("Enter m and x")
m,x=input().split()
m=int(m)
x=int(n)
print("Result=",mf.f5(m,x))
elif c==6:
print("Thanks")
break
else:
print("Wrong input")
|
97b70861783db6640a05ba8f54088aa5e3380166 | c-tham/PythonOOP | /03-Product/03-Product.py | 1,851 | 3.828125 | 4 | class Product(object):
def __init__(self, price, item_name, weight, brand):
self.price = price
self.item_name = item_name
self.weight = weight
self.brand = brand
self.status = "for sale"
self.display_info()
def sell(self):
print "Item sold"
self.tax(0.05)
self.status = 'sold'
self.display_info()
return(self)
def tax(self, tax):
self.tax = tax
print "Sale Tax: ", self.tax
print "Tax Amount: ", self.price * self.tax
if self.tax == 0:
print "Tax cannot be zero!"
return(self)
self.price = self.price + (self.price * self.tax)
return(self)
def returnitem(self, reason):
self.reason = reason
print "Item return: ", self.reason
if self.reason == 'defective':
self.status = 'defective'
self.price = 0
elif self.reason == 'box':
self.status = 'for sale'
elif self.reason == 'opened':
self.status = 'used'
self.price = self.price * 0.8
self.display_info()
return(self)
def display_info(self):
print "Item Name: ", self.item_name
print "Item Brand: ", self.brand
print "Item Price: ", self.price
print "Item Weight: ", self.weight
print "Item status: ", self.status
print "****************************"
return(self)
# phone1 = Product(500,"Iphone7","5oz","Apple")
# phone1.sell().display_info()
# phone1.returnitem("opened").display_info()
phone1 = Product(500,"Iphone7","5oz","Apple")
phone1.sell()
phone1.returnitem("opened")
phone2 = Product(600,"Iphone8","5oz","Apple")
phone2.sell()
phone2.returnitem("box")
phone3 = Product(700,"IphoneX","5oz","Apple")
phone3.sell()
phone3.returnitem("defective") |
e3c7130f3be8ecfe84c1acf0439afec427b37bea | numpee/ngsim | /moving_circles.py | 851 | 3.578125 | 4 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.animation as animation
fig = plt.figure()
ax = fig.add_subplot(111)
plt.xlim(-100, 100)
plt.ylim(-100, 100)
width = 5
bars = 25
RB = [] # Establish RB as a Python list
for a in range(bars):
RB.append(patches.Rectangle((a*15-140,-100), width, 200,
color="blue", alpha=0.50))
def init():
for a in range(bars):
ax.add_patch(RB[a])
return RB
def animate(i):
for a in range(bars):
temp = np.array(RB[i].get_xy())
temp[0] = temp[0] + 3;
RB[i].set_xy(temp)
return RB
anim = animation.FuncAnimation(fig, animate,
init_func=init,
frames=15,
interval=20,
blit=True)
plt.show()
|
28f3c284def08b41865d5e983f0b01ab69c35b81 | Rashi1997/Python_Exercises | /37.TextFile.py | 491 | 3.625 | 4 | """Write a program that given a text file will create a new text file in which all the lines from the original file are numbered from 1 to
n (where n is the number of lines in the file)."""
loc="C:/Users/rasdhar/Desktop/Python Training/37/text_file.txt"
f=open(loc)
lines=f.read().split("\n")
f.close()
f_output=open("C:/Users/rasdhar/Desktop/Python Training/37/list_text_file.txt",'w')
i=1
for line in lines:
f_output.write(str(i)+". "+line+"\n")
i+=1
f_output.close()
|
1a420c9e8ea34cd6f2d87396bd20a4cada16e77d | rlampe2/Advent_of_Code2016 | /Day06/one.py | 751 | 3.921875 | 4 | # Author: Ryan Lampe
# 5/18/2020
# Advent of Code 2016
# Day 6, Problem 1
from collections import Counter
# Have a list of lists for each index, and add all the characters in that column to it.
# Then for each list, print the most common character
index = {}
with open('input.txt', 'r') as file:
lines = file.read().splitlines() # Use instead of readlines to get rid of newlines
for i in range(0, len(lines[0])):
index[i] = [] # create a list at that index
for line in lines:
for i in range(0, len(line)):
index[i].append(line[i])
# Find most common char:
for i in range(0, len(lines[0])):
c = Counter(index[i]).most_common(1)
for key, val in c:
print(key) # There's only one entry in c, but want just the key
|
5396b9bbb4ef164871b78234797602a9225355c9 | K-Jaswanth/DSP-Lab-and-Assignments | /prime_number.py | 358 | 3.71875 | 4 | #Prime numbers upto a limit
print("Jaswanth sai - 121910313044")
lower = int(input("Enter the lower limit:"))
higher = int(input("Enter the higher limit:"))
#logic begins here
for a in range(lower,higher):
if a>1:
for i in range(2,a):
if(a%i==0):
break
else:
print(a)
|
92b909a5ea80d7b0f4a1298e9f225f3867beed24 | hankyeolk/PythonStudy | /sorting/sequential search.py | 592 | 3.796875 | 4 | #순차 탐색 (Sequential Search)
example_list = [17, 92, 18, 33, 58, 5, 33, 42]
def seqS(a, x):
for i in range(len(a)):
if a[i] == x:
return i
return -1 #else를 쓰면 끝까지 가지 않고 종료해버림
print(seqS(example_list, 900))
def seqS2(a, x):
k = []
for i in range(len(a)):
if a[i] == x:
k.append(i)
return k
print(seqS2(example_list, 900))
s_num = [39, 14, 67, 105]
s_name = ["justin", "john", "mike", "summer"]
def seqS3(a, b, x):
for i in range(len(a)):
if a[i] == x:
return b[i]
return "?"
print(seqS3(s_num, s_name, 67)) |
f8b55c65691273d6de3f61078a02030a24f94ce4 | kuanyingchou/tinyvim | /tinyvim.py | 1,323 | 3.703125 | 4 | class TextCpn:
def __init__(self):
self.content = [[]]
self.showLineNumber = True
self.cursor_x = 0
self.cursor_y = 0
def __str__(self):
prefix = ''
no = 1
res = ''
for line in self.content:
if self.showLineNumber:
res = res + str(no) + '. '
for char in line:
res = res + char
res = res + '\n'
no = no + 1
return res;
def insert(self, c):
current_line = self.content[self.cursor_y]
if c == '\n':
self.content[self.cursor_y] = current_line[:self.cursor_x]
self.content.insert(self.cursor_y + 1, current_line[self.cursor_x:])
self.move_down()
else:
current_line.insert(self.cursor_x, c)
self.move_right()
#def new_line(self):
# self.content.append([''])
def move_right(self):
current_line = self.content[self.cursor_y]
if self.cursor_x < len(current_line):
self.cursor_x = self.cursor_x + 1
def move_left(self):
if self.cursor_x > 0:
self.cursor_x = self.cursor_x - 1
def move_down(self):
self.cursor_y = self.cursor_y + 1
if __name__ == '__main__':
txt = TextCpn()
txt.insert('h')
txt.insert('e')
txt.insert('l')
txt.insert('l')
txt.insert('o')
txt.insert('\n')
txt.insert('b')
txt.insert('y')
txt.insert('e')
print(txt)
|
7f2f7f669a58e39a94623588dbab424a501ee873 | 54lihaoxin/leetcode_python | /src/MinimumPathSum/solution.py | 1,353 | 3.765625 | 4 | # Minimum Path Sum
#
# Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
#
# Note: You can only move either down or right at any point in time.
debug = True
debug = False
# from CommonClasses import * # hxl: comment out this line for submission
class Solution:
# @param grid, a list of lists of integers
# @return an integer
def minPathSum(self, grid):
minDict = {}
i = len(grid) - 1
while 0 <= i:
j = len(grid[0]) - 1
while 0 <= j:
if i == len(grid) - 1 and j == len(grid[0]) - 1:
minDict[(i, j)] = grid[i][j]
elif i == len(grid) - 1 and j < len(grid[0]) - 1:
minDict[(i, j)] = grid[i][j] + minDict[(i, j + 1)]
elif i < len(grid) - 1 and j == len(grid[0]) - 1:
minDict[(i, j)] = grid[i][j] + minDict[(i + 1, j)]
else:
minDict[(i, j)] = grid[i][j] + min(minDict[(i + 1, j)], minDict[(i, j + 1)])
if debug: print i, j, self.minDict[(i, j)], self.minDict
j -= 1
i -= 1
return minDict[(0, 0)]
|
a7fbea43f7a571864dc0de5e7453ba10684948e2 | sokazaki/leetcode_solutions | /problems/0716_max_stack.py | 1,026 | 3.734375 | 4 | # O(1) push/pop/top/peekMax, O(N) popMax Time Complexity / O(N) Space Complexity Solution with Two Stack
class MaxStack:
def __init__(self):
self.stack=[]
self.maxstack=[]
def push(self, x):
self.stack.append(x)
if not self.maxstack:
self.maxstack.append(x)
else:
self.maxstack.append(max(x, self.maxstack[-1]))
def pop(self):
self.maxstack.pop()
return self.stack.pop()
def top(self):
return self.stack[-1]
def peekMax(self):
return self.maxstack[-1]
def popMax(self):
n = self.maxstack.pop()
tmp = []
while n != self.stack[-1]:
tmp.append(self.pop())
self.stack.pop()
for i in range(len(tmp)-1, -1, -1):
self.push(tmp[i])
return n
# Your MaxStack object will be instantiated and called as such:
# obj = MaxStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.peekMax()
# param_5 = obj.popMax()
|
46430e85f76969326da72bda5d92277c641f5b34 | Phillip215/digitalcrafts | /week1/day4/loopingOverLists.py | 408 | 4.09375 | 4 | pets = ["dog", "cat", "ham"]
print(len(pets))
# Loop over a list
index = 0
while index < len(pets):
pet = pets[index]
print("What pet are ya? Well I'm a %s" % pet )
index += 1
# For in loops are better to use than a while loop
for pet in pets:
print(pet)
# How to combine lists
first = [1, 2, 3, 4]
first.extend([5, 6, 7])
print(first)
# TO delete a item in a list
del first[1]
print(first)
|
e44be145405d1b08bba120c5e2e2adf10383dc6b | gurudurairaj/gp | /holiday.py | 84 | 3.609375 | 4 | a=["Saturday","Sunday"]
g=input()
if g in a:
print("yes")
else:
print("no")
|
347c634bfad24cf322e4fdfecff755527bad3ca6 | AcubeK/LeDoMaiHanh-Fundamental-C4E23 | /Season 4/D4/intro.py | 506 | 3.59375 | 4 | # # person = ["Bucko", "Mind", "Home", 18, 6, 896, True, ]
# person = {}
# print(person)
# print(type(person))
person = { # Key & Key value
"Name": "Bucko",
"Location": "Mind",
"Age": 18
}
# print(person)
# person["Death_counts"] = 896 # C
# # print(person["Name"]) # R
# key = "Name" # U
# print(person[key])
# if key in person:
# print(person[key])
# else:
# print("Not found.")
|
4151ac521d2105a8430a602050ad798db2e3deb0 | dshapiro1dev/RuCoBo | /src/examples/builtin_types/Numbers.py | 1,517 | 4.5 | 4 | # numbers in python can take different forms
# integers: round numbers like 1, 12, -5
# floats: numbers with decimals like 3.553 , 1.0505, 3.1415, and 5.000000
integer1 = 37
integer2 = 12
divd = integer1 / integer2
print(type(integer1)) # integer
print(type(integer2)) # integer
print(type(divd)) # float
# notice: if we divide one integer by another - and dont get a clean integer, the result is a float
i1 = 6
i2 = 3
print(type(i1/i2)) # even if the result is an integer - python automatically says a division of 2 integers gets a float
# we can also convert from one type to another
# lets say we have a string - and we want an integer
mystr = "37"
theint = int(mystr) # int() converts the string into an integer
print(theint)
# now what happens if we try convert a float to an int
myflt = 3.1415926
myint = int(myflt)
print(myint) # 3 -> we drop the decimal and converted to an integer (close enough to PI)
# all the arithmetic operations are natural - but Python has some specific charaters
f1 = 2.17
f2 = 3.22
f3 = -333.33
print(f1+f2) # addition
print(f1-f2) # subtraction
print(f1==f2) # equivalence test (note: the double == tests if 2 things are equal, the single = assigns a value)
print(f1/f2) # division
print(f1*f2) # multiplication
print(f1 ** f2) # f1 to the power of f2
print(abs(f3)) # absolute value
# for the mathematically inclined - python even has complex numbers
c1 = complex(2,3) # 2 + 3i 2 = real part 3 = imaginary part
print(c1) # prints out: 2 + 3j |
20e6f290bc2fa83c3a6deaed30c4c51fb2315b2d | beginstudy/python_newstudy | /mountain_poll.py | 606 | 3.859375 | 4 | responses = {}
#设置一个标志,指出调查是否继续
投票活动 = True
while 投票活动:
#提示输入被调查者的名字和回答
name = input("\n请问你的名字是?")
response = input("你想住多少天?")
#将答卷存储在字典中
responses[name] = response
#看看是否还有人要参与调查
repeat = input("还有人要参与调查吗?(yes/no)")
if repeat == 'no':
投票活动 = False
#调查结束,显示结果
print("\n---调查结果---")
for name,response in responses.items():
print(name + "想住" + response + '天。') |
2e543c5e77465f3981b32667f1585f01d0bd1e69 | mohammadfebrir/learningPython | /sec2Lec6Ex5-function.py | 279 | 4.15625 | 4 | num1 = int(input("input number1: "))
num2 = int(input("input number2: "))
if num1>num2:
print("first is greater")
print("difference is " +str(num1 - num2))
elif num1<num2:
print("first is less")
print("difference is " +str(num1 - num2))
else:
print("numbers are equal")
|
e91d8b362e1764f5c795f6b37d10aed2b1337608 | KenjaminButton/runestone_thinkcspy | /12_dictionaries/exercises/12.7.3.exercise.py | 1,104 | 4.0625 | 4 | '''
Write a program called alice_words.py that creates a text file named
alice_words.txt containing an alphabetical listing of all the words,
and the number of times each occurs, in the text version of Alice’s
Adventures in Wonderland. (You can obtain a free plain text version
of the book, along with many others, from http://www.gutenberg.org.)
The first 10 lines of your output file should look something like this:
Word Count
a 631
a-piece 1
abide 1
able 1
about 94
above 3
absence 1
absurd 2
'''
import string
infile = open('alice.txt', 'r')
text = infile.readlines()
counts = {}
for line in text:
for word in line:
counts[word] = counts.get (word, 0) +1
'''
if word != " ":
if word != ".":
'''
word_keys = sorted(counts.keys())
infile.close()
outfile = open("alice_words.txt", 'w')
outfile.write("Word \t \t Count \n")
outfile.write("======================= \n")
for word in word_keys:
outfile.write("%-12s%d\n" % (word.lower(), counts[word]))
outfile.close()
|
9aec265c285174de8e26804bd55061d8e4be6ebb | msanchezzg/UVaOnlineJudge | /10000-10999/10945/motherBear_10945.py | 220 | 3.796875 | 4 | while True:
s = input()
if s == 'DONE':
break
s = [c.upper() for c in s if c.isalpha()]
s2 = s[::-1]
if s == s2:
print('You won\'t be eaten!')
else:
print('Uh oh..')
|
05b311c21c2f33b185c4d1696a5bdfcc000bc6f0 | natrine/guessnumber | /guess.py | 804 | 4.03125 | 4 | import random
correctNum = random.randint(1, 100)
def guessNum():
guess = input("Guess an integer from 1 to 100: ")
try:
guess = int(guess)
if guess < 1 or guess > 100:
print("Please guess between 1 and 100.\n")
guessNum()
elif guess > correctNum:
print("Too high! Guess again.\n")
guessNum()
elif guess < correctNum:
print("Too low! Guess again.\n")
guessNum()
else:
# guess = correctNum
print("Good job, you guessed correctly!\nThe number is " + str(correctNum) + ".\n")
except ValueError:
print("Please guess an integer. \n")
guessNum()
guessNum()
close = input("Press enter to exit this program. ")
|
c9b599aaa1c9c57022723bad51ad9b13a3e1ff09 | Amir324/itc_bootcamp_winter2020 | /Python/200310161111_Mimic.py | 3,358 | 4.1875 | 4 | #!/usr/bin/python -tt
## adapted to Python3 for ITC - 17/10/18
## - also added pep8 and naming convention compliance
##
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
"""Mimic pyquick exercise -- optional extra exercise.
Google's Python Class
Read in the file specified on the command line.
Do a simple split() on whitespace to obtain all the words in the file.
Rather than read the file line by line, it's easier to read
it into one giant string and split it once.
Build a "mimic" dict that maps each word that appears in the file
to a list of all the words that immediately follow that word in the file.
The list of words can be be in any order and should include
duplicates. So for example the key "and" might have the list
["then", "best", "then", "after", ...] listing
all the words which came after "and" in the text.
We'll say that the empty string is what comes before
the first word in the file.
With the mimic dict, it's fairly easy to emit random
text that mimics the original. Print a word, then look
up what words might come next and pick one at random as
the next work.
Use the empty string as the first word to prime things.
If we ever get stuck with a word that is not in the dict,
go back to the empty string to keep things moving.
Note: the standard python module 'random' includes a
random.choice(list) method which picks a random element
from a non-empty list.
For fun, feed your program to itself as input.
Could work on getting it to put in linebreaks around 70
columns, so the output looks better.
"""
import random
import sys
PATH = 'alice_mimic.txt'
NUMBER_OF_WORDS = 200
NUMBER_OF_ARGS = 2
FILE_NAME = 1
def mimic_dict(filename):
"""Returns mimic dict mapping each word to list of words which follow it."""
mimic_dict = {}
prev = ''
try:
with open(filename, 'r+') as file:
data = [line.strip().split() for line in file]
for line in data:
for word in line:
if not prev in mimic_dict:
mimic_dict[prev] = [word.strip()]
else:
mimic_dict[prev].append(word.strip())
prev = word
return mimic_dict
except:
sys.exit("can't read a file")
def print_mimic(mimic_dict, word):
"""Given mimic dict and start word, prints 200 random words."""
try:
for num in range(NUMBER_OF_WORDS):
print(word)
next_word = mimic_dict.get(word)
if not next_word:
next_word = mimic_dict['']
word = random.choice(next_word)
except:
sys.exit('something went wrong :(')
def test_mimic_dict():
"""
testing the mimic_dict() function
"""
assert type(mimic_dict(PATH)) == dict
print('testing function mimic_dict() passed!')
def main():
""" Provided main(), calls print_mimic and mimic() and get user's input: filename.txt """
test_mimic_dict()
if len(sys.argv) != NUMBER_OF_ARGS:
print('usage: ./mimic.py file-to-read')
sys.exit(FILE_NAME)
my_dict = mimic_dict(sys.argv[FILE_NAME])
print_mimic(my_dict, '')
if __name__ == "__main__":
main() |
f53fc4b9d84e5fc5b7fcc98df2d560bd4af0ea54 | RCNOverwatcher/Python-Challenges | /Sources/Challenges/070.py | 204 | 4.09375 | 4 | countries = ("England", "Scotland", "Ireland", "Wales", "United Kingdom")
print (countries)
ask = input("Enter the number you want to locate the country for")
ask = int(ask) - 1
print(countries[int(ask)]) |
639781db273d5e14d8c5da5b56491941b4c391d7 | OdilGaniyev/pythondarslari | /main.py | 523 | 3.609375 | 4 | # import random
# for i in range (10):
# print (random.random())
# kiritilganSon = int(input("son->"))
# tasodifiySon = random.randint(1,5)
# if kiritilganSon == tasodifiySon:
# print(tasodifiySon)
# print("Yutdingiz")
# else:
# print("tasodifiySon")
# print("Dam oling")
import random
while True:
tasodifiySon = random.randint(1,4)
kritilganSon = int(input("son->"))
if kritilganSon == tasodifiySon:
print("Yutdingiz")
break
else:
print("Omadingiz kelmadi")
|
60ffa7dc990107ce62e16086df9008e36b7b834a | isaacv15/sophiaClass | /main.py | 1,284 | 4.15625 | 4 | import random
guessesTaken = 0
print("Hello what is your name?")
myName = input()
number = random.randint(1,20)
print("Hello, " + myName + "! I am thinking of a number between 1 and 20, you have 5 guesses to guess the correct answer. If you can guess the number correctly I will tell you my name.")
while guessesTaken < 5:
print("Take your guess!")
guess = input()
if (guess.isdigit() == False):
print("Your input was invalid.")
validInput = False
while (validInput == False):
guess = input("Take your guess!")
if (guess.isdigit() == True):
validInput = True
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print("Your guess is low!")
if guess > number:
print("Your guess is high!")
if guess == number:
break
if guess == number:
if guessesTaken == 1:
print("Good job " + myName + "! You guessed my number in 1 guess! My name is Isaac Varghese, its been a pleasure playing with you!")
else:
print("Good job " + myName + "! You guessed my number in " +
str(guessesTaken) + " guesses! My name is Isaac Varghese, its been a pleasure playing with you!")
if guess != number:
number = str(number)
print("Nope, I'm sorry, the number I was thinking of was " +
number + ".")
|
7394ccb4619cb41d06fbea711dead41a66ab81a4 | Alexanderklau/Algorithm | /Greedy_alg/leetcode/minimum-deletion-cost-to-avoid-repeating-letters.py | 1,552 | 3.5 | 4 | # coding: utf-8
__author__ = 'Yemilice_lau'
"""
给你一个字符串 s 和一个整数数组 cost ,其中 cost[i] 是从 s 中删除字符 i 的代价。
返回使字符串任意相邻两个字母不相同的最小删除成本。
请注意,删除一个字符后,删除其他字符的成本不会改变。
示例 1:
输入:s = "abaac", cost = [1,2,3,4,5]
输出:3
解释:删除字母 "a" 的成本为 3,然后得到 "abac"(字符串中相邻两个字母不相同)。
示例 2:
输入:s = "abc", cost = [1,2,3]
输出:0
解释:无需删除任何字母,因为字符串中不存在相邻两个字母相同的情况。
示例 3:
输入:s = "aabaa", cost = [1,2,3,4,1]
输出:2
解释:删除第一个和最后一个字母,得到字符串 ("aba") 。
"""
cost = [3,5,10,7,5,3,5,5,4,8,1]
s = "aaabbbabbbb"
class Solution(object):
def minCost(self, s, cost):
n = 0
k = 0
new_s = list(s)
while n + 1 < len(cost):
print(n)
print(cost)
print(new_s)
print(new_s[n], new_s[n + 1])
if new_s[n] == new_s[n + 1]:
if cost[n] < cost[n + 1]:
k += cost[n]
new_s.pop(n)
cost.pop(n)
n -= 1
else:
k += cost[n + 1]
new_s.pop(n + 1)
cost.pop(n + 1)
n -= 1
n += 1
return k
z = Solution()
print(z.minCost(s, cost)) |
85273adc94aa5c424281c37225b358f2af428ef8 | ganhan999/ForLeetcode | /605、种花问题.py | 1,030 | 4.03125 | 4 | """
假设有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
给你一个整数数组flowerbed 表示花坛,由若干 0 和 1 组成,其中 0 表示没种植花,1 表示种植了花。另有一个数n ,能否在不打破种植规则的情况下种入n朵花?能则返回 true ,不能则返回 false。
示例 1:
输入:flowerbed = [1,0,0,0,1], n = 1
输出:true
示例 2:
输入:flowerbed = [1,0,0,0,1], n = 2
输出:false
"""
"""
连续三个0则可以种一盆花
"""
class Solution:
def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:
flowerbed = [0] + flowerbed#前后都补0
flowerbed = flowerbed + [0]#前后都补0
for i in range(1, len(flowerbed) - 1):
if flowerbed[i - 1] == 0 and flowerbed[i] == 0 and flowerbed[i + 1] == 0:
n = n - 1
flowerbed[i] = 1
return n <= 0
|
141a55ff8bd941d5f9c006393c7512a4c7603e06 | gaur1616/Huffman_Decoding | /Prefix_free_code.py | 3,473 | 3.78125 | 4 | import string
#Class definition of tree for generating a Prefix Free Code
class Tree:
def __init__(self, cargo, left=None, right=None):
self.cargo = cargo
self.left = left
self.right = right
self.freq = 0
self.code =''
def __str__(self):
return str(self.cargo)
def getLetter(self):
return self.letter
def setLetter(self,value):
self.letter=value
def getFreq(self):
return self.freq
def setFreq(self,value):
self.freq=value
def getCode(self):
return self.code
def setCode(self,value):
self.code=value
#Stack definition to sort and store the created trees/symbols
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
#Sort and Store in Stack:
def sortedInsert(S, element):
if (S.isEmpty() or element.freq < S.peek().freq):
S.push(element)
else:
temp = S.pop()
sortedInsert(S, element)
S.push(temp)
#To visualise the tree:
def print_tree_indented(tree, level=0):
if tree == None: return
print_tree_indented(tree.right, level+1)
print ' ' * level + str(tree.cargo) + ' ' + str(tree.code)
print_tree_indented(tree.left, level+1)
#Code Assignment for the generated prefix free tree:
def update_code(tree, appcode):
if tree == None: return
update_code(tree.right, appcode+'1')
tree.code=tree.code+ appcode
update_code(tree.left, appcode+'0')
#Codebook Creation for encoding:
def create_codebook(tree):
if tree == None: return
create_codebook(tree.right)
if len(tree.cargo)==1:
wf.write(tree.cargo+' , '+tree.code+'\n')
create_codebook(tree.left)
#File Handling: Open and Reading the text in the file:
rf=open('D:\Documents\UB Course\Subjects\ITC\Homework\Exercise 4\Input Text.txt','r')
para=rf.read()
rf.close()
#Length of the Paragraph read:
length_para=float(len(para))
#Creating a dictionary:
dictionary= string.ascii_lowercase + string.ascii_uppercase + string.punctuation + ' ' + string.digits
#Relative Frequency of each symbol:
codebook=[];
for i in range(len(dictionary)):
letter_count=string.count(para,dictionary[i])
codebook.append([dictionary[i],letter_count])
sym_tocode=Stack()
#Stack of all alphabets and punctuations with non zero frequency in a sorted manner
for element in codebook:
if element[1]!=0:
newNode=Tree(element[0]);
newNode.freq=element[1]
sortedInsert(sym_tocode, newNode)
#Prefix free code tree generation
while sym_tocode.size()>1:
t1=sym_tocode.pop()
t2=sym_tocode.pop()
mytree=Tree('(N)', t2, t1)
mytree.freq=t1.freq+t2.freq
sortedInsert(sym_tocode, mytree)
print_tree_indented(sym_tocode.peek())
#Code generation for the generated tree
update_code(sym_tocode.peek(), '')
#Generating Prefix Free Code Documentation for the provided text:
wf=open('D:\Documents\UB Course\Subjects\ITC\Homework\Exercise 4\Prefix Free Code.txt','w')
create_codebook(sym_tocode.peek())
wf.close()
|
38788ef6ac45bf5c876be539f996ee3ed64623dd | SimonBrown94/Battleships | /Player.py | 5,203 | 4 | 4 | import Board
import Ship
import random
class Player:
def __init__(self, board_size, bot, diff, ships):
self.ships = []
self.board_size = board_size
self.my_board = Board.Board(board_size)
self.opp_board = Board.Board(board_size)
self.remaining_attacks = []
self.attack_stack = []
self.opp_ships = []
self.turns = 0
for i in ships:
self.opp_ships.append(i)
if bot == 'P':
self.bot = False
elif bot == 'C':
self.bot = True
for i in range(board_size):
for j in range(board_size):
self.remaining_attacks.append([i, j])
self.diff = diff
def add_ship(self, ship_number, length):
# Add a ship to the player
if not self.bot:
# This section is for human players
# Print the current board and state ships length
self.my_board.print_board()
print("Ship: " + str(ship_number) + ", Length: " + str(length))
valid_position = False
# Ask for position and check if it is valid
while not valid_position:
x = input("Ship " + str(ship_number) + " x coordinate = ")
y = input("Ship " + str(ship_number) + " y coordinate = ")
d = input("Ship " + str(ship_number) + " direction = ").lower()
if d == 'h':
if not x.isnumeric() or int(x) + length > self.board_size:
print("Invalid ship position, please choose again (ship goes off the board)")
continue
for i in range(length):
if self.my_board.board[int(y), int(x) + i] == 'S':
print("Invalid ship position, please choose again (ship overlaps another ship")
valid_position = False
break
else:
x = int(x)
y = int(y)
valid_position = True
elif d == 'v':
if not y.isnumeric() or int(y) + length > self.board_size:
print("Invalid ship position, please choose again (ship goes off the board)")
continue
for i in range(length):
if self.my_board.board[int(y) + i, int(x)] == 'S':
print("Invalid ship position, please choose again (ship overlaps another ship)")
valid_position = False
break
else:
x = int(x)
y = int(y)
valid_position = True
else:
print("Invalid direction, please choose again (must be 'h' or 'v')")
else:
# This section is for if the computer has to generate ship positions
d = random.choice(['h', 'v'])
valid_position = False
while not valid_position:
if d == 'h':
x = random.randrange(self.board_size - length)
y = random.randrange(self.board_size)
else:
x = random.randrange(self.board_size)
y = random.randrange(self.board_size - length)
if d == 'h':
for i in range(length):
if self.my_board.board[y, x + i] == 'S':
valid_position = False
break
else:
valid_position = True
elif d == 'v':
for i in range(length):
if self.my_board.board[y + i, x] == 'S':
valid_position = False
break
else:
valid_position = True
# Once the valid coordinates are chosen, add a new ship and update the boards
self.ships.append(Ship.Ship(x, y, length, d))
for coord in self.ships[ship_number].coords:
self.my_board.coord_update(coord[0], coord[1], 'S')
def opp_attack(self, x, y):
# Check the input coordinates against the coordinates of each ship, if hit then update ship
for ship in self.ships:
for i in range(len(ship.coords)):
if [x, y] == ship.coords[i]:
action = ship.update_ship(i)
if action == "Hit":
return action, []
elif action == "Sank!":
return action, ship.coords
return "Miss", []
def still_alive(self):
# If a player has at least one ship which is not dead then the are still alive
for ship in self.ships:
if not ship.dead:
return True
return False
|
7df7b9d0d411db6008f1b7468cd11e43fce42630 | sidmaskey13/python_assignments | /DT45.py | 107 | 3.78125 | 4 | given_tuple = (1,2,3,4,5,6)
to_index = 4
print(f"{to_index} is in index {given_tuple.index(to_index)}")
|
60b3e7c45b40ff621c654d6adcf77b8ee14b866c | Peixinho20/Fundamentos-da-Computacao | /python2/frase-sem-caracter.py | 272 | 4.15625 | 4 | #Faça um programa que leia uma string e um caractere e crie uma outra string sem o caractere lido.
frase = raw_input("Digite uma frase: ")
caracter = raw_input("Escolha um caractere: ")
palavras = frase.split(caracter)
junto = ''.join(palavras)
#print frase
print junto
|
3bd5e5ce5e68028327ec01be32dd16030c5ef1d9 | roeisavion/roeisproject2 | /תרגילים המהצגת/4.2.py | 174 | 4.03125 | 4 | a=int(input("enter a number1"))
for i in range (2,a) :
if i!=a and a%i==0 :
print("the number is non-prime")
break
else:
print("the number is prime")
|
86f7c0e8a25f873638c2a99eff659a73c87092ac | Mansoorshareef1996/Grocery-stimulation-using-python | /grocery stimulation.py | 10,759 | 4.4375 | 4 | #!/usr/bin/python3
from random import seed, randrange
from header6 import *
N = 10 # Setting the vale of N as 10
def rnd(low, high):
'''
It Generates random numbers
:param : low,high
:return: The random number in the range low,high
'''
return randrange(low, high + 1) # returns the random number in the range low and high
def arrival(clock, picking):
'''
It is used to calculate the arrival time of the customer
:param:clock,picking
:return: The next arrival time and the next pick of the customer
'''
next_arr_time = clock + rnd(MIN_INT_ARR, MAX_INT_ARR) # The next arrival time is calculated by adding the clock with the rnd of minimum interarrival time and max interarrival
if N > 0: # Customer has arrived, calculate the time it takes to pick
print("Arriving to Store: " + str(clock)) # Printing the arriving to store time
customer = {
"atime": clock, # Arrival time
"ptime": clock + rnd(MIN_PICK, MAX_PICK), # Finish pick time
"wtime": 0, # waiting time in checkout line
"dtime": 0 # departing time from store of a customer
} # Dictionary of the customer to capture the data values of customer as a single unit
picking.append(customer) # Append the customer to the picking
# Find the minimum pick time from the list of pickers
next_pick = None # The next pick is intially None
for customer in picking: # for loop for the customers in picking
if next_pick is None or customer["ptime"] < next_pick: # If the value of next pick is none or the customer[ptime] is greater than next pick
next_pick = customer["ptime"] # If the if statemnt is satisfied then next pick is equals to customer[ptime]
return next_arr_time, next_pick # Return the value of next arrival time and next pick time
def shopping(clock, picking, checkout):
'''
Move customers who have finished picking and add it to the check out
Next customer is the customer that has the lowest value
:param:clock,picking,checkout: It is the checkout time and picking time of customer
:return:the next pick and the checkout time
'''
finished_picking_customer = None # The value of finished picking customer is None
for customer in picking: #for loop for customers in picking
if customer["ptime"] == clock: #If the cutomer ptime is equal to the clock
if N > 0: # If the value of N is greater than 0
print("Picking Grocery Done: " + str(clock)) # Print the picking is done and the time
finished_picking_customer = customer # Updating the customers who have finished picking
break
picking.remove(finished_picking_customer) # Remove the customers from picking who are done with their picking
# If the checkout is busy with someone else then the person will have to
# go to the line. The person's departure time is dependent on the last person
# in check out
if len(checkout) == 0: # If the length of the checkout is zero than
finished_picking_customer["dtime"] = clock + rnd(MIN_SERV, MAX_SERV) #The departing time of the customers who have finished picking is calculated with the given formula above
checkout.append(finished_picking_customer) # Update the checkout list with the customers who have finished picking items
# Find the minimum pick time from the list of pickers
next_pick = None # The value of next pick is None
for customer in picking: # For loop for customer in picking
if next_pick is None or customer["ptime"] < next_pick: # If the next pick is none or the customer picking time completion is greater than next pick
next_pick = customer["ptime"] # The value of next pick is the customer time of completion of picking up the grocery items
return next_pick, checkout[0]["dtime"] # It returns the next pick value and the checkout time of departing time
def update_stat(cust, total):
'''
Update the stats
:param:customer,total
'''
total["num"] += 1 # Total is calculated as the total[num]+1
total["pick"] += cust["ptime"] - cust["atime"] # The total pick time is calculated as the customer picking completion time minus the customer arrival time
serv_time = cust["dtime"] - cust["ptime"] # The service time is calculated as the customer departure time minus the customer picking completion time
if cust["wtime"] > 0: # If the customer waiting time is greater than zero
wait_time = cust["wtime"] - cust["ptime"] # waiting time is the customer wait time ninus the customer picking time completion
total["wait"] += wait_time # total wait time is calculated as the taotal wait time plus the wait time
serv_time = cust["dtime"] - cust["wtime"] # The serving time is the customer departing time minus the customer wait time
total["serv"] += serv_time # Total serving time is the total serv time plus the serving time
total["shop"] += cust["dtime"] - cust["atime"] #Total shoping time is the customer departing time minus the customer arrival time
def print_stat(total):
'''
printing the stats
:param:total
'''
num_shopped = "{:,}".format(total["num"])# The total number of shopped customer is calculated
avg_pick = "{:,.3f}".format(total["pick"] / total["num"]) # The average pick tme is calculated
avg_shop = "{:,.3f}".format(total["shop"] / total["num"]) # The average shop time is calculated
avg_wait = "{:,.3f}".format(total["wait"] / total["num"]) # The average wait time is clculated
avg_serv = "{:,.3f}".format(total["serv"] / total["num"]) # The average serving time is calculated
spacing = len(num_shopped) # The spacing is calculated as the length of the number of customers shopped
if len(avg_pick) > spacing: # If the lengh of average pick is greater than than the spacing
spacing = len(avg_pick) # The value of spacing is set as the length of the average pick
if len(avg_shop) > spacing: # If the length of average shoppe is greater than spacing
spacing = len(avg_shop) # spacing is the value of length of average shoppe
if len(avg_wait) > spacing: # If the length of average is greater than spacing
spacing = len(avg_wait) # The value of spacing is length of average wait time
print("Num of customers shopped = " + num_shopped.rjust(spacing)) # Printing the customer shoppe
print("Avg grocery pick time = " + avg_pick.rjust(spacing)) # Printing the Average grocery pick time
print("Avg wait time in checkout = " + avg_wait.rjust(spacing)) # Printing the average wait time in checkout
print("Avg serv time in checkout = " + avg_serv.rjust(spacing)) # Printing the average serve time in checkout
print("Avg time in store = " + avg_shop.rjust(spacing)) # Printing the Average time in store
def departure(clock, checkout, total):
'''
The departure of the customer is calculated
:param: clock,checkout,total
'''
global N
# Depart the next customer
cust = checkout.pop(0)
if N > 0: # If the value of N is greater than 0
print("Departing from Store: " + str(clock)) # Print the Departing from store time
print('\n') # Including the spaces
N -= 1 # The value of N is calculated as N minus 1
update_stat(cust, total) # The stats is updated with the customer and total value
if len(checkout) > 0: # If the length of checkout is greater than
checkout[0]["wtime"] = clock # The checkout of cust at zero wait time is the value of clock
checkout[0]["dtime"] = clock + rnd(MIN_SERV, MAX_SERV) # The checkout of customer o depart time is calculated using the above formula
return checkout[0]["dtime"] # The Checkout of customer o depart time is returned if the length of checkout is greater than zero
return None # Return the None value
def update_clock(next_arr, next_pick, next_dept):
'''
The clock time is updated
:param:next_arr,next_pick,next_dept: The value of clock is updated based on the parameters
:return:the next clock value
'''
# Find the smallest clock time
next_clock = next_arr
if next_pick is not None and next_pick < next_clock: # If the next pick is not none and next pic is greater than next clock
next_clock = next_pick # The next clock is set as the value of next pick
if next_dept is not None and next_dept < next_clock: # If the next dept is not None and the next dept is greater than next clcck
next_clock = next_dept # The next clock value is the value of next departure value
return next_clock # Return the value of next clock
def main():
'''
Entry point in the program
'''
seed(SEED) # Before generating the random number we call the SEED function
clock = 0 # Intialize the clock
# Initialize events
next_arr = 0 # arrival time of the next customer
next_pick = None # time of a customer who is next to finish picking up the grocery items
next_serv = None # the time of a customer who is next to be served in the checkout line
next_dept = None # the departing time of a next customer from the store.
# Initialize the statistical values
total = {
"num": 0, # total number of customers departed from the store
"pick": 0, # accumulated grocery picking times
"wait": 0, # accumulated waiting times
"serv": 0, # accumulated service times
"shop": 0 # accumulated time spent in the store over all customers
}
picking = [] # List of Picking
checkout = [] # List of Checkout
while clock < SIMTIME: # if the value of clock is greater than SIMTIME
if clock == next_arr: # If the value of clock is equals to the next arrival time
next_arr, next_pick = arrival(clock, picking) # The next arrival and next pick time is set using the clock and picking values
elif clock == next_pick: # If the value of clock is equals to the next pick value
next_pick, next_dept = shopping(clock, picking, checkout) # It is calculated as the shopping using clock.picking and the picking
elif clock == next_dept: #If the clock value is equals to the next departure then
next_dept = departure(clock, checkout, total) # Departure is calculated as the clock,checkout and the total
clock = update_clock(next_arr, next_pick, next_dept) # The valueof clock is updated using the next arrival time,next pick and next departure time
print() # Calling the print fucntion
print_stat(total) # Printing the stats using the the total
main() # Calling the main function
|
09bc97e129edab7475876e7e0bad3fbe033c5dd3 | GonzaloMonteodorisio/ejercicios-python-unsam | /Clase06/grafico_experimentos_promedios.py | 921 | 3.609375 | 4 | import matplotlib.pyplot as plt
import numpy as np
# from busqueda_secuencial import busqueda_secuencial_
from experimento_secuencial import generar_lista
from experimento_secuencial_promedio import experimento_secuencial_promedio
m = 10000
k = 1000
largos = np.arange(256) + 1 # estos son los largos de listas que voy a usar
print(largos)
comps_promedio = np.zeros(256) # aca guardo el promedio de comparaciones sobre una lista de largo i, para i entre 1 y 256.
for i, n in enumerate(largos):
lista = generar_lista(n, m) # genero lista de largo n
comps_promedio[i] = experimento_secuencial_promedio(lista, m, k)
print(comps_promedio)
# ahora grafico largos de listas contra operaciones promedio de búsqueda.
plt.plot(largos,comps_promedio,label = 'Búsqueda Secuencial')
plt.xlabel("Largo de la lista")
plt.ylabel("Cantidad de comparaciones")
plt.title("Complejidad de la Búsqueda")
plt.legend()
plt.show() |
5fa01229080654cea2ed627a01140b07154b183b | eduardosalomon/my-first-repo | /excercise.py | 1,111 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 13 13:23:33 2020
@author: edu
"""
#n = input("Input number: "
def is_even(n) :
while n:
if n % 2 == 0 :
return True
else:
return False
#%%
def is_odd(n) :
while n:
if n % 2 == 1 :
return True
else:
return False
#%% Factorial
def factorial(n):
if n < 2:
return 1
return n * factorial(n-1)
n= int(input("Input interger: "))
print(factorial(n))
#%% Multiples
def multiples(numbers, n):
multi = []
for i in numbers:
if i % n ==0:
multi.append(i)
return multi
numbers= [1,2,3,4,5,6,7,8,9,10,
11,12,13,14,15,16,17,18,19,20,
21,22,23,24,25,26,27,28,29,30,
31,32,33,34,35,36,37,38,39,40,
41,42,43,44,45,46,47,48,49,50,
51,52,53,54,55,56,57,58,59,60,
61,62,63,64,65,66,67,68,69,70,
71,72,73,74,75,76,77,78,79,80,
81,82,83,84,85,86,87,88,89,90,
91,92,93,94,95,96,97,98,99,100]
|
7daeffdf98d493d10785473f485f2a0158123cbb | jpitman1010/Whiteboard | /HR-delete-a-node-from-a-linked-list.py | 3,157 | 4.21875 | 4 | # This challenge is part of a tutorial track by MyCodeSchool and is accompanied by a video lesson.
# Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value.
# Example
# After removing the node at position , .
# Function Description
# Complete the deleteNode function in the editor below.
# deleteNode has the following parameters:
# - SinglyLinkedListNode pointer llist: a reference to the head node in the list
# - int position: the position of the node to remove
# Returns
# - SinglyLinkedListNode pointer: a reference to the head of the modified list
# Input Format
# The first line of input contains an integer , the number of elements in the linked list.
# Each of the next lines contains an integer, the node data values in order.
# The last line contains an integer, , the position of the node to delete.
# Constraints
# , where is the element of the linked list.
# Sample Input
# 8
# 20
# 6
# 2
# 19
# 7
# 4
# 15
# 9
# 3
# Sample Output
# 20 6 2 7 4 15 9
# Explanation
# The original list is . After deleting the node at position , the list is .
#!/bin/python3
import math
import os
import random
import re
import sys
class SinglyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_node(self, node_data):
node = SinglyLinkedListNode(node_data)
if not self.head:
self.head = node
else:
self.tail.next = node
self.tail = node
def print_singly_linked_list(node, sep, fptr):
while node:
fptr.write(str(node.data))
node = node.next
if node:
fptr.write(sep)
# Complete the deleteNode function below.
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
def deleteNode(head, position):
if position == 0:
return head.next
count = 1
prev = head
current = head.next
while count < position:
prev = current
current = current.next
count += 1
prev.next = current.next
prev=current
current = current.next
return head
# Test Case 0:
# Compiler Message
# Success
# Input (stdin)
# Download
# 8
# 20
# 6
# 2
# 19
# 7
# 4
# 15
# 9
# 3
# Expected Output
# Download
# 20 6 2 7 4 15 9
# Test Case 1:
# Compiler Message
# Success
# Input (stdin)
# Download
# 4
# 11
# 9
# 2
# 9
# 1
# Expected Output
# Download
# 11 2 9
# Test Case 3-8 locked:
# if __name__ == '__main__':
# fptr = open(os.environ['OUTPUT_PATH'], 'w')
# llist_count = int(input())
# llist = SinglyLinkedList()
# for _ in range(llist_count):
# llist_item = int(input())
# llist.insert_node(llist_item)
# position = int(input())
# llist1 = deleteNode(llist.head, position)
# print_singly_linked_list(llist1, ' ', fptr)
# fptr.write('\n')
# fptr.close()
|
27a6a582e21495da03010e3f11b0826e85ba16b9 | l346wang/yelp-review-nlp | /playGround.py | 222 | 3.6875 | 4 |
from nltk.corpus import stopwords
stopWords = set(stopwords.words('english'))
tokens = ['I', 'do', 'not', 'like', 'the', 'movie']
for w in tokens:
print(w)
if w not in stopWords and len(w) != 1:
print(w) |
31b9e3a89cac854c72ecf883e1ab6edda6a2358b | anna-s-dotcom/python_grundkurse_meineNotizen | /Tag03/listinlist.py | 1,221 | 4.3125 | 4 | # for i in range(3):
# for j in range(5):
# print(f"({i},{j})", end=" ")
# print()
inner=[0,1,2,3,4,5,]
outer=[]
for i in range(3):
outer.append(inner)
# print(outer)
#
#
# for i in range(len(outer)):
# print(outer[i])
# print()
#
# for i in outer:
# print(i)
# print()
# print(outer)
#alle schleifen geben untereinander alle elemente der listen aus
outer=[[1,2,3], [4,5,6], [7,8,9]]
#
# for inner in outer:
# for element in inner:
# print(element)
# print()
#
# #hier können den elementen der inneren Listen neue Werte zugewiesen werden
# for inner in outer:
# for i_inner in range(len(inner)):
# print(inner[i_inner])
# print()
#
# #hier können den elementen der inneren Listen neuen Werte zugewiesen werden
# for i_outer in range(len(outer)):
# for i_inner in range(len(outer[i_outer])):
# print(outer[i_outer][i_inner])
# print()
# for i_outer in range(len(outer)):
# for i_inner in range(len(outer[i_outer])):
# print(outer[i_outer][i_inner], f"[{i_outer}], [{i_inner}]", end= " ,")
# print()
print(outer[0])
outer[0].append(78)
print(outer[0])
print(outer)
|
07137db245532f40294510746df5eaa812c2f38d | wiput1999/PrePro60-Python | /Online/Week3/week3_earth_is_the_center2.py | 2,024 | 4.03125 | 4 | """ Earth is the center 2 """
def main():
""" Main function """
text = input()
space = (20 - len(text))//2
print("|", " " * space, "%.20s" %text, " " * space, "|", sep='')
print("FOR DEBUG: Space = ", space, " Text Length = ", len(text), sep='')
print()
space = (50 - len(text))//2
print("|", " " * space, "%.50s" %text, " " * space, "|", sep='')
print("FOR DEBUG: Space = ", space, " Text Length = ", len(text), sep='')
print()
space = (40 - len(text))//2
print("|", " " * space, "%.40s" %text, " " * space, "|", sep='')
print("FOR DEBUG: Space = ", space, " Text Length = ", len(text), sep='')
print()
space = (30 - len(text))//2
print("|", " " * space, "%.30s" %text, " " * space, "|", sep='')
print("FOR DEBUG: Space = ", space, " Text Length = ", len(text), sep='')
print()
space = (22 - len(text))//2
print("|", " " * space, "%.22s" %text, " " * space, "|", sep='')
print("FOR DEBUG: Space = ", space, " Text Length = ", len(text), sep='')
print()
space = (14 - len(text))//2
print("|", " " * space, "%.14s" %text, " " * space, "|", sep='')
print("FOR DEBUG: Space = ", space, " Text Length = ", len(text), sep='')
print()
space = (20 - len(text))//2
print("|", " " * space, "%.20s" %text, " " * space, "|", sep='')
print("FOR DEBUG: Space = ", space, " Text Length = ", len(text), sep='')
print()
space = (42 - len(text))//2
print("|", " " * space, "%.42s" %text, " " * space, "|", sep='')
print("FOR DEBUG: Space = ", space, " Text Length = ", len(text), sep='')
print()
space = (60 - len(text))//2
print("|", " " * space, "%.60s" %text, " " * space, "|", sep='')
print("FOR DEBUG: Space = ", space, " Text Length = ", len(text), sep='')
print()
space = (70 - len(text))//2
print("|", " " * space, "%.70s" %text, " " * space, "|", sep='')
print("FOR DEBUG: Space = ", space, " Text Length = ", len(text), sep='')
print()
main()
|
e464fe1e1030cc679982e1c792b478b72c95ec5e | priyankarnd/Data-Pre-processing-Training | /Operations/concatenation.py | 699 | 3.515625 | 4 | import pandas as pd
import numpy as np
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('display.max_colwidth', None)
# Data 1
df1 = pd.DataFrame([['a',1],['b',2]], columns = ['letter', 'number'])
print(df1)
# Data 2
df2 = pd.DataFrame([['c',3],['d',4]], columns = ['letter', 'number'])
print(df2)
# Concatenation
print(pd.concat([df1, df2]))
# Data 3
df3 = pd.DataFrame([['c', 3, 'cat'],['d', 4, 'dog']], columns = ['letter', 'number', 'animal'])
print(df3)
# Concatenation
print(pd.concat([df1, df3]))
#only columns common for both data frames are joined togther
print(pd.concat([df1, df3], join="inner")) |
7ac2ad4f0430d014665274752085884182fd05de | nitin-nizhawan/incubator | /prjs/prog/prblm/projecteuler/Prob120.py | 609 | 3.5625 | 4 | #!/usr/bin/python
def rmax(n):
retVal=[2,2]
n2=n*n
# for i in range (1,n,2): we should check only odd number and deliberately skip even one as for them rem is always 2, euler gives error if even numbers are not included, do not why it is so, i have sent a mail to one of the members for this
for i in range (1,n):
newRem=(2*i*n)%n2
if retVal[0]<newRem:
retVal=[newRem,i]
return retVal
rmaxsum=0;
for i in range(3,1001):
rmaxval=rmax(i)
print "a=%d ,rmax=%d , n=%d" % (i,rmaxval[0],rmaxval[1])
rmaxsum+=rmaxval[0]
if rmaxval[1]%2==0:
print "-----------------------------------"
print rmaxsum
|
dfa19935cc3d6a34025ddcc2b8603da45ccb9d12 | richnakasato/ctci-py | /3.4.queue_via_stacks.0.py | 844 | 3.75 | 4 | import random
class QueueStacks():
def __init__(self):
self.left = list()
self.right = list()
def __len__(self):
return len(self.left) + len(self.right)
def push(self, data):
self.left.append(data)
def _left_to_right(self):
while len(self.left) > 0:
self.right.append(self.left.pop())
def pop(self):
if self.is_empty():
raise Exception('empty!')
if len(self.right) == 0:
self._left_to_right()
return self.right.pop()
def top(self):
if self.is_empty():
raise Exception('empty!')
if len(self.right) == 0:
self._left_to_right()
return self.right[-1]
def is_empty(self):
return len(self) == 0
def main():
pass
if __name__ == "__main__":
main()
|
652de0279fdba567b7211acab0a9b06860fbea7e | YaoYuBJTU/ADMM_Python | /ADMM_for_Solomon_and_Jingdong_Refactoring/ADMM Solomon C101.100/C101_100_ADMM.py | 27,273 | 3.578125 | 4 | import csv
import time
import copy
import pandas as pd
import matplotlib.pyplot as plt
class Node:
"""
class name: Node
represents physical nodes in the vehicle routing system
including the origin node (depot, type=1), the destination node (depot, type=1), and the customers (type=2)
"""
def __init__(self):
"""
attributes of the Node object
"""
self.node_id = 0
self.x = 0.0
self.y = 0.0
self.type = 0
self.outgoing_node_id_list = []
self.outgoing_node_size = 0
self.outgoing_link_obj_list = []
self.demand = 0.0
self.activity_beginning_time = 0
self.activity_ending_time = 0
self.service_time = 0
self.base_profit_for_admm = 0
self.base_profit_for_lr = 0
class Link:
"""
class name: Link
represents the physical links in the vehicle routing system
the nodes incident to a link can be any physical node, including customers, origin depot, and destination depot
"""
def __init__(self):
"""
attributes of the Link object
"""
self.link_id = 0
self.from_node_id = 0
self.to_node_id = 0
# Q: how to compute the distance of a link?
# A: ((customer1['x_coord'] - customer2['x_coord']) ** 2 + (customer1['y_coord'] - customer2['y_coord']) ** 2) ** 0.5
self.distance = 0.0
self.spend_tm = 1.0
class Agent:
"""
class name: Agent
An Agent object represents a vehicle, which is a decision maker to carry out the logistics transportation missions
"""
def __init__(self):
"""
attributes of the Agent object
"""
self.agent_id = 0
self.from_node_id = 0
self.to_node_id = 0
self.departure_time_beginning = 0
self.arrival_time_ending = 0
self.capacity = 0
class VSState:
"""
class Name: VSState
class for Vehicle Scheduling State
member functions:
__init__(): generate an VSState object
my_copy(): given a VSState object, we can load the information from that VSState object through this function
calculate_label_cost: calculate the label cost of the VSState object, it is used for label updating, objective function computation, and bound value finding
generate_string_key: generate the string key of the VSState object
"""
def __init__(self):
self.current_node_id = 0
self.m_visit_node_sequence = []
self.m_visit_time_sequence = []
self.m_used_vehicle_capacity = 0
self.passenger_service_state = [0] * g_number_of_nodes
self.passenger_vehicle_visit_allowed_flag = [1] * g_number_of_nodes
self.label_cost_for_admm = 0
self.label_cost_for_lr = 0
self.primal_label_cost = 0
self.total_travel_cost = 0
self.total_waiting_cost = 0
self.total_fixed_cost = 0
def my_copy(self, current_element):
self.current_node_id = current_element.current_node_id
self.m_visit_node_sequence = copy.copy(current_element.m_visit_node_sequence)
self.m_visit_time_sequence = copy.copy(current_element.m_visit_time_sequence)
self.m_used_vehicle_capacity = current_element.m_used_vehicle_capacity
self.passenger_service_state = copy.copy(current_element.passenger_service_state)
self.passenger_vehicle_visit_allowed_flag = copy.copy(current_element.passenger_vehicle_visit_allowed_flag)
self.label_cost_for_admm = current_element.label_cost_for_admm
self.label_cost_for_lr = current_element.label_cost_for_lr
self.primal_label_cost = current_element.primal_label_cost # primal label cost is USED to compute the objective function value to the PRIMAL problem (namely, the upper bound value)
self.total_travel_cost = current_element.total_travel_cost
self.total_waiting_cost = current_element.total_waiting_cost
self.total_fixed_cost = current_element.total_fixed_cost
def calculate_label_cost(self):
# fixed cost
if from_node_id == 0 and to_node_id != g_number_of_nodes - 1:
self.label_cost_for_admm += fixed_cost
self.label_cost_for_lr += fixed_cost
self.primal_label_cost += fixed_cost
self.total_fixed_cost += fixed_cost
# transportation cost
self.label_cost_for_admm = self.label_cost_for_admm - g_node_list[to_node_id].base_profit_for_admm + link_obj.distance
self.label_cost_for_lr = self.label_cost_for_lr - g_node_list[to_node_id].base_profit_for_lr + link_obj.distance
self.primal_label_cost = self.primal_label_cost + link_obj.distance
self.total_travel_cost = self.total_travel_cost + link_obj.distance
# waiting cost
if from_node_id != 0 and waiting_cost_flag == 1:
self.label_cost_for_admm += (g_node_list[to_node_id].activity_beginning_time - next_time) * waiting_arc_cost
self.label_cost_for_lr += (g_node_list[to_node_id].activity_beginning_time - next_time) * waiting_arc_cost
self.primal_label_cost += (g_node_list[to_node_id].activity_beginning_time - next_time) * waiting_arc_cost
self.total_waiting_cost += (g_node_list[to_node_id].activity_beginning_time - next_time) * waiting_arc_cost
def generate_string_key(self):
return self.current_node_id
class TimeIndexedStateVector:
"""
class Name: TimeIndexedStateVector
vector recording states at different time instants
VSState objects will be stored in the member variables of this class
"""
def __init__(self):
self.current_time = 0
self.m_VSStateVector = []
self.m_state_map = []
def m_find_state_index(self, string_key):
if string_key in self.m_state_map:
return self.m_state_map.index(string_key)
else:
return -1
def update_state(self, new_element, ul_flag):
string_key = new_element.generate_string_key() # obtain the "string_key" of VSState object "new_element"
state_index = self.m_find_state_index(string_key) # try to find the location of the "string_key" within "m_state_map" object
if state_index == -1:
self.m_VSStateVector.append(new_element) # just add the VSState object "new_element" into "m_VSStateVector"
self.m_state_map.append(string_key) # add the "string_key" into "m_state_map"
else: # (state_index != -1)
if ul_flag == 0: # ADMM
if new_element.label_cost_for_admm < self.m_VSStateVector[state_index].label_cost_for_admm:
self.m_VSStateVector[state_index] = new_element
else: # LR
if new_element.label_cost_for_lr < self.m_VSStateVector[state_index].label_cost_for_lr:
self.m_VSStateVector[state_index] = new_element
def sort(self, ul_flag):
if ul_flag == 0: # ADMM
self.m_VSStateVector = sorted(self.m_VSStateVector, key=lambda x: x.label_cost_for_admm)
self.m_state_map = [e.generate_string_key() for e in self.m_VSStateVector]
else: # LR
self.m_VSStateVector = sorted(self.m_VSStateVector, key=lambda x: x.label_cost_for_lr)
self.m_state_map = [e.generate_string_key() for e in self.m_VSStateVector]
def get_best_value(self):
if len(self.m_VSStateVector) >= 1:
return [self.m_VSStateVector[0].label_cost_for_admm, self.m_VSStateVector[0].label_cost_for_lr, self.m_VSStateVector[0].primal_label_cost]
def read_input_data():
# global variables
global g_number_of_nodes
global g_number_of_customers
global g_number_of_links
global g_number_of_agents
global g_number_of_time_intervals
# step 1: read information of NODEs
# step 1.1: establish origin depot
node = Node()
node.node_id = 0
node.type = 1
node.x = 40.0
node.y = 50.0
node.activity_beginning_time = 0
node.activity_ending_time = g_number_of_time_intervals
g_node_list.append(node)
g_number_of_nodes += 1
# step 1.2: establish customers
with open(r"./input/input_node.csv", "r") as fp:
print('Read input_node.csv')
reader = csv.DictReader(fp)
for line in reader:
node = Node()
node.node_id = int(line['NO.'])
node.type = 2
node.x = float(line['XCOORD.'])
node.y = float(line['YCOORD.'])
node.demand = float(line['DEMAND'])
node.activity_beginning_time = int(line['READYTIME'])
node.activity_ending_time = int(line['DUEDATE'])
node.service_time = int(line['SERVICETIME'])
g_node_list.append(node)
g_number_of_nodes += 1
g_number_of_customers += 1
print(f'The number of customers is {g_number_of_customers}')
# step 1.3: establish destination depot
node = Node()
node.node_id = g_number_of_nodes
node.type = 1
node.x = 40.0
node.y = 50.0
node.activity_beginning_time = 0
node.activity_ending_time = g_number_of_time_intervals
g_node_list.append(node)
g_number_of_nodes += 1
print(f'the number of nodes is {g_number_of_nodes}')
# step 2: read information of LINKs
with open(r"./input/input_link.csv", "r") as fp:
print('Read input_link.csv')
reader = csv.DictReader(fp)
for line in reader:
link = Link()
link.link_id = int(line['ID'])
link.from_node_id = int(line['from_node'])
link.to_node_id = int(line['to_node'])
link.distance = float(line['distance'])
link.spend_tm = int(line['spend_tm'])
# establish the correlation with nodes and links
g_node_list[link.from_node_id].outgoing_node_id_list.append(link.to_node_id) # add the ID of the tail Node object into the "outbound_node_list" of the head Node object
g_node_list[link.from_node_id].outgoing_node_size = len(g_node_list[link.from_node_id].outgoing_node_id_list) # update the "outbound_node_size" of the head Node object
g_node_list[link.from_node_id].outgoing_link_obj_list.append(link) # add the Link object into the "outbound_link_list" of the head node of the Link instance
g_link_list.append(link)
g_number_of_links += 1
print(f'The number of links is {g_number_of_links}')
# step 3: read information of AGENTs
for i in range(g_number_of_agents):
agent = Agent()
agent.agent_id = i
agent.from_node_id = 0
agent.to_node_id = g_number_of_nodes - 1
agent.departure_time_beginning = 0
agent.arrival_time_ending = g_number_of_time_intervals
agent.capacity = 200
g_agent_list.append(agent)
print(f'The number of agents is {g_number_of_agents}')
def g_time_dependent_dynamic_programming(vehicle_id, origin_node, departure_time_beginning, destination_node, arrival_time_ending, beam_width, ul_flag):
# :param ULFlag: 0 or 1, controls whether the dynamic programming is for ADMM algorithm or the pure Lagrangian relaxation
# 0: ADMM (Upper Bound) ; 1: LR (Lower Bound)
# global variables
global g_ending_state_vector
global waiting_cost_flag # 0: no need to wait; 1: need to wait
global link_obj
global from_node_id
global to_node_id
global next_time
g_time_dependent_state_vector = [None] * (arrival_time_ending - departure_time_beginning + 1)
if arrival_time_ending > g_number_of_time_intervals or g_node_list[origin_node].outgoing_node_size == 0:
return MAX_LABEL_COST
for t in range(departure_time_beginning, arrival_time_ending + 1):
g_time_dependent_state_vector[t] = TimeIndexedStateVector()
g_time_dependent_state_vector[t].current_time = t
g_ending_state_vector[vehicle_id] = TimeIndexedStateVector()
# origin node
element = VSState()
element.current_node_id = origin_node
g_time_dependent_state_vector[departure_time_beginning].update_state(element, ul_flag)
# start dynamic programming
for t in range(departure_time_beginning, arrival_time_ending):
g_time_dependent_state_vector[t].sort(ul_flag)
for w in range(min(beam_width, len(g_time_dependent_state_vector[t].m_VSStateVector))):
current_element = g_time_dependent_state_vector[t].m_VSStateVector[w]
from_node_id = current_element.current_node_id
from_node = g_node_list[from_node_id]
for i in range(from_node.outgoing_node_size):
to_node_id = from_node.outgoing_node_id_list[i]
to_node = g_node_list[to_node_id]
link_obj = from_node.outgoing_link_obj_list[i]
next_time = t + link_obj.spend_tm
# case i: to_node is the destination depot
if to_node_id == destination_node:
waiting_cost_flag = 0 # no need to wait
new_element = VSState()
new_element.my_copy(current_element)
new_element.m_visit_node_sequence.append(to_node_id)
new_element.m_visit_time_sequence.append(next_time)
new_element.m_visit_node_sequence.append(to_node_id)
new_element.m_visit_time_sequence.append(arrival_time_ending)
new_element.calculate_label_cost()
g_ending_state_vector[vehicle_id].update_state(new_element, ul_flag)
continue
# case ii: to_node is the origin depot
if to_node_id == origin_node:
continue
# case iii: to_node is a customer
if current_element.passenger_vehicle_visit_allowed_flag[to_node_id] == 0:
# has been visited, no allow
continue
else: # current_element.passenger_vehicle_visit_allowed_flag[to_node_id] == 1
# time window constraint
if next_time > to_node.activity_ending_time:
continue
if next_time + to_node.service_time > arrival_time_ending:
continue
# capacity constraint
if current_element.m_used_vehicle_capacity + to_node.demand > g_agent_list[vehicle_id].capacity:
continue
# check whether it is needed to wait
if next_time < to_node.activity_beginning_time: # need to wait
waiting_cost_flag = 1
new_element = VSState()
new_element.my_copy(current_element)
new_element.current_node_id = to_node_id
new_element.passenger_service_state[to_node_id] = 1 # change the entry of "passenger_service_state" to note that the "to_node" has been visited
new_element.passenger_vehicle_visit_allowed_flag[to_node_id] = 0 # change the corresponding flag of "passenger_vehicle_visit_allowed_flag" to note that the vehicle "vehicle_id" can not visit this "to_node" again
new_element.m_visit_node_sequence.append(to_node_id)
new_element.m_visit_time_sequence.append(next_time)
new_element.m_used_vehicle_capacity += to_node.demand
new_element.m_visit_node_sequence.append(to_node_id)
new_element.m_visit_time_sequence.append(to_node.activity_beginning_time)
new_element.calculate_label_cost()
new_element.m_visit_node_sequence.append(to_node_id)
new_element.m_visit_time_sequence.append(to_node.activity_beginning_time + to_node.service_time)
g_time_dependent_state_vector[to_node.activity_beginning_time + to_node.service_time].update_state(new_element, ul_flag)
continue
else: # do NOT need to wait
waiting_cost_flag = 0
new_element = VSState()
new_element.my_copy(current_element)
new_element.current_node_id = to_node_id
new_element.passenger_service_state[to_node_id] = 1 # change the entry of "passenger_service_state" to note that the "to_node" has been visited
new_element.passenger_vehicle_visit_allowed_flag[to_node_id] = 0 # change the corresponding flag of "passenger_vehicle_visit_allowed_flag" to note that the vehicle "vehicle_id" can not visit this "to_node" again
new_element.m_visit_node_sequence.append(to_node_id)
new_element.m_visit_time_sequence.append(next_time)
new_element.m_used_vehicle_capacity += to_node.demand
new_element.calculate_label_cost()
new_element.m_visit_node_sequence.append(to_node_id)
new_element.m_visit_time_sequence.append(next_time + to_node.service_time)
g_time_dependent_state_vector[next_time + to_node.service_time].update_state(new_element, ul_flag)
continue
g_ending_state_vector[vehicle_id].sort(ul_flag)
return g_ending_state_vector[vehicle_id].get_best_value()
def g_alternating_direction_method_of_multipliers():
# global variables
global admm_local_lower_bound
global admm_local_upper_bound
global admm_global_lower_bound
global admm_global_upper_bound
global glo_lb
global glo_ub
global beam_width
global path_node_seq
global path_time_seq
global g_number_of_admm_iterations
global g_number_of_agents
global g_number_of_nodes
global service_times
global repeat_served
global un_served
global record_profit
global rho
path_node_seq = []
path_time_seq = []
service_times = []
repeat_served = []
un_served = []
record_profit = []
global_upper_bound = MAX_LABEL_COST
global_lower_bound = -MAX_LABEL_COST
for i in range(g_number_of_admm_iterations):
print(f"=== Iteration number for the ADMM: {i} ===")
number_of_used_vehicles = 0
path_node_seq.append([])
path_time_seq.append([])
service_times.append([0] * g_number_of_nodes)
repeat_served.append([])
un_served.append([])
record_profit.append([0] * g_number_of_nodes)
if i > 0:
service_times[i] = service_times[i - 1]
for v in range(g_number_of_agents - 1):
print(f"Dynamic programming for vehicle: {v}")
# prepare mu^v_p
if g_ending_state_vector[v] != None:
for n in range(1, g_number_of_customers + 1):
service_times[i][n] -= g_ending_state_vector[v].m_VSStateVector[0].passenger_service_state[n]
for n in range(1, g_number_of_customers + 1):
g_node_list[n].base_profit_for_admm = g_node_list[n].base_profit_for_lr + (1 - 2 * service_times[i][n]) * rho / 2.0
vehicle = g_agent_list[v]
g_time_dependent_dynamic_programming(v, vehicle.from_node_id, vehicle.departure_time_beginning, vehicle.to_node_id, vehicle.arrival_time_ending, beam_width, 0)
admm_local_upper_bound[i] += g_ending_state_vector[v].m_VSStateVector[0].primal_label_cost
path_node_seq[i].append(g_ending_state_vector[v].m_VSStateVector[0].m_visit_node_sequence)
path_time_seq[i].append(g_ending_state_vector[v].m_VSStateVector[0].m_visit_time_sequence)
for n in range(1, g_number_of_customers + 1):
service_times[i][n] += g_ending_state_vector[v].m_VSStateVector[0].passenger_service_state[n]
if len(path_node_seq[i][v]) != 2:
number_of_used_vehicles += 1
for n in range(1, g_number_of_customers + 1):
if service_times[i][n] > 1:
repeat_served[i].append(n)
if service_times[i][n] == 0:
un_served[i].append(n)
admm_local_upper_bound[i] += 50
# number_of_used_vehicles += 1
record_profit[i].append(g_node_list[n].base_profit_for_lr)
print(f"Number of used vehicles: {number_of_used_vehicles}")
vehicle = g_agent_list[-1]
g_time_dependent_dynamic_programming(vehicle.agent_id, vehicle.from_node_id, vehicle.departure_time_beginning, vehicle.to_node_id, vehicle.arrival_time_ending, beam_width, 1)
admm_local_lower_bound[i] += g_number_of_agents * g_ending_state_vector[g_number_of_agents - 1].m_VSStateVector[0].label_cost_for_lr
for n in range(1, g_number_of_customers + 1):
admm_local_lower_bound[i] += g_node_list[n].base_profit_for_lr
g_node_list[n].base_profit_for_lr += (1 - service_times[i][n]) * rho
if glo_ub > admm_local_upper_bound[i]:
glo_ub = admm_local_upper_bound[i]
admm_global_upper_bound[i] = glo_ub
if glo_lb < admm_local_lower_bound[i]:
glo_lb = admm_local_lower_bound[i]
admm_global_lower_bound[i] = glo_lb
def output_data():
# output path finding result
f = open("./output/output_path.csv", "w")
f.write("iteration,vehicle_id,path_node_seq,path_time_seq,\n")
for i in range(g_number_of_admm_iterations):
for v in range(g_number_of_agents - 1):
f.write(str(i) + ",") # iteration number of admm: "i"
f.write(str(v) + ",") # ID of the vehicle: "v"
str1 = "" # string which records the sequence of nodes in the path
str2 = "" # string which records the sequence of time instants in the path
for s in range(len(path_node_seq[i][v])):
str1 = str1 + str(path_node_seq[i][v][s]) + "_"
str2 = str2 + str(path_time_seq[i][v][s]) + "_"
f.write(str1 + "," + str2 + ",\n")
f.close()
# output the Lagrangian multipliers
f = open("./output/output_profit.csv", "w")
f.write("iteration,")
for n in range(1, g_number_of_customers + 1):
f.write(str(n) + ",")
f.write("\n")
for i in range(g_number_of_admm_iterations):
f.write(str(i) + ",")
for n in range(g_number_of_customers):
f.write(str(record_profit[i][n]) + ",")
f.write("\n")
f.close()
# output the gap information
f = open("./output/output_gap.csv", "w")
f.write("iteration,local_lower_bound,local_upper_bound,global_lower_bound,global_upper_bound,repeated_services,missed_services,\n")
for i in range(g_number_of_admm_iterations):
f.write(str(i) + ",") # write the current iteration number
f.write(str(admm_local_lower_bound[i]) + ",") # write the local lower bound value for the current iteration
f.write(str(admm_local_upper_bound[i]) + ",") # write the local upper bound value for the current iteration
f.write(str(admm_global_lower_bound[i]) + ",") # write the global upper bound value for the current iteration
f.write(str(admm_global_upper_bound[i]) + ",") # write the global upper bound value for the current iteration
for j in repeat_served[i]:
f.write(str(j) + "; ")
f.write(",")
for k in un_served[i]:
f.write(str(k) + "; ")
f.write(",\n")
f.close()
# plot
gap_df = pd.read_csv("./output/output_gap.csv")
iter_list = list(gap_df['iteration'])
glo_LB_list = list(gap_df['global_lower_bound'])
glo_UB_list = list(gap_df['global_upper_bound'])
loc_LB_list = list(gap_df['local_lower_bound'])
loc_UB_list = list(gap_df['local_upper_bound'])
plt.rcParams['savefig.dpi'] = 300
plt.rcParams['figure.dpi'] = 300
plt.figure()
plt.plot(iter_list, glo_LB_list, color='orange', linestyle='--')
plt.plot(iter_list, glo_UB_list, color="red")
plt.xlabel('Number of iterations', fontname="Times New Roman")
plt.ylabel('Objective value', fontname="Times New Roman")
plt.legend(labels=['Global lower bound', 'Global upper bound'], loc='best', prop={'family': 'Times New Roman'})
plt.savefig("./output/fig_global_gap.svg")
plt.show()
plt.figure()
plt.plot(iter_list, loc_LB_list, color='orange', linestyle='--')
plt.plot(iter_list, loc_UB_list, color="red")
plt.xlabel('Number of iterations', fontname="Times New Roman")
plt.ylabel('Objective value', fontname="Times New Roman")
plt.legend(labels=['Local lower bound', 'Local upper bound'], loc='best', prop={'family': 'Times New Roman'})
plt.savefig("./output/fig_local_gap.svg")
plt.show()
# plot the path finding result (spatial)
plt.figure()
for v in range(g_number_of_agents - 1):
x_coord = [40]
y_coord = [50]
for s in range(len(path_node_seq[g_number_of_admm_iterations - 1][v])):
# obtain the Node object
node_ID = path_node_seq[-1][v][s]
x_coord.append(g_node_list[node_ID].x)
y_coord.append(g_node_list[node_ID].y)
x_coord.append(40)
y_coord.append(50)
plt.plot(x_coord, y_coord, linewidth=0.5)
# plot the planar illustration
plt.scatter(40, 50, marker='^')
x_coord = []
y_coord = []
for n in g_node_list[1:-1]:
x_coord.append(n.x)
y_coord.append(n.y)
plt.xlabel("Longitude", fontname="Times New Roman")
plt.ylabel("Latitude", fontname="Times New Roman")
plt.scatter(x_coord, y_coord)
plt.savefig("./output/fig_path.svg")
plt.show()
if __name__ == "__main__":
fixed_cost = 0
waiting_arc_cost = 0
g_number_of_nodes = 0
g_number_of_customers = 0
g_number_of_links = 0
g_number_of_agents = 11 # this value is 11, the best-known solution utilizes 10 vehicles
# 10 agents are used to compute the upper bound (Admm) , 1 agent is used to compute the lower bound (LR)
g_number_of_time_intervals = 1236
g_number_of_admm_iterations = 16
MAX_LABEL_COST = 99999
beam_width = 100
rho = 1
g_node_list = []
g_link_list = []
g_agent_list = []
admm_local_lower_bound = [0] * g_number_of_admm_iterations # lower bound value of each iteration in the ADMM algorithm
admm_local_upper_bound = [0] * g_number_of_admm_iterations # upper bound value of each iteration in the ADMM algorithm
admm_global_lower_bound = [0] * g_number_of_admm_iterations # lower bound value of each iteration in the ADMM algorithm
admm_global_upper_bound = [0] * g_number_of_admm_iterations # upper bound value of each iteration in the ADMM algorithm
glo_lb = -99999
glo_ub = 99999
g_ending_state_vector = [None] * g_number_of_agents
print("Reading data......")
read_input_data()
time_start = time.time()
g_alternating_direction_method_of_multipliers()
print(f'Processing time of ADMM: {time.time() - time_start: .2f} s')
output_data()
|
d3770b89d5391c360d24be0f96a83903009c3ffe | TerrisGO/computation-of-flow-oscillation-in-pipes | /Designs/general/numerical_method.py | 17,172 | 3.671875 | 4 | # -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from Designs.general import friction_factor
from prettytable import PrettyTable
"""This module is built to solve a differential equation of the form:
d^2(z)/dt^2 + a * |dz/dt| * (dz/dt) + b*z = 0.
where a = f/2D
b = 2g/L
if there are two reservoirs
a = fk/2D where k = Le/L
b = (gA/L)*((1/A1)+(1/A2))
where A = area of pipe
A1 = area of first reservoir
A2 = area of second reservoir
reducing this 2nd order ODE to a system of 1st order ODE:
we have: dz/dt = f(t, z, V) = V
d^2(z)/dt^2 = dV/dt = g(t, z, V) = - a*|V|*V - b*z
"""
class NumericalMethod(object):
# Assign given values of all numerical methods
def __init__(self, D, L, v, e, g=9.81):
"""where v is the kinematic viscosity; unit in m^2/s.
D is the diameter of pipe; unit in meters.
L is the length of the pipe; unit in meters.
e is the roughness height; unit in m.
g is the acceleration due to gravity, 9.81m/s^2.
A1 is the area of first reservoir
A2 is the area of second reservoir
D1 is the diameter of first reservoir
D2 is the diameter of second reservoir
f is the friction factor
"""
self.D = D
self.L = L
self.v = v
self.e = e
self.g = g
self.b = (2*self.g)/self.L
self.A1 = None # no reservoir 1
self.A2 = None # no reservoir 2
self.D1 = None
self.D2 = None
self.length_minor_losses = None
self.Le = L
self.f = None #
self.pipe_label = "Pipe"
self.reservoir_1_label = "Reservoir 1"
self.reservoir_2_label = "Reservoir 2"
self.exact_label = "Exact"
self.trapezoidal_label = "Trapezoidal"
self.runge_kutta_label = "Runge-Kutta"
self.bashforth_label = "Adams Bashforth"
self.moulton_label = "Adams Moulton"
self.results = {}
def set_initial_conditions(self, t0, z0, dzdt, h, t):
"""where t0 is the initial curr_time; unit in secs.
z0 is the initial head of fluid at t0; unit in m.
dzdt is the initial velocity at t0; unit in m/s.
h is the curr_time step; unit in secs.
t is the final curr_time; unit in secs.
"""
self.t0 = t0
self.z0 = z0
self.t = t
self.h = h if h!=0 else 1
self.V0 = dzdt
def set_reservoir_param(self, D1, D2, length_minor_losses, f=None):
from math import pi
A1 = (pi * (D1**2)) / 4.0 # Cross sectional area of a circular shape
self.A1 = A1
A2 = (pi * (D2**2)) / 4.0 # Cross sectional area of a circular shape
self.A2 = A2
A = (pi * (self.D**2)) / 4.0 # Cross sectional area of a circular shape
self.A = A
self.length_minor_losses = length_minor_losses
Le = self.L + self.length_minor_losses # To get equivalent loss in pipe lenght
self.Le = Le
self.f = f
# Formula for coefficient b when we have two reservoirs.
self.b = ( (self.g * self.A) / self.L ) * ( (1/self.A1) + (1/self.A2) )
def interpolate(self, boundary_1, boundary_2, param_2):
"""Assumes boundary_1 is a list of two Real numbers
boundary_2 is a list of two Real numbers
param_2_middle is a Real numbers.
Returns: a Real number that correspond to param_2_middle,
which is the interpolation of boundary_1 and boundary_2
"""
lower, upper = 0, 1
lower_1, upper_1 = boundary_1[lower], boundary_1[upper]
lower_2, upper_2 = boundary_2[lower], boundary_2[upper]
param_1 = (((param_2 - lower_2)*(upper_1 - lower_1))/(upper_2 - lower_2)) + lower_1
return param_1
def getF(self, V):
# Returns a dictionary that contains friction factor and Reynolds number.
ff = friction_factor.FrictionFactor(V, self.v, self.e, self.D)
return ff.getF_and_R()
# This represent dz/dt = V; where V is the velocity.
def fn(self, t, z, V):
return V
# This control the value of 'a' in the 2nd order ODE
def get_k(self):
return self.Le / self.L
# Please don't use 'g' variable for the function name because 'g'
# has been used for the acceleration due to gravity; g = 9.81.
# This represent d^2(z)/dt^2 = dv/dt = - a|V|V - bz; where V is the velocity
def gn1(self, t, z, V):
# function to get friction factor and Reynold's number given a velocity.
# note that new friction factor is computed for each call of this
# function
ff = self.getF(V) if self.f == None else {"f": self.f, "R": None}
f = ff["f"] # get friction factor
R = ff["R"] # get Reynold's number
k = self.get_k()
a = (f*k)/(2*self.D) # k would be 1 if there is no reservoir since Le == L.
# which would reduce a to a = f/2D
return -(a * V*abs(V)) - (self.b * z)
def k(self, t, z, V):
return self.fn(t, z, V)
def m(self, t, z, V):
return self.gn1(t, z, V)
# Runge-Kutta constant computation for 2nd order
def runge_kutta_4th(self, tn, zn, Vn):
if (not self.A1) or (not self.A2):
ff = self.getF(Vn)
f = ff["f"] # get friction factor
R = ff["R"] # get Reynold's number
self.results[tn] = (tn, zn, Vn, f, R) # track all the required values
h = self.h
k1 = h * self.k(tn, zn, Vn)
m1 = h * self.m(tn, zn, Vn)
k2 = h * self.k(tn + h/2.0, zn + k1/2.0, Vn + m1/2.0)
m2 = h * self.m(tn + h/2.0, zn + k1/2.0, Vn + m1/2.0)
k3 = h * self.k(tn + h/2.0, zn + k2/2.0, Vn + m2/2.0)
m3 = h * self.m(tn + h/2.0, zn + k2/2.0, Vn + m2/2.0)
k4 = h * self.k(tn + h, zn + k3, Vn + m3)
m4 = h * self.m(tn + h, zn + k3, Vn + m3)
zn = zn + (1/6.0) * (k1 + 2*k2 + 2*k3 + k4)
Vn = Vn + (1/6.0) * (m1 + 2*m2 + 2*m3 + m4)
return (zn, Vn)
def get_turning_point(self, index, elem_dict):
"""Assumes index: an int
elem_dict: a dictionary,
where the key is an integer and
value is a tuple of (time, head).
Turning point definition:
A number is a turning point if
1. its absolute value is greater than or less than both absolute
value of previous number and the next number
2. and all three element are of the same sign.
"""
is_turning_point = False
head_index = 1
time_index = 0
curr_head = elem_dict[index][head_index]
curr_time = elem_dict[index][time_index]
prev_index = index - 1
next_index = index + 1
# If element is at the start of the dictionary,
# just check if the next element is a turning point neighbour.
# See doc string for turning point definition.
if index == 0:
next_head = elem_dict[next_index][head_index]
if abs(curr_head) >= abs(next_head):
if curr_head < 0 and next_head < 0:
is_turning_point = True
if curr_head > 0 and next_head > 0:
is_turning_point = True
# If element is at the end of the dictionary,
# just check if the previous element is a turning point neighbour.
# See doc string for turning point definition.
elif index == (len(elem_dict) - 1):
prev_head = elem_dict[prev_index][head_index]
if abs(curr_head) >= abs(prev_head):
if curr_head < 0 and prev_head < 0:
is_turning_point = True
if curr_head > 0 and prev_head > 0:
is_turning_point = True
# Check if the both the previous and next element are turning point
# neighbour.
# See doc string for turning point definition.
else:
prev_head = elem_dict[prev_index][head_index]
next_head = elem_dict[next_index][head_index]
if abs(curr_head) > abs(prev_head) and abs(curr_head) > abs(next_head):
# all element have to have the same sign to be a turning point
if curr_head < 0 and prev_head < 0 and next_head < 0:
is_turning_point = True
if curr_head > 0 and prev_head > 0 and next_head > 0:
is_turning_point = True
if abs(curr_head) < abs(prev_head) and abs(curr_head) < abs(next_head):
if curr_head < 0 and prev_head < 0 and next_head < 0:
is_turning_point = True
if curr_head > 0 and prev_head > 0 and next_head > 0:
is_turning_point = True
if is_turning_point:
return (curr_time, curr_head)
def get_all_turning_points_for_pipe_reservoir1_reservoir2(self, elems_dict):
'''Assumes elems_dict is a dictionary that contains:
key: a string (Pipe, Reservoir 1 or Reservoir 2)
values: dictionary:
key: an integer
value: tuple of (time, head).
'''
pipe_turning_points = {}
reservoir_1_turning_points = {}
reservoir_2_turning_points = {}
# we must have at least 3 element to get a turning point
first_dict = elems_dict[self.pipe_label]
if len(first_dict) > 2:
pipe_dict = elems_dict[self.pipe_label]
reservoir_1_dict = elems_dict[self.reservoir_1_label]
reservoir_2_dict = elems_dict[self.reservoir_2_label]
for index in range(len(first_dict)):
pipe_turning_point = self.get_turning_point(index, pipe_dict)
if pipe_turning_point != None:
pipe_turning_points[index] = pipe_turning_point
reservoir_1_turning_point = self.get_turning_point(index, reservoir_1_dict)
if reservoir_1_turning_point != None:
reservoir_1_turning_points[index] = reservoir_1_turning_point
reservoir_2_turning_point = self.get_turning_point(index, reservoir_2_dict)
if reservoir_2_turning_point != None:
reservoir_2_turning_points[index] = reservoir_2_turning_point
# return turnining points for the pipe and the two reservoirs
return {self.pipe_label: pipe_turning_points,
self.reservoir_1_label: reservoir_1_turning_points,
self.reservoir_2_label: reservoir_2_turning_points
}
def get_all_turning_points_for_pipe(self, elem_dict):
'''Assumes elems_dict is a dictionary that contains:
key: a string (Pipe, Reservoir 1 or Reservoir 2)
value: dictionary:
key: an integer
value: tuple of (time, head).
'''
pipe_dict = elem_dict[self.pipe_label]
pipe_turning_points = {}
# we must have at least 3 element to get a turning point
if len(pipe_dict) > 2:
for index in range(len(pipe_dict)):
turning_point = self.get_turning_point(index, pipe_dict)
if turning_point != None:
pipe_turning_points[index] = turning_point
return {self.pipe_label: pipe_turning_points}
def plot_single_graph(self, fig="", _title="", t_label="", z_label="",
t_vals=[], z_vals=[], _label="",
color_plus_lineType=['r--', 'b--'], line_thickness=1.0):
plt.figure(fig)
plt.clf()
plt.xlabel(t_label)
plt.ylabel(z_label)
plt.plot(t_vals, z_vals, color_plus_lineType[0],
label = _label, linewidth = line_thickness)
plt.legend(loc = 'upper right')
plt.title(_title)
plt.show()
def plot_single(self, method_vals, _type, method_label="Numerical"):
tvals = []
surge_vals = []
time, head = 0, 1
surge_dict = method_vals[_type]
for key in ((surge_dict)):
tvals.append(surge_dict[key][time])
surge_vals.append(surge_dict[key][head])
self.plot_single_graph(fig=f"{method_label} method ({_type})",
_title=f"Graph of {_type} head Vs. Time",
t_label="time, t",
z_label="head, z",
t_vals=tvals,
z_vals=surge_vals,
_label=f"{_type} (viscosity: {self.v})",
color_plus_lineType=['b--', 'r--'])
def plot_multiple_graphs(self, fig="", _title="", t_label="",
z_label="", t_vals=[], z_vals=[], labels=(),
color_plus_lineType=['b--', 'g^', 'ro'],
line_thickness=.5):
plt.figure(fig)
plt.clf()
plt.xlabel(t_label)
plt.ylabel(z_label)
y0, y1, y2 = 0, 1, 2
plt.plot(t_vals, z_vals[y0], color_plus_lineType[y0],
label = labels[y0], linewidth = line_thickness)
plt.plot(t_vals, z_vals[y1], color_plus_lineType[y1],
label = labels[y1], linewidth = line_thickness)
plt.plot(t_vals, z_vals[y2], color_plus_lineType[y2],
label = labels[y2], linewidth = line_thickness)
plt.legend(loc = 'upper right')
plt.title(_title)
plt.show()
def plot_multiple(self, method_vals, _type, method_label="Numerical"):
'''Assumes _type: string
method_vals is a dictionary that contains:
key: a string (Pipe, Reservoir 1 or Reservoir 2)
value: dictionary;
key: an integer
value: tuple of (time, head).
'''
tvals = []
pipe_vals, reservoir_1_vals, reservoir_2_vals = [], [], []
time, head = 0, 1
pipe_dict = method_vals[self.pipe_label]
reservoir_1_dict = method_vals[self.reservoir_1_label]
reservoir_2_dict = method_vals[self.reservoir_2_label]
for key in ((pipe_dict)):
tvals.append(pipe_dict[key][time])
pipe_vals.append(pipe_dict[key][head])
reservoir_1_vals.append(reservoir_1_dict[key][head])
reservoir_2_vals.append(reservoir_2_dict[key][head])
self.plot_multiple_graphs(fig=f"{method_label} method",
_title=f"Graph of Pipe-Reservoirs head Vs. Time",
t_label="time, t",
z_label="head, z",
t_vals=tvals,
z_vals=(pipe_vals,
reservoir_1_vals,
reservoir_2_vals),
labels=(self.pipe_label,
self.reservoir_1_label,
self.reservoir_2_label),
color_plus_lineType=['b--', 'g^', 'ro'])
def drawTable(self, method_vals, pipe_label="", reservoir_1_label="", reservoir_2_label=""):
table = PrettyTable()
sn_title = "sn"
time_title = "curr_time"
if self.A1 and self.A2: # if we have two reservoirs
table.field_names = [sn_title, time_title, pipe_label,
reservoir_1_label, reservoir_2_label]
table.align = 'l' # align all values to the left
for sn in (method_vals[self.pipe_label]):
pipe = method_vals[self.pipe_label]
reservoir_1 = method_vals[self.reservoir_1_label]
reservoir_2 = method_vals[self.reservoir_2_label]
t, z_pipe = pipe[sn]
t, z_reservoir_1 = reservoir_1[sn]
t, z_reservoir_2 = reservoir_2[sn]
row = [sn, t, z_pipe, z_reservoir_1, z_reservoir_2]
table.add_row(row)
else:
table.field_names = [sn_title, time_title, pipe_label]
table.align = 'l' # align all values to the left
for sn in (method_vals[self.pipe_label]):
pipe = method_vals[self.pipe_label]
t, z_pipe = pipe[sn]
row = [sn, t, z_pipe]
table.add_row(row)
print(table)
if __name__ == '__main__':
pass
|
4818e2e0f57a597414d8d7f957abaf4422cf1251 | Whatsupyuan/python_ws | /8.第八章-函数function/08_def_0803_defaultParameterVal.py | 363 | 3.546875 | 4 | '''函数声明
info="Russia" 为默认赋值
'''
def printInfo(username,info="Russia"):
print("Hello ," + username)
print("Info , " + info)
print()
# 函数调用时 , 使用参数名进行绑定
printInfo(username="Kobe",info="los angles")
printInfo(info="clc",username="James")
printInfo(username="yuan")
printInfo(username="yuan" , info="bj") |
0e5888a669f11c4a9f1bac450b826e30aa566e61 | NurbekSakiev/Algorithms | /LeetCode/116_Populating_Next_Right_Pointers.py | 1,201 | 3.921875 | 4 | # Definition for binary tree with next pointer.
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
if root:
q = [root]
while q:
n = len(q)
prev = None
for i in range(n):
node = q.pop()
if node.left:
q.insert(0,node.left)
if node.right:
q.insert(0,node.right)
if prev:
prev.next = node
prev = node
if i == n-1:
node.next = None
# Solution 2
def connect(self, root):
if not root: return
pre = root
cur = None
while pre.left:
cur = pre
while cur:
cur.left.next = cur.right
if cur.next:
cur.right.next = cur.next.left
cur = cur.next
pre = pre.left |
9c67219777740e16bf57d50c31e2597f15a2b089 | Deeptiii/Coding | /Pattern_Sliding_Window/StringAnagrams.py | 2,207 | 4.25 | 4 | # String Anagrams (hard) #
# Given a string and a pattern, find all anagrams of the pattern in the given string.
# Anagram is actually a Permutation of a string. For example, “abc” has the following six anagrams:
# abc
# acb
# bac
# bca
# cab
# cba
# Write a function to return a list of starting indices of the anagrams of the pattern in the given string.
# Example 1:
# Input: String="ppqp", Pattern="pq"
# Output: [1, 2]
# Explanation: The two anagrams of the pattern in the given string are "pq" and "qp".
# Example 2:
# Input: String="abbcabc", Pattern="abc"
# Output: [2, 3, 4]
# Explanation: The three anagrams of the pattern in the given string are "bca", "cab", and "abc".
# https://leetcode.com/problems/find-all-anagrams-in-a-string/
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
winStart = 0
n = len(s)
k = len(p)
matched = 0
sub = {}
res = []
for i in range(k):
if p[i] not in sub:
sub[p[i]] = 0
sub[p[i]]+=1
for winEnd in range(n):
charEnd = s[winEnd]
if charEnd in sub:
sub[charEnd]-=1
if sub[charEnd] == 0:
matched+=1
if matched == len(sub):
res.append(winStart)
if winEnd >= k-1:
charStart = s[winStart]
winStart+=1
if charStart in sub:
if sub[charStart] == 0:
matched-=1
sub[charStart]+=1
return res
# winStart = 0
# n = len(s)
# k = len(p)
# ana = []
# ans = []
# p = sorted(p)
# for winEnd in range(n):
# charEnd = s[winEnd]
# ana.append(charEnd)
# if len(ana)>k:
# ana.pop(0)
# winStart+=1
# if k == len(ana) and sorted(ana) == p:
# ans.append(winStart)
# return ans |
058834396a1625dc9ae49c4ede894e21f4371429 | boknowswiki/mytraning | /lintcode/python/0070_binary_tree_level_order_traversal_II.py | 970 | 3.875 | 4 | #!/usr/bin/python -t
# bfs, queue and tree traversal solution
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
from collections import deque
class Solution:
"""
@param root: A tree
@return: buttom-up level order a list of lists of integer
"""
def levelOrderBottom(self, root):
# write your code here
ret = []
if root == None:
return []
q = deque([root])
while q:
level = []
for i in range(len(q)):
node = q.popleft()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
level.append(node.val)
#print level
ret.append(level)
ret.reverse()
return ret
|
df2e72c0eec9f55ef0b2923b0faa38827fc6b21d | alokaviraj/python-program-2 | /function sumofseries.py | 205 | 3.71875 | 4 | def sumofseries():
n=int(input("enter the last digit"));
s=0;
a=1;
while(a<=n):
s=s+a;
a=a+1;
print("sum=",s)
sumofseries();
|
489fc05bf968770247ee16a0dd827e5f538105e3 | wavetogether/wave_algorithm_challenge | /2020/2020-01/29/joy.py | 187 | 3.515625 | 4 | class Solution:
def fizzBuzz(self, n: int) -> List[str]:
return ["FizzBuzz" if (i%15 == 0) else "Fizz" if (i%3==0) else 'Buzz' if (i%5==0) else str(i) for i in range(1, n+1)]
|
fa7bb5906e6ef12966f203f7853d0b8ff985d133 | sowmyamanojna/BT3051-Data-Structures-and-Algorithms | /rosalind/1_dna.py | 755 | 3.859375 | 4 | """
A string is simply an ordered collection of symbols selected from some alphabet and formed into a word; the length of a string is the number of symbols that it contains.
An example of a length 21 DNA string (whose alphabet contains the symbols 'A', 'C', 'G', and 'T') is "ATGCTTCAGAAAGGTCTTACG."
Given: A DNA string s
of length at most 1000 nt.
Return: Four integers (separated by spaces) counting the respective number of times that the symbols 'A', 'C', 'G', and 'T' occur in s
.
Sample Dataset
AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC
Sample Output
20 12 17 21
"""
fin = open("rosalind_dna.txt", 'r')
s = fin.read()
d = {}
for i in "ATGC":
d[i] = 0
for i in s:
d[i] += 1
for i in "ACGT":
print d[i], |
afc74f0bc3b7e441dae6888ff4f120ee38a2d2ac | brrgrr/LC101_Unit1 | /think_python/5.13.2.py | 841 | 4.375 | 4 | '''
Write a program to draw this. Assume the innermost square is 20 units per side and each successive square is 20 units bigger, per side, than the one inside it.
'''
import turtle
def draw_square(t, sz):
"""Get turtle t to draw a square with sz side"""
for i in range(4):
t.forward(sz)
t.left(90)
def main():
wn = turtle.Screen()
wn.bgcolor("lightgreen")
alex = turtle.Turtle()
alex.color("salmon")
alex.pensize(3)
magic_number = 20
number_of_squares = 5
for i in range(number_of_squares):
size = magic_number * (i+1)
draw_square(alex,size)
alex.up()
alex.backward(magic_number/2)
alex.right(90)
alex.forward(magic_number/2)
alex.left(90)
alex.down()
wn.exitonclick()
if __name__ == "__main__":
main()
|
b2963bb2c24bfbe85c071dc96eca82beada69863 | andy-sweet/fcdiff | /fcdiff/util.py | 1,498 | 3.59375 | 4 | """
Provides convenient, but non-vital utilities.
"""
import numpy as np
def N_to_C(N):
"""
Computes the number of connections for a network with N regions.
Arguments
---------
N : 2 <= int
Number of regions.
Returns
-------
C : 1 <= int
Number of connections.
"""
return N * (N - 1) / 2
def C_to_N(C):
"""
Computes the number of regions for a network with C connections.
Arguments
---------
C : 1 <= int
Number of connections.
Returns
-------
N : 1 <= int
Number of regions.
"""
N = (np.sqrt(8 * C + 1) - 1) / 2 + 1
return N
def nm_to_c(n, m):
"""
Converts a pair of region indices (n, m) to a connection index.
Arguments
---------
n : 0 <= int
First region index.
m : n < int
Second region index.
Returns
-------
c : 0 <= int < N * (N - 1) / 2
Connection index.
Notes
-----
N is the total number of regions.
"""
return N_to_C(n) + m
def c_to_nm(c):
"""
Converts a connection index to a pair of region indices (n, m).
Arguments
---------
c : 0 <= int < N * (N - 1) / 2
Connection index.
Returns
-------
n : 0 <= int
First region index.
m : n < int
Second region index.
Notes
-----
N is the total number of regions.
"""
n = np.floor((np.sqrt(8 * c + 1) - 1) / 2) + 1
m = c - N_to_C(n)
return (n, m)
|
d871c82c2507d7f61beecfe93af7dfff85a877c5 | inteljack/EL6183-Digital-Signal-Processing-Lab-2015-Fall | /project/Examples/Examples/PP2E/Dstruct/Classics/MoreGraphs/graph2.py | 1,415 | 3.53125 | 4 | # use exceptions to exit early
class Silent:
def found(self, soln): pass
def final(self): pass
class Interact:
def found(self, soln):
print 'Solution:', soln, 'length:', len(soln)
answer = raw_input('More? ') # after each solution
if answer not in ['Y', 'y', 'yes', 'Yes']:
raise stopSearch
def final(self):
print 'No (more) solutions' # end of the search?
silent = Silent()
interact = Interact() # make one instance
stopSearch = '' # exit search fast
class Graph:
mode = silent
def __init__(self, label, extra=None):
self.name = label
self.data = extra
self.arcs = []
def __repr__(self):
return self.name
def search(self, goal):
Graph.solns = []
try:
self.generate([self], goal)
except stopSearch:
pass
else:
self.mode.final()
Graph.solns.sort(lambda x,y: cmp(len(x), len(y)))
return Graph.solns
def generate(self, path, goal):
if self == goal:
Graph.solns.append(path)
self.mode.found(path)
else:
for arc in self.arcs:
if arc not in path:
arc.generate(path + [arc], goal)
|
856d6cef7540fb33d9fef9a114f97b201bdf6491 | Larrydek/Python-UNSAM | /03 - Trabajando con datos/solucion_de_errores.py | 2,672 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 20 16:31:25 2021
@author: Manjuanel
"""
#solucion_de_errores
#ejercicios de errores en el código
#%%
#Ejercicio 3.1: Semántica
#el error era semántico debido a que el código determinaba si la última letra era a o no.
#no reconocía 'a' mayúscula
#lo solucioné borrando el while y agregando un if con las dos condiciones
def tiene_a(expresion):
n = len(expresion)
if 'a' in expresion or 'A' in expresion:
return True
else:
return False
print(tiene_a('UNSAM 2020'))
print(tiene_a('abracadabra'))
print(tiene_a('La novela 1984 de George Orwell'))
#%%
#Ejercicio 3.2: Sintáxis
#Tenía múltiples errores sintácticos, agregué ':' y '=='
#No funcionaba para mayúsculas
def tiene_a(expresion):
n = len(expresion)
i = 0
while i<n:
if expresion[i] == 'a' or expresion[i] == 'A':
return True
i += 1
return False
print(tiene_a('UNSAM 2020'))
print(tiene_a('La novela 1984 de George Orwell'))
#%%
#Ejercicio 3.3: Tipos
#No funcionaba para números ya que el condicional del if es '1' (string)
#transformé la variable a string para ser usada en todo el programa
def tiene_uno(expresion):
expresion = str(expresion)
n = len(expresion)
i = 0
tiene = False
while (i<n) and not tiene:
if expresion[i] == '1':
tiene = True
i += 1
return tiene
print(tiene_uno('UNSAM 2020'))
print(tiene_uno('La novela 1984 de George Orwell'))
print(tiene_uno(1984))
#%%
#Ejercicio 3.4: Alcances
#La función nunca cerraba
#Le agregué el return a la función para que devuelva C y pueda ser usada
def suma(a,b):
c = a + b
return c
a = 2
b = 3
c = suma(a,b)
print(f"La suma da {a} + {b} = {c}")
print(suma(2,3))
#%%
#Ejercicio 3.5: Pisando memoria
#El problema era que siempre llenaba el registro con el último dato del camión
#Lo solucioné vaciando el registro despues de cada empuje de datos del camión al registro
import csv
from pprint import pprint
def leer_camion(nombre_archivo):
camion=[]
registro={}
with open(nombre_archivo,"rt") as f:
filas = csv.reader(f)
encabezado = next(filas)
for fila in filas:
registro[encabezado[0]] = fila[0]
registro[encabezado[1]] = int(fila[1])
registro[encabezado[2]] = float(fila[2])
pprint(registro)
#pprint(camion)
camion.append(registro)
registro = {}
return camion
camion = leer_camion('../Data/camion.csv')
pprint(camion)
|
224a52779f8f9d3ecafc4300e9a425e18902d476 | MCHARNETT/MITx-6.00.01-Week-5 | /probelm 3.py | 865 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 11 14:34:32 2017
@author: harne
"""
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
newHand = hand.copy()
word = word.lower()
for i in range(len(word)):
if word[i] not in newHand:
return False
else:
newHand[word[i]] -=1
if word in wordList:
return True
return False
WORDLIST_FILENAME = "words.txt"
print(isValidWord("rapture", hand, ))
Expected False, but got True for word: 'rapture' and hand: {'r': 1, 'a': 3, 'p': 2, 'e': 1, 't': 1, 'u': 1} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.