blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
72c689962dad9a51ba5a33f73fe7040a216bdc6f | 44652499/embedded | /python/python2/py1.py | 256 | 3.90625 | 4 | #!/usr/bin/python2
#if True:
# print ('true')
# print ('true1')
#else:
# print('false')
# print('false1')
#print ('hello')
#input("\n\nplease input any key:")
#import sys
#x='hello'
#sys.stdout.write(x+'abc\n')
a,b,c=1,2,"hello"
print a
print b
print c
|
27c3046a265df402ede5070208be4bf0093240f0 | prem0023/Python | /bubble_sort.py | 337 | 3.90625 | 4 | def sort(list):
for i in range(len(list)-1,0,-1):
for j in range(i):
if list[j] > list[j+1]: #swapping
a = list[j]
list[j] = list[j+1]
list[j+1] = a
list = [22,25,9, 10, 11,29,1, 3, 5, 7, 8,42,48,52,59,66, 15,35,36,39]
sort(list)
print(list)
|
ec201d673ea1a4681921d20bbe95a7def0af04ee | albertsuwandhi/Python-for-NE | /Week4/Exceptions.py | 960 | 3.859375 | 4 | #!/usr/bin/env python3
my_dict = {'brand':'cisco'}
'''
print("BEFORE")
print(my_dict['model'])
'''
try:
print("BEFORE")
print(my_dict['model'])
print("AFTER")
except KeyError:
print("--- Caught Exception -----")
#raise
print("--After Exception--")
print("-"*40)
try:
print(my_dict['model'])
except KeyError as e:
print(e.__class__)
print(str(e))
print("--- Caught Exception : Print Info ---")
print("-"*40)
my_list=[]
try:
print(my_list[1])
print(my_dict['model'])
except (KeyError,IndexError):
print("Multiple Exception handled")
print("-"*40)
try:
print(my_list[1])
print(my_dict['model'])
except KeyError:
print("Key Error Exception")
except IndexError:
print("Index Error Exception")
print("-"*80)
try:
print(my_dict['model'])
except Exception as e:
print(e.__class__)
print(str(e))
print("--- Caught Exception : Print Info ---")
finally:
print("Always Printed")
|
b28859e565f2f5c8c157886f7eaaa0a20d585628 | sreedevik29/python-practice | /mad-libs/mad-libs.py | 963 | 4.03125 | 4 | from random import *
def main():
name = raw_input("Write a name: ")
favourite_activity = raw_input("Write what your favourite activity is: ")
emotion = raw_input("Name an emotion: ")
pet = raw_input("What is your favourite animal? ")
second_name = raw_input("What would you name a pet: ")
celebration = raw_input("Name a holiday you'd like to celebrate: ")
third_name = raw_input("Write a third name: ")
second_activity = raw_input("Write another activity you like to do: ")
second_emotion = raw_input("How do you feel about that activity? ")
print("Hi, my name is " + name + ". My favourite thing to do is " + favourite_activity + ". It makes me feel " + emotion + ". I love my pet " + pet + " whose name is " + second_name + ". Tomorrow is " + celebration + " and to celebrate, my best friend " + third_name + " and I are going to " + second_activity + ". I'm feeling very " + second_emotion + " about tomorrow.")
if __name__ == '__main__':
main() |
51dacbf11f0019756f196129447330a8f0f222ba | lolaguer/Python210-W19 | /students/lolaguerrero/session02/series.py | 1,757 | 4.1875 | 4 | ## Fibonacci ##
def fibonacci(n):
""" Return the nth value in the fibonacci series.
Fibonnacci series: 0, 1, 1, 2, 3, 5, 8, 13, ... """
if n == 0:
return 0
elif n == 1:
return 1
else:
ans = fibonacci(n-2) + fibonacci(n-1)
return ans
# Testing Fibonacci series
print ('Testing Fibonacci:')
for i in range(0,10):
print (fibonacci(i))
## Lucas ##
def lucas(n):
""" Return the nth value in the lucas series.
Lucas series is similar to fibonacci but it starts with the values 2 and 1:
2, 1, 3, 4, 7, 11, 18, 29, ... """
if n == 0:
return 2
elif n == 1:
return 1
else:
ans = lucas(n-2) + lucas(n-1)
return ans
# Testing Lucas series
print ('Testing Lucas:')
for i in range(0,10):
print (lucas(i))
## Generalizing ##
def sum_series(n, v1=0, v2=1):
""" Calling this function with no optional parameters will produce numbers from the fibonacci series.
Calling it with the optional arguments 2 and 1 will produce values from the lucas numbers """
if (v1 == 2) and (v2 == 1):
if n == 0:
return 2
elif n == 1:
return 1
else:
ans = sum_series(n - 2, v1=2, v2=1) + sum_series(n - 1, v1=2, v2=1)
else:
if n == 0:
return 0
elif n == 1:
return 1
else:
ans = sum_series(n - 2) + sum_series(n - 1)
return ans
# Asserting the general serie
print ('Testing sum_series:')
assert (fibonacci(9) == sum_series(9))
assert (fibonacci(13) == sum_series(13))
assert (lucas(9) == sum_series(9, v1=2, v2=1))
assert (lucas(13) == sum_series(13, v1=2, v2=1))
print ('No problem with the general serie') |
1bbba29e144b409efbb73943bcd248b3909899f7 | sonyacao/Country-Classes | /processUpdates.py | 4,572 | 3.90625 | 4 | """
Sonya Cao
COMPSCI 1026
BAUER
12/04/19
Process Updates program: uses the information from an update file to change the information of specified countries in the country catalogue
"""
from CountryCatalogue import CountryCatalogue
from Country import Country
def processUpdates(cntryFileName, updateFileName):
cExists = False
while cExists == False: #will continue to prompt user for name of data file until it exists or they choose to quit
try:
countriesFile = open(cntryFileName, "r")
cExists = True
except IOError:
answer = input("Country file does not exist. Do you want to quit? (Y or N)")
if answer == "Y":
countriesFile.close()
return False
else:
cntryFileName = input("Enter the countries file name")
except:
print("An issue has occurred! The program will now exit!")
return False
cat = CountryCatalogue(cntryFileName) #creates a country catalogue object using the data file
countriesFile.close()
uExists = False
while uExists == False: #will continue to prompt user for name of updates file until it exists or they choose t
try:
updates = open(updateFileName, "r")
uExists = True
except IOError:
answer = input("Updates file does not exist. Do you want to quit? (Y or N)")
if answer == "Y":
outputFile = open("output.txt", "w")
outputFile.write("Update Unsuccessful\n")
countriesFile.close()
return False
else:
updateFileName = input("Enter the update file name")
except:
print("An issue has occurred! The program will now exit!")
return False
line = updates.readline()
while line != "": #loops through the entire updates file
countryExists = False
updateFields = line.split(";") #seperates the information in the update file
updateName = updateFields[0].strip()
for element in cat._countryCat: #if the country in the update file does not exist, a new country object is created
if element._name == updateName:
updateCountry = cat.findCountry(element)
countryExists = True
if countryExists == False:
cat.addCountry(updateName,"","","")
updateCountry = cat.findCountry(Country(updateName,"","",""))
for i in range(1, len(updateFields)):
if updateType(updateFields[i]) == 'P':
update = updateFields[i].strip()
update = update.strip("P=")
cat.setPopulationOfCountry(updateCountry, update) #updates the population of the country
elif updateType(updateFields[i]) == 'A':
update = updateFields[i].strip()
update = update.strip("A=")
cat.setAreaOfCountry(updateCountry, update) #updates the area of the country
elif updateType(updateFields[i]) == 'C':
update = updateFields[i].strip()
update = update.strip("C=")
cat.setContinentOfCountry(updateCountry, update) #updates the continent of the country
elif updateType(updateFields[i])== None: #if the file is in the wrong format will open an output fil that just has Update Unsuccessful
outputFile = open("output.txt", "w")
outputFile.write("Update Unsuccessful\n")
return False
if i == 3: #if there are more than 3 updates, stop at the third one
break
line = updates.readline()
updates.close()
CountryCatalogue.saveCountryCatalogue(cat, "output.txt") #writes the updated country catalogue to an output file
return True
def updateType(updateFields): #returns P, A or C depending on what information is being updated
updateFields = updateFields.strip(" ")
try:
if updateFields[1] == '=':
if updateFields[0] == 'P':
return 'P'
elif updateFields[0] == 'A':
return 'A'
elif updateFields[0] == 'C':
return 'C'
else:
print("Error: update file in wrong format")
except IndexError: #Exception for when the update file is in the wrong format
print("Error: update file in wrong format")
return None
except:
print("An issue has occurred! The program will now exit!")
return False
|
1547b7767ae25e5888bd5c9980896d3c1c6f8ff7 | albac/python-scripts | /numbers.py | 749 | 4.09375 | 4 | # Test code to input a N number and return a sequence from 1 to N, and print Fizz if multiple of 3, Buzz multiple of 5 and FizzBuzz if both
# Enter your code here. Read input from STDIN. Print output to STDOUT
def multiple_three(i):
number = int(i)
if number%3 == 0:
return True
return False
def multiple_five(i):
number = int(i)
if number%5 == 0:
return True
return False
def numbers(n):
for i in range(1,n):
if multiple_three(i) and multiple_five(i):
print "FizzBuzz"
elif multiple_three(i):
print "Fizz"
elif multiple_five(i):
print "Buzz"
else:
print i
n = int(raw_input('Enter number: '))
numbers(n+1)
|
804a580734e04cc26fa5e49d14b142ba988a6e12 | NaiNew/yzu | /lesson05/def Demo7.py | 186 | 3.734375 | 4 | def add(x):
return x + 1
def sub(x):
return x - 1
x = 10
x = add(x)
print(x)
x = sub(x)
print(x)
def operate(func, x):
return func(x)
x = 10
x = operate(sub, x)
print(x)
|
e491161a8306395b0810c0838e33f8fa902892e3 | flashfinisher7/ML_Fellowship | /Week2/Dictionary/Program6.py | 138 | 3.671875 | 4 |
dict_key = {1: 10, 2: 20, 3: 50}
print("Original Dictionary=", dict_key)
del dict_key[2]
print("remove key from dictionary :", dict_key)
|
17ce24c03d0f07509f76e425bb62ace83ed08533 | SDasman/Python_Learning | /DataStructuresNAlgorithms/Fibonacci_Bonanza.py | 1,956 | 4.3125 | 4 | # Print Fibonacci 1 1 2 3 5 8 13
import time
import sys
from functools import lru_cache
def fibonacci_recursive(number):
if number < 2:
return 1
return fibonacci_recursive(number - 1) + fibonacci_recursive(number - 2)
@lru_cache(maxsize=None)
def fibonacci_recursive_cached(number):
if number < 2:
return 1
return fibonacci_recursive_cached(number - 1) + fibonacci_recursive_cached(number - 2)
cache = {} #This contains numbers and their corresponding fibonnaci summed value.
def fibonacci_memoized_recursive(number):
if number < 2:
return 1
elif number in cache:
return cache[number]
sum = fibonacci_memoized_recursive(number - 1) + fibonacci_memoized_recursive(number - 2)
cache[number] = sum
return sum
# More Optimized Following:
def fibonacci_iterative(number):
first_num = 1
second_num = 0
temp = 0
for _ in range(number+1):
temp = second_num
second_num = first_num + second_num
first_num = temp
return second_num
sys.setrecursionlimit(2000)
times = 100
test_value = 2090
before_time = time.time()
for _ in range(times):
fibonacci_iterative(test_value)
print(f'This is how long the fibonacci iterative took for {test_value}, {times} times', time.time() - before_time)
# before_time = time.time()
# for _ in range(times):
# fibonacci_recursive(test_value)
# print(f'This is how long the fibonacci recursive took for {test_value}, {times} times', time.time() - before_time)
# before_time = time.time()
# for _ in range(times):
# fibonacci_recursive_cached(test_value)
# print(f'This is how long the fibonacci recursive cached took for {test_value}, {times} times', time.time() - before_time)
# before_time = time.time()
# for _ in range(times):
# fibonacci_memoized_recursive(test_value)
# print(f'This is how long the fibonacci memoized recursive took for {test_value}, {times} times', time.time() - before_time) |
914a5c4b39310cb756fe54fff1ff2b2d35b94294 | ProemPhearomDev/Python-Course | /Learn Python/4.If Else IF Else ControlFlow/IF.py | 343 | 4.25 | 4 |
# Python supports the usual logical conditions from mathematics:
# Equals: a == b
# Not Equals: a != b
# Less than: a < b
# Less than or equal to: a <= b
# Greater than: a > b
# Greater than or equal to: a >= b
a = 40
b = 40
if a < b :
print("a is less than b")
elif a > b:
print("a is greater than b")
else :
print("Nothig")
|
8eae8f58478a5e374fb38ca6f8a2c51869cf8d18 | justinuzoije/python-dictionary-exercises | /phonebook.py | 2,184 | 4.0625 | 4 | import pickle
phone_book = {}
userChoice = 0
def look_up_entry():
targetName = raw_input("Name: ")
if targetName in phone_book:
print "Found entry for %s: %s" % (targetName, phone_book[targetName])
else:
print "Entry not found"
def set_entry():
targetName = raw_input("Name: ")
targetNumber = raw_input("Phone Number: ")
phone_book[targetName] = targetNumber
print "Entry stored for %s" % targetName
def delete_entry():
targetName = raw_input("Name: ")
del phone_book[targetName]
print "Entry deleted"
def list_entry():
for entry in phone_book:
print "Found entry for %s: %s" % (entry, phone_book[entry])
def save_entry():
#open the file in write mode (w)
myfile = open('phonebook.pickle', 'w')
#dump the contents of the phonebook_dict into myfile - the open file
pickle.dump(phone_book, myfile)
#close myfile
myfile.close()
print "Entries saved to phonebook.pickle"
def restore_entry():
#The global statement lets the function know that it is talking about
#the global phone_book, not a local variable version of it
global phone_book
#open the file in read mode (r)
myfile = open('phonebook.pickle', 'r')
#load the contents from teh file and store it in the phonebook_dict variable
phone_book = pickle.load(myfile)
print "Entries restored"
while userChoice != 7:
userChoice = int(raw_input('''Electronic Phone Book
=====================
1. Look up an entry
2. Set an entry
3. Delete an entry
4. List all entries
5. Save entries
6. Restore saved entries
7. Quit
What do you want to do (1-7)?
'''))
#1 - Look up an entry
if userChoice == 1:
look_up_entry()
#2 - Set an entry
elif userChoice == 2:
set_entry()
#3 - Delete an entry
elif userChoice == 3:
delete_entry()
#4 - List all entries
elif userChoice == 4:
list_entry()
#5 - Save entries
elif userChoice == 5:
save_entry()
#6 - Restore saved entries
elif userChoice == 6:
restore_entry()
#7 - Quit
elif userChoice == 7:
print "Bye"
|
7d33deb56e172a417379dc629f35b798946e55f2 | yysherlock/Problems | /jiaBook/1-7.4_backtrack_8queens_quicker.py | 848 | 3.84375 | 4 |
n = 8
def print_sol(sol):
for i in range(len(sol)):
print '('+str(i)+','+str(sol[i])+')',
print ''
# vis list of list 3 x n
vis = []
for i in range(3):
vis.append([])
for j in range(2*n):
vis[-1].append(0)
def search(sol,row):
""" use a simple data structure to quickly check whether current solution
is valid or not """
if row == n:
print_sol(sol)
return
for col in range(n):
# vis[0][x]: x th column is occupied or not
# vis[1][x]: x th diagonal is occupied or not
# vis[2][x]: x th secondary diagonal is occupied or not
if (not vis[0][col]) and (not vis[1][col-row+n]) and (not vis[2][col+row]):
sol.append(col)
vis[0][col] = vis[1][col-row+n] = vis[2][col+row] = 1
search(sol,row+1)
vis[0][col] = vis[1][col-row+n] = vis[2][col+row] = 0
sol.pop(-1)
search([],0)
|
d22ddd682c2fde1ff8e224e8bd1c1071c4bbbd5a | tub212/PythonCodeStudy | /Python_Study/LAB/LAB_1n1.py | 560 | 3.671875 | 4 | """1TO1 """
###comment
def ntoone(number):
""" int -> int(a lot)
This function print number 1 to 1
"""
if number == 0:
print "1" "\n" "0" "\n" "1"
elif number >= 1:
for i in xrange(1, number+1):
print i
for j in reversed(xrange(1, number)):
print j
elif number <= -1:
print "1" "\n" "0"
for k in xrange(1, abs(number)+1):
print -k
for j in reversed(xrange(1, abs(number))):
print -j
print "0" "\n" "1"
ntoone(int(raw_input()))
|
c9a6e34442fcb5fb72494d64b9ca27feee6bb741 | RyanLongRoad/variables | /assignment_improvement_exercise_complete.py | 392 | 4.28125 | 4 | #john bain
#variable improvement exercise
#05-09-12
import math
radius = int(input("please enter the radius of the circle: "))
circumference = float(2* math.pi * radius)
circumference = round(circumference,2)
area = float(math.pi * radius**2)
area = round(area,2)
print("The circumference of this circle is {0}.".format(circumference))
print("The area of this circle is {0}.".format(area))
|
49a68731cf48e435c86b03f895cef3f1baf661d2 | schaul/resistance | /game.py | 6,759 | 3.875 | 4 | import itertools
import random
from player import Player
class State:
"""Simple game state data-structure that's passed to bots to help reduce
the amount of book-keeping required. Your bots can access this via the
self.game member variable.
This data-structure is available in all the bot API functions, and gets
updated automatically (in between API calls) once new information is
available about the game."""
def __init__(self):
self.turn = 1 # int (1..5): Mission number.
self.tries = 1 # int (1..5): Attempt number.
self.wins = 0 # int (1..3): Number of resistance wins.
self.losses = 0 # int (1..3): Number of spy victories.
self.leader = None # Player: Current mission leader.
self.team = None # set(Player): Set of players picked.
self.players = None # list[Player]: All players in a list.
class Game:
"""Implementation of the core gameplay of THE RESISTANCE. This class
currently only supports games of 5 players."""
NUM_TURNS = 5
NUM_WINS = 3
NUM_LOSSES = 3
def onPlayerVoted(self, player, vote, leader, team):
pass
def onPlayerSelected(self, player, team):
pass
def __init__(self, bots):
self.state = State()
# Randomly assign the roles based on the player index.
roles = [True, True, False, False, False]
random.shuffle(roles)
# Create Bot instances based on the constructor passed in.
self.bots = [p(self.state, i, r) for p, r, i in zip(bots, roles, range(1, len(bots)+1))]
# Maintain a copy of players that includes minimal data, for passing to other bots.
self.state.players = [Player(p.name, p.index) for p in self.bots]
# Configuration for the game itself.
self.participants = [2, 3, 2, 3, 3]
self.leader = itertools.cycle(self.state.players)
# Random starting leader!
for i in range(random.randint(0, 4)):
self.leader.next()
def run(self):
"""Main entry point for the resistance game. Once initialized call this to
simulate the game until it is complete."""
# Tell the bots who the spies are if they are allowed to know.
spies = set([Player(p.name, p.index) for p in self.bots if p.spy])
for p in self.bots:
if p.spy:
p.onGameRevealed(self.state.players, spies)
else:
p.onGameRevealed(self.state.players, set())
# Repeat as long as the game hasn't hit the max number of missions.
while self.state.turn <= self.NUM_TURNS:
# Some missions will take multiple turns...
if self.step():
self.state.turn += 1
self.state.tries = 1
else:
self.state.tries += 1
# If there wasn't an agreement then the spies win.
if self.state.tries > 5:
self.state.turn = self.NUM_TURNS+1
break
# Determine if either side has won already.
if self.won:
break
if self.lost:
break
# Pass back the results to the bots so they can do some learning!
for p in self.bots:
p.onGameComplete(self.state.wins >= self.NUM_WINS, spies)
@property
def won(self):
return self.state.wins >= self.NUM_WINS
@property
def lost(self):
return self.state.losses >= self.NUM_LOSSES
def step(self):
"""Single step/turn of the resistance game, which can fail if the voting
does not have a clear majority."""
# Step 1) Pick the leader and ask for a selection of players on the team.
self.state.leader = self.leader.next()
self.state.team = None
l = self.bots[self.state.leader.index-1]
for p in self.bots:
p.onMissionAttempt(self.state.turn, self.state.tries, self.state.leader)
count = self.participants[self.state.turn-1]
selected = l.select(self.state.players, count)
# Check the data returned by the bots is in the expected format!
assert type(selected) is list or type(selected) is set, "Expecting a list as a return value of select()."
assert len(set(selected)) == count, "The list returned by %s.select() is of the wrong size!" % (l.name)
for s in selected: assert isinstance(s, Player), "Please return Player objects in the list from select()."
# Make an internal callback, e.g. to track statistics about selection.
self.onPlayerSelected(l, [b for b in self.bots if b in selected])
# Copy the list to make sure no internal data is leaked to the other bots!
selected = [Player(s.name, s.index) for s in selected]
self.state.team = set(selected)
for p in self.bots:
p.onTeamSelected(self.state.leader, selected)
# Step 2) Notify other bots of the selection and ask for a vote.
votes = []
score = 0
for p in self.bots:
v = p.vote(selected[:])
self.onPlayerVoted(p, v, l, [b for b in self.bots if b in selected])
assert type(v) is bool, "Please return a boolean from vote()."
votes.append(v)
score += int(v)
# Step 3) Notify players of the vote result.
for p in self.bots:
p.onVoteComplete(votes[:])
# Bail out if there was no clear majority...
if score <= 2:
return False
# Step 4) In this case, run the mission and ask the bots if they want
# to go through with the mission or sabotage!
sabotaged = 0
for s in selected:
p = self.bots[s.index-1]
result = False
if p.spy:
result = p.sabotage()
sabotaged += int(result)
if sabotaged == 0:
self.state.wins += 1
else:
self.state.losses += 1
# Step 5) Pass back the results of the mission to the bots.
# Process the team first to make sure any timing of the result
# is the same for all player roles, specifically over IRC.
for s in selected:
p = self.bots[s.index-1]
p.onMissionComplete(sabotaged)
# Now, with delays taken into account, all other results can be
# passed back safely without divulging Spy/Resistance identities.
for p in [b for b in self.bots if b not in selected]:
p.onMissionComplete(sabotaged)
return True
|
8410a08bf61470a670b3decf20cdc51dfc64138a | pastorcmentarny/denva | /src/common/loggy.py | 681 | 3.546875 | 4 | import logging
logger = logging.getLogger('app')
def log_error_count(errors):
number_of_errors = len(errors)
if number_of_errors >= 2:
logger.error('Found {} errors. Errors: {}'.format(len(errors), str(errors)))
elif number_of_errors > 0:
logger.warning('Found {} error. Errors: {}'.format(len(errors), str(errors)))
else:
logger.debug('No errors found.')
def log_time(what: str, start_time, end_time):
logger.info('{} took {} ms.'.format(what, int((end_time - start_time) * 1000)))
def log_with_print(msg: str, warning: bool = False):
if warning:
logger.warning(msg)
else:
logger.info(msg)
print(msg)
|
4300cd659315d825b1f0d9f9e738421784c22e24 | SpyrosDellas/design-of-computer-programs | /src/WaterPouring.py | 4,136 | 4.21875 | 4 | import heapq
import doctest
def pour_problem(first_capacity: int, second_capacity: int, goal: int, start=(0, 0)) -> list:
"""Solve the water pour problem for two glasses.
We have two glasses with specified capacities, a start state and a goal state.
The goal state is specified as a volume of water that can be in either glass.
We need to find a shortest path from the start to the goal state.
>>> print(pour_problem(9, 4, 6))
[(0, 0), (9, 0), (5, 4), (5, 0), (1, 4), (1, 0), (0, 1), (9, 1), (6, 4)]
>>> print(pour_problem(7, 9, 8))
[(0, 0), (0, 9), (7, 2), (0, 2), (2, 0), (2, 9), (7, 4), (0, 4),
(4, 0), (4, 9), (7, 6), (0, 6), (6, 0), (6, 9), (7, 8)]
>>> test(10)
Exploring parameter space for glass capacities and goal in [1, 10]...
One of the problems with longest solution is: (first_capacity=8, second_capacity=9, goal=4), number of steps = 14
Solution: [(0, 0), (0, 9), (8, 1), (0, 1), (1, 0), (1, 9), (8, 2), (0, 2), (2, 0), (2, 9), (8, 3), (0, 3),
(3, 0), (3, 9), (8, 4)]
>>> test(20)
Exploring parameter space for glass capacities and goal in [1, 20]...
One of the problems with longest solution is: (first_capacity=17, second_capacity=19, goal=18), number of steps = 34
Solution: [(0, 0), (0, 19), (17, 2), (0, 2), (2, 0), (2, 19), (17, 4), (0, 4), (4, 0), (4, 19), (17, 6), (0, 6),
(6, 0), (6, 19), (17, 8), (0, 8), (8, 0), (8, 19), (17, 10), (0, 10), (10, 0), (10, 19), (17, 12), (0, 12), (12, 0),
(12, 19), (17, 14), (0, 14), (14, 0), (14, 19), (17, 16), (0, 16), (16, 0), (16, 19), (17, 18)]
"""
# the path from the previous state to each state visited
path_to = dict()
path_to[start] = None
# min oriented priority queue of states to visit; represented as tuples (path length, state)
frontier = []
heapq.heappush(frontier, (0, start))
while frontier:
current = heapq.heappop(frontier)
if goal in current[1]:
return recover_path(current[1], path_to)
for successor in successors(current[1], first_capacity, second_capacity):
if successor not in path_to:
heapq.heappush(frontier, (current[0] + 1, successor))
path_to[successor] = current[1]
return []
def recover_path(goal: tuple, path_to: dict) -> list:
"""Recover and return the path from start to goal."""
path = [goal]
previous = path_to[goal]
while previous:
path.append(previous)
previous = path_to[previous]
path.reverse()
return path
def successors(current: tuple, first_capacity: int, second_capacity: int) -> list:
result = []
level1, level2 = current
# empty the glasses
result.append((0, level2))
result.append((level1, 0))
# fill the glasses
result.append((first_capacity, level2))
result.append((level1, second_capacity))
# transfer between glasses
remainder = first_capacity - level1
level1 = min(first_capacity, level1 + level2)
level2 = max(0, level2 - remainder)
result.append((level1, level2))
level1, level2 = current
remainder = second_capacity - level2
level2 = min(second_capacity, level1 + level2)
level1 = max(0, level1 - remainder)
result.append((level1, level2))
return result
def path_length(triplet: tuple):
cap1, cap2, goal = triplet
return len(pour_problem(cap1, cap2, goal))
def test(limit):
print("Exploring parameter space for glass capacities and goal in [1, %d]..." % limit)
parameter_set = set([(cap1, cap2, goal) for cap1 in range(1, limit) for cap2 in range(cap1, limit)
for goal in range(1, max(cap1, cap2))])
max_solution = max([args for args in parameter_set], key=path_length)
max_path = pour_problem(*max_solution)
print("One of the problems with longest solution is: "
"(first_capacity=%d, second_capacity=%d, goal=%d), number of steps = %d"
% (*max_solution, len(max_path) - 1))
print("Solution: ", max_path)
if __name__ == "__main__":
print(doctest.testmod(verbose=True, optionflags=doctest.NORMALIZE_WHITESPACE))
|
68b523eb572b5c64c5bb8981aedde1aad4d2bd42 | chyfnuonuo/Algorithms_Fourth_Edition_study | /Chapter1_Fundamentals/bagqueuestack/bag.py | 1,101 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/7/19 20:45
# @Author : leo cheng
# @Email : chengyoufu@163.com
# @File : bag.py
# @Software: PyCharm
from Chapter1_Fundamentals.bagqueuestack.link_list import LinkList, Node
class Bag(object):
def __init__(self):
self.__data_list = []
def add(self, item):
self.__data_list.append(item)
def is_empty(self):
return len(self.__data_list) == 0
def __len__(self):
return len(self.__data_list)
class BagUseLinkList(object):
def __init__(self):
self.__data_list = LinkList()
def add(self, item):
node = Node(item)
self.__data_list.append(node)
def is_empty(self):
return self.__data_list.is_empty()
def __len__(self):
return len(self.__data_list)
def __iter__(self):
self.__data_list.__iter__()
return self
def __next__(self):
return self.__data_list.__next__()
if __name__ == '__main__':
bag = BagUseLinkList()
bag.add(1)
bag.add(3)
bag.add(4)
for node in bag:
print(node)
|
7aca7aa1c69c2395e32464e05854d225c4b86cd0 | simzou/robots | /Server/V2s/determineRobotMovement.py | 2,026 | 3.859375 | 4 | import math
import operator
def determineRobotMovement(startX, startY, theta, endX, endY):
"""
Function takes in the robot's starting position and heading and the
ending location and returns the angle to turn (between -pi to pi) and
the distance between the two points (i.e. the distance for the robot
to travel)
"""
def dotProduct(a, b):
return sum(map( operator.mul, a, b))
def crossProduct(a, b):
c = [a[1]*b[2] - a[2]*b[1],
a[2]*b[0] - a[0]*b[2],
a[0]*b[1] - a[1]*b[0]]
return c
# a is the unit vector for the direction the robot is facing
a = [math.cos(theta), math.sin(theta), 0]
# b is the vector from start point to end point
b = [endX - startX, endY - startY, 0]
b_mag = math.sqrt(b[0]**2 + b[1]**2)
# shouldn't happen, but in case our start and end points are the same
if b_mag == 0:
amountToTurn = 0.0
else:
# normalizing b
b = [elem / float(b_mag) for elem in b]
# a dot b = |a||b| cos (theta)
amountToTurn = math.acos(dotProduct(a,b))
# if the direction of the third element of the cross product is
# negative, we turn right (so angle is negative), else we turn left
c = crossProduct(a,b)
if c[2] < 0:
amountToTurn = amountToTurn * -1;
print "turn right"
else:
print "turn left"
distanceToTravel = b_mag
print ("amountToTurn: %f" % amountToTurn)
print ("distanceToTravel: %f" % distanceToTravel)
return (amountToTurn, distanceToTravel)
if __name__ == "__main__":
assert (determineRobotMovement(0,0,math.pi/4,0,5)[0] > 0)
assert (determineRobotMovement(0,0,math.pi/4,0,5)[1] == 5)
assert (determineRobotMovement(0,0,0,-3,0)[1] == 3)
assert (determineRobotMovement(0,0,0,-3,0)[0] - math.pi == 0)
assert (determineRobotMovement(0,0,math.pi/4,3,0)[0] < 0)
assert (determineRobotMovement(0,0,math.pi/4,0,0)[0] == 0)
assert (determineRobotMovement(0,0,math.pi/4,6,-5)[0] < 0)
assert (determineRobotMovement(0,0,math.pi/4,-5,7)[0] > 0)
determineRobotMovement(53, 74, 5.06, 360, 360) |
2517d8a431d002c737ca79ccc86fb4b1338e5462 | flogothetis/Technical-Coding-Interviews-Algorithms-LeetCode | /Must-Do-Coding-Questions-GeeksForGeeks/Arrays/trappingWater.py | 956 | 3.796875 | 4 | '''
Trapping Rain Water
Medium Accuracy: 42.45% Submissions: 100k+ Points: 4
Given an array arr[] of N non-negative integers representing height of blocks at index i as Ai where the width of each block is 1. Compute how much water can be trapped in between blocks after raining.
Structure is like below:
| |
|_|
We can trap 2 units of water in the middle gap.
'''
def trappingWater (array) :
n = len(array)
rightMaxBlock = [None] * n
# Track right tollest block
curr_max = -1
for block in range (n-1, -1, -1):
curr_max= max(curr_max, array[block])
rightMaxBlock[block] = curr_max
left_curr_max = -1
countTrappingWater = 0
for block in range (n):
left_curr_max = max (left_curr_max, array[block])
countTrappingWater += max (min (left_curr_max, rightMaxBlock[block]) - array[block] , 0)
return countTrappingWater
print( trappingWater([7 ,4 ,0 ,9]))
print( trappingWater([6,9,9]))
|
b6c3f60bb0568359fe2d2ff9ba14bf0412e80588 | leigh90/zero-to-hero-python-Udemy | /Section13:AdvancedModules/regexe.py | 3,968 | 4.375 | 4 | text = "The agent's phone number is is 408-55-1234"
print("phone" in text)
# import regex library, then pass in the search term to re.search()
# re.search takes in a number of parameters the pattern you are searching for, where to search for it and others
# it returns the start and end index (span) of the search term as well as the match for example <_sre.SRE_Match object; span=(12, 17), match='phone'>
import re
pattern = "phone"
pattern2 = "zawadi"
march = re.search(pattern, text)
print(march)
print(march.span())
print(march.start())
print(march.end())
# if it doesnt find a match it returns None
print(re.search(pattern2, text))
# you can use .findall() to return all instances of a pattern in the text
text1 = "my phone is in my phone"
matches = re.findall('phone', text1)
print(len(matches))
print(matches)
# to return each match object
for match in re.finditer('phone', text1):
# returns tuples of the start and end index of each occurence
print(match.span())
# to return the exact text that matched
print(match.group())
# Regular Expressions
# Character identifiers
# The Syntax - backslash character for example \d which is a digit
# \d - A DIGIT for example file_\d\d would look for fileunderscoretwodigits e.g file_25
# \w - ALPHANUMERIC e.g \w-\w\w\w any alphanumeric character followed by a hyphen and 3 more letters or numbers also includes underscores A-b_1
# \s WHITESPACE - a\sb\sc letter a whitespace letter b whitespace letter c
# \D NON DIGIT \D\D\D three non-digits e.g ABC
# \W NON ALPHANUMERIC \W\W\WWWWW not a letter or number e.g ^.+=)
# \S NON WHITESPACE \S\S\S\S not a whitespace e.g Yoyo
# EXAMPLE
textone = 'My phone nummber is 408-555-7777'
phone = re.search(r'\d\d\d-\d\d\d-\d\d\d\d',textone)
# r raw string tells python that the backslash is not meant to be escaped like you would to avoid quote mark errors
# please search for a pattern that is 3digits hyphen 3 digits hyphen 4-digits
print(phone)
# to print the exact matching text
print(phone.group())
# QUANTIFIERS - Allow you to replicate characters in asimpler way
# + means 'search where this specific pattern Occurs more than once.' \w-\w+ alphanumeric followed by hyphen followed by more than one alphanumeric character Version A-b1_1
# {3} Occurs exactly 3 times \D{3} this specific character appears more than once abc
# {2,4} occurs in the range provided eg \d{2,4} digits occuring between 2 to 4 times
# {3,} Occurs 3 or more times \w{3} any alphanumeric characters appearing more than the number provided
# * Occurs more than 0 times e.g A*B*C* a occurs more than 0 times b occurs more thank 0 times and c occurs more than 0 times e.h AAACCC
# ? Once or none E.g plurals? does s appear once or none e.g plural
# Quantifier with expressions
phone = re.search(r'\d{3}-\d{3}-\d{4}',textone)
print(phone)
# to print the exact matching text
print(phone.group())
# say you wanted to separate pieces of the pattern you can use the compile method
phone_pattern = re.compile(r'(\d{3})-(\d{3})-(\d{4})')
results = re.search(phone_pattern,textone)
results.group()
# to rturn the specific parts of the pattern
print(results.group(1))
print(results.group(2))
print(results.group(3))
# ADDITIONAL SYNTAX
# | (pipe) means or e.g
re.search(r'cat|dog','the cat is here')
# . (wildcard) means anything before the characters I am looking for re.findall(r'.at','The cat in the hat sat there') will return 'cat','hat,'sat' insted of at,at,at
re.findall(r'.at','The cat in the hat sat there')
# ^ (caret) means start with
re.findall(r'\d','1 is a number')
# $ means ends with
re.findall(r'\d$','2 is a number 6')
# [] means exclude
phrase = 'there are 3 numbers in 34 inside this 5 sentence'
pattern3 = r'[^\d]+' #this says exclude all digits
print(re.findall(pattern3, phrase))
# good way to remove punctuation
phrase_test = "This is a string! But it has punctuation. How can we remove it"
clean = re.findall(r'[^!.?]+', phrase_test)
print(''.join(clean)) |
b77c745496c8f56327f19bc1c2285ff040fbab3b | smileshy777/practice | /sword/KthNode.py | 607 | 3.640625 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.list_ = []
def KthNode(self, pRoot, k):
if k == 0:
return None
self.helper(pRoot)
if k > len(self.list_):
return None
return self.list_[k - 1]
def helper(self, node):
if node:
self.helper(node.left)
self.list_.append(node)
self.helper(node.right)
obj = Solution()
a = TreeNode(0)
a.left = TreeNode(1)
print(obj.KthNode(a, 2)) |
06a1d60d9ca18c63ffa489fdd08bff32be6f8ff3 | pBouillon/codesignal | /arcade/python/2_Lurking_in_Lists/Lists_Concatenation.py | 838 | 4.0625 | 4 | """
Given two lists lst1 and lst2, your task is to return
a list formed by the elements of lst1 followed by the
elements of lst2.
Note: this is a bugfix task, which means that the
function is already implemented but there is a bug in
one of its lines. Your task is to find and fix it.
Example
For lst1 = [2, 2, 1] and lst2 = [10, 11], the output should be
listsConcatenation(lst1, lst2) = [2, 2, 1, 10, 11].
Input/Output
[execution time limit] 4 seconds (py3)
[input] array.integer lst1
Guaranteed constraints:
0 ≤ lst1.length ≤ 20,
-106 ≤ lst1[i] ≤ 106.
[input] array.integer lst2
Guaranteed constraints:
0 ≤ lst2.length ≤ 20,
-106 ≤ lst2[i] ≤ 106.
[output] array.integer
"""
def listsConcatenation(lst1, lst2):
res = lst1
res.extend(lst2)
return res
|
c45dc8060dfadd8022ef491348935194dfca1647 | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/grnguy001/question2.py | 1,820 | 4.15625 | 4 | #Done By Guy Green
#Dot Product, adding vectors and working out magnitude of vectors
#For assignment 6
import math
#Getting vector from user
VectorA=input("Enter vector A:\n")
VectorB=input("Enter vector B:\n")
#Seperating the numbers of the vectors
VectorA=VectorA.split(" ")
VectorB=VectorB.split(" ")
#Might NOT work for boundary cases
#Working out dot product by multiplying each of the like components and adding it to original 0
dotAB=0
for i in range(len(VectorA)):
ComponentA=VectorA[i] #x,y and z components
ComponentB=VectorB[i] #x,y and z components
dotAB+=eval(ComponentA)*eval(ComponentB)
#Creating a list because it is easier to print required output
sumAB=[]
for j in range(len(VectorA)):
ComponentA=VectorA[j]
ComponentB=VectorB[j]
ABadded=str(eval(ComponentA)+eval(ComponentB)) #adding the components as strings so they don't add different components of the vector
sumAB.append(int(ABadded)) #Adding to list
#Working out magnitude by adding the square of the components and and then squarerooting the sum
magAsquared=0.00
magBsquared=0.00
for k in range(len(VectorA)):
ComponentA=VectorA[k]
ComponentB=VectorB[k]
magAsquared+=(eval(ComponentA))**2 #Squaring each component
magBsquared+=(eval(ComponentB))**2 #Squaring each component
#Squarerooting it and rounding it off to two decimal places
magA=math.sqrt(magAsquared)
magA=round(magA, 2)
magB=math.sqrt(magBsquared)
magB=round(magB, 2)
#If it an actual integer is the answer, python only gives one decimal place. This is to add a decimal place
if len(str(magA))==3:
magA=str(magA)+"0"
if len(str(magB))==3:
magB=str(magB)+"0"
#Printing
print("A+B =", sumAB)
print("A.B =", dotAB)
print("|A| =", magA)
print("|B| =", magB) |
ffc113f08dd28517400d9cbf6a978704e96bce7f | ViRaL95/HackerRank | /Queues/queues_using_two_stacks.py | 765 | 3.59375 | 4 | input_value = input()
enqueue = []
dequeue = []
for index in range(0, int(input_value)):
input_value = input()
if (len(input_value.split(" ")) == 2):
[operation, element] = input_value.split(" ")
else:
operation = input_value.split(" ")[0]
if operation == '1':
enqueue.append(element)
elif operation == '2':
if len(dequeue) == 0:
while (len(enqueue) > 0):
popped_element = enqueue.pop()
dequeue.append(popped_element)
dequeue.pop()
elif operation == '3':
if len(dequeue) == 0:
while (len(enqueue) > 0):
popped_element = enqueue.pop()
dequeue.append(popped_element)
print(dequeue[len(dequeue) -1])
|
2ecdce790c294b2c463871e3240f3b144e0a2437 | 2014mchidamb/Standalone-Algos | /Data_Structures/skip_list.py | 4,274 | 3.734375 | 4 | '''
Simple skip list implementation; see Wikipedia for details.
'''
from time import time
import math
import random
class ListNode:
# Skip list node class that has links to levels below.
def __init__(self, val, num_levels=1):
self.val = val
self.next = None
self.prev = None
self.below = None
self.copy_below(num_levels)
def copy_below(self, num_levels):
# Makes this node into a ladder of num_levels nodes.
cur = self
for i in range(num_levels-1):
cur.below = ListNode(self.val)
cur = cur.below
def splice(self, node):
self.next.prev = node
node.next = self.next
node.prev = self
self.next = node
def connect(self, node):
self.next = node
node.prev = self
def connect_all(self, node):
cur = self
while cur and node:
cur.connect(node)
cur = cur.below
node = node.below
def remove(self):
if self.prev and self.next:
# Can't remove head or tail.
self.prev.connect_all(self.next)
class SkipList:
def __init__(self, vals, max_level=32, insertion_prob=0.5):
self.max_level = max_level
self.insertion_prob = insertion_prob
# Initialize head and tail of list.
self.head = ListNode(-math.inf, self.max_level)
self.tail = ListNode(math.inf, self.max_level)
self.head.connect_all(self.tail)
# Initialize rest of list.
self.initialize(vals)
def find(self, val):
# Returns node if found, otherwise None.
cur = self.head
while cur:
while val > cur.val:
cur = cur.next
if val == cur.val:
break
cur = cur.prev.below
return cur
def insert(self, val):
# Keeps previous node at each level.
prevs = []
cur = self.head
while cur:
while val >= cur.val:
# Guaranteed to stop since tail has math.inf.
cur = cur.next
cur = cur.prev
prevs.append(cur)
# Step back, and then move down a level.
cur = cur.below
node = None
prob = 0
prev_index = len(prevs) - 1
while prev_index >= 0 and prob <= self.insertion_prob:
# Add node above current node and splice it into list
# at that level.
up_node = ListNode(val)
up_node.below = node
prevs[prev_index].splice(up_node)
# Randomly choose whether to add at next level.
prev_index -= 1
node = up_node
prob = random.random()
def delete(self, val):
node = self.find(val)
if node:
node.remove()
def initialize(self, vals):
for val in vals:
self.insert(val)
def print_list(self):
cur = self.head
while cur:
next_cur = cur.below
while cur:
print(cur.val, end=' ')
cur = cur.next
cur = next_cur
print()
def TEST_SKIP_LIST(nums_size=1000):
nums = list(range(nums_size))
skip = SkipList(nums, 10, 0.5)
def simple_find(val):
for num in nums:
if num == val:
return num
return None
queries = [random.randint(-nums_size, nums_size) for i in range(nums_size)]
simple_ans = [0 for i in range(nums_size)]
skip_ans = [0 for i in range(nums_size)]
start = time()
for i, query in enumerate(queries):
simple_ans[i] = simple_find(query)
simple_time = time() - start
start = time()
for i, query in enumerate(queries):
skip_ans[i] = skip.find(query)
skip_time = time() - start
for i in range(nums_size):
if skip_ans[i] != None:
skip_ans[i] = skip_ans[i].val
print("Total time taken by simple search: ", simple_time)
print("Total time taken by skip list: ", skip_time)
if simple_ans != skip_ans:
print("TEST FAILED: Answers are not equal.")
else:
print("TEST PASSED: Answers are equal.")
if __name__ == '__main__':
TEST_SKIP_LIST()
|
20a4ae7189d0541a2cb0ff510c0409250ad41e5c | xuehaushu/Project_data | /jsonsp.py | 545 | 3.84375 | 4 |
#!/usr/bin/python3
import json
#将字典类型转换成jason类型对象
data = {
'no':1,
'name':'Runoob',
'url':'http://www.runoob.com'}
json_str = json.dumps(data)
print("Python原数据:",repr(data))
print("JASON对象:",json_str)
#将json对象转换为字典
data2 = json.loads(json_str)
print("data2['name']",data2['name'])
print("data2['url']",data2['url'])
#数据json的写入和读取
with open('data.json','w') as f:
json.dump(data,f)
with open('data.json','r') as f:
data3 = json.load(f)
print(repr(data3)) |
a751bd0a529fa3526908f623fd609c3d51b20524 | lev2cu/python_test | /pandas/test5.py | 354 | 3.671875 | 4 |
from pandas import Series, DataFrame
import pandas as pd
left = DataFrame({'k1': ['sd','we', 'er'], 'k2': ['df','iu','ew'], 'lval': [1,2,3]})
right = DataFrame({'k1':['rt','sd'], 'k2': ['iu', 'iu'], 'rval':[4,5]})
#multiple keys: pass a list of column names -> on=['key1', 'key2'],
data = pd.merge(left,right,on=['k1','k2'], how = 'outer')
print data |
b6f323c1b563af7c9eb5ab3507b6512e7e045ba8 | jermainejk/ultra-savers | /JUsers.py | 1,677 | 3.515625 | 4 | class JUsers():
def __init__(self, username, account, password):
self.__username = username
self.__account = account
self.__password = password
def get_username(self):
return self.__username
def get_account(self):
return self.__account
def get_password(self):
return self.__password
def set_username(self, username):
self.__username = username
def set_account(self, account):
self.__account = account
def set_password(self, password):
self.__password = password
class Child():
def __init__(self,parent,bank,month,year,child,account,amount):
self.__parent = parent
self.__child = child
self.__account = account
self.__amount = amount
self.__bank = bank
self.__month = month
self.__year = year
def get_parent(self):
return self.__parent
def get_child(self):
return self.__child
def get_account(self):
return self.__account
def get_amount(self):
return self.__amount
def get_bank(self):
return self.__bank
def get_month(self):
return self.__month
def get_year(self):
return self.__year
def set_parent(self, parent):
self.__parent = parent
def set_child(self, child):
self.__child = child
def set_account(self, account):
self.__account = account
def set_amount(self, amount):
self.__amount =amount
def set_bank(self, bank):
self.__bank =bank
def set_month(self, month):
self.__month = month
def set_year(self, year):
self.__month = year |
dc5362cbd5ffd557083452b35498d0e00b1f5727 | HarshaSudhakaran/excercise | /divisible_five.py | 119 | 3.859375 | 4 | list=[1101,102,103,104,105,106,107,108,109,110]
for i in list:
if i%5==0:
print(i,'is divisible by 5')
|
27b07b393844838fb2c5d710a337e0dae9f50f0d | c-boe/Reinforcement-learning | /4 Dynamic programming/Jacks car rental/policy_iteration.py | 8,768 | 3.703125 | 4 | """
Implementation of Exercise 4.7 in Chapter 4 of Sutton and Barto's "Reinforcement
Learning"
"""
import numpy as np
from jackscarrental import JacksCarRental
import time
import matplotlib.pyplot as plt
#%%
def init_val_fun(max_cars_per_loc):
'''
Initialize state value function for iterative policy improvement
Parameters
----------
max_cars_per_loc : int
maximum number of cars per location.
Returns
-------
V : ndarray, shape (max_cars_per_loc, max_cars_per_loc)
State value function
'''
# state value function
V = np.zeros((max_cars_per_loc + 1, max_cars_per_loc + 1))#
return V
def init_policy(max_cars_per_loc):
"""
Initialize policy for iterative policy improvement
Parameters
----------
max_cars_per_loc : int
maximum number of cars per location.
Returns
-------
pi : ndarray, shape (max_cars_per_loc, max_cars_per_loc)
policy.
"""
# policy
pi = np.zeros((max_cars_per_loc + 1, max_cars_per_loc + 1))
return pi
#%%
def eval_policy(env, pi, V, theta, gamma):
'''
Calculate state value function for given policy
Parameters
----------
env :
JCS MDP
pi : ndarray
policy
V : ndarray
state value function
theta : float
treshold for policy evaluation
gamma : float
discount factor of DP
Returns
-------
V : ndarray, shape (max_cars_per_loc, max_cars_per_loc)
state value function
'''
v_tmp = np.zeros(V.shape)
Delta = theta + 1
while theta < Delta:
Delta = 0
for cars_A in range(0, V.shape[0]):
for cars_B in range(0, V.shape[1]):
v_tmp[cars_A, cars_B] = V[cars_A, cars_B]
# Calculate value function for given action
V[cars_A, cars_B] = value_function(env, (cars_A, cars_B),
pi[cars_A, cars_B], V, gamma)
# compare value function with previous value function
Delta = np.max([Delta, np.abs(v_tmp[cars_A, cars_B] -
V[cars_A, cars_B])])
return V
def improve_policy(env, V, actions):
'''
Iterate improvement of policy
Parameters
----------
env :
JCS MDP
V : ndarray
state value function
actions: int
number of cars moved
Returns
-------
V : ndarray, shape (max_cars_per_loc, max_cars_per_loc)
state value function
'''
pi = np.zeros(V.shape)
for cars_A in range(0, V.shape[0]):
for cars_B in range(0, V.shape[1]):
Q_prev = 0
for action in actions:
# maximum number of cars which can be shifted
if cars_A + action >= 0 and cars_B - action >= 0:
# Calculate Q value function for given state (cars_A, cars_B)
# and action a
Q_next = value_function(env, (cars_A, cars_B), action, V, gamma)
if Q_next > Q_prev:
Q_prev = Q_next
pi[cars_A, cars_B] = action
return pi
def value_function(env, current_state, action, Value_function, gamma):
"""
Calculate value function for given initial state and action
Parameters
----------
env :
JCS MDP
current_state : tuple
current state consisting of number of cars at A and B
action :
number of cars shifted from A to B
Value_function : ndarray, shape (max_cars_per_loc, max_cars_per_loc)
state value function
Returns
-------
V_value : float
state value for current state
"""
# probability transition matrix
p = env.PTM_dict["p"]
n_B_ret = env.PTM_dict["n_B_ret"]
n_A_ret = env.PTM_dict["n_A_ret"]
n_B_req = env.PTM_dict["n_B_req"]
n_A_req = env.PTM_dict["n_A_req"]
# calculate how many cars can be rented currently
# (assume that requests and returns happen at the same)
n_A_req_2 = np.array([current_state[0] + n_A_ret + int(action),
n_A_req]).min(axis = 0)
n_B_req_2 = np.array([current_state[1] + n_B_ret - int(action),
n_B_req]).min(axis = 0)
# send all additional cars away
next_state_A = np.array([current_state[0] + n_A_ret - n_A_req_2 + int(action),
env.max_cars_per_loc*np.ones(len(n_A_ret))]).min(axis = 0)
next_state_B = np.array([current_state[1] + n_B_ret - n_B_req_2 - int(action),
env.max_cars_per_loc*np.ones(len(n_A_ret))]).min(axis = 0)
next_state_A = next_state_A.astype(int)
next_state_B = next_state_B.astype(int)
# calculate rewards and value function
parking_A = next_state_A > env.nr_free_parking
parking_B = next_state_B > env.nr_free_parking
reward_parking = env.reward_parking_lot*(next_state_A*parking_A +
next_state_B*parking_B)
reward_rent = (env.reward_req*(n_A_req_2 + n_B_req_2))
reward = reward_rent + reward_parking
reward_shift = env.reward_shift*((action - env.free_shift_AB)*(action>0) -
(action)*(action<0))
VF_state = p*(reward + gamma*Value_function[next_state_A, next_state_B])
V_value = VF_state.sum() + reward_shift
return V_value
def policy_iteration(env, theta, gamma):
'''
Policy iteration algorithm
Parameters
----------
env :
Jacks car service MDP
theta : float
treshold for policy evaluation
gamma : float
discount factor of DP
Returns
-------
V : ndarray, shape (max_cars_per_loc, max_cars_per_loc)
state value function
pi : ndarray, shape (max_cars_per_loc, max_cars_per_loc)
policy
'''
actions = env.action_space()
V = init_val_fun(env.max_cars_per_loc)
pi = init_policy(env.max_cars_per_loc)
pi_tmp = np.random.rand(pi.shape[0],pi.shape[1])
while not np.array_equal(pi, pi_tmp):
pi_tmp = pi
# evaluate value function
V = eval_policy(env, pi_tmp, V, theta, gamma)
# improve_policy
pi = improve_policy(env, V, actions)
# plots
return V, pi
#%%
def plot_VF(V):
'''
Plot value function as a function of number of cars at each location
Parameters
----------
V : ndarray, shape (max_cars_per_loc, max_cars_per_loc)
state value function
Returns
-------
None.
'''
plt.figure()
plt.imshow(V)
plt.colorbar()
plt.title("Value function")
plt.xlabel("Cars at B")
plt.ylabel("Cars at A")
def plot_policy(pi):
'''
Plot policy as a function of number of cars at each location
Parameters
----------
pi : ndarray, shape (max_cars_per_loc, max_cars_per_loc)
policy
Returns
-------
None.
'''
plt.figure()
plt.imshow(pi)
plt.colorbar()
plt.title("policy function")
plt.xlabel("Cars at B")
plt.ylabel("Cars at A")
#%%
if __name__ == '__main__':
"""
Set parameters and run jacks car service (Example 4.2 and Exercise 4.7
in Chapter 4 of Sutton and Barto's "Reinforcement Learning" )
"""
max_cars_per_loc = 20 # max number of cars per location
gamma = 0.9 # discount factor
theta = 0.01 # treshold for policy evaluation
lbd_req_A = 3 # lambda paramters of poisson distribution for
lbd_ret_A = 3 # request and return at location A
lbd_req_B = 4 # location B
lbd_ret_B = 2
max_n = 8 # defines number of considered terms in poisson distr.
min_shift = -5 # max. number of shifted cars (action space)
max_shift = 5
reward_req = 10 # reward for requested car
reward_shift = -2 # penalty for car moved over night
nr_free_parking = 10 # number of free parking cars
reward_parking_lot = 0 # penalty for parking more cars over night
free_shift_AB = 1 # shift first car from A to B for free
start = time.time()
env_JCS = JacksCarRental(
max_cars_per_loc, min_shift, max_shift,
lbd_req_A, lbd_ret_A, lbd_req_B, lbd_ret_B, max_n,
reward_req, reward_shift, reward_parking_lot,
nr_free_parking, free_shift_AB
)
V, pi = policy_iteration(env_JCS, theta, gamma)
end = time.time()
print(end - start)
plot_policy(pi)
plot_VF(V) |
1b9adfa35407e8cde6022f0177b01f8c0b18b9de | williamd4112/market-oriented-multi-agent-system | /simulator/time_sys.py | 1,217 | 3.65625 | 4 | import numpy as np
import math
class TimeSystem(object):
'''
A time system use hour as atomic unit.
'''
PERIOD = 24
HALF_PERIOD = PERIOD / 2
PERIOD_REPRS = ['AM', 'PM']
def __init__(self, initial_hour, initial_day=0):
self.current_sim_hour = initial_hour * initial_day + initial_hour
def step(self, stride=1):
self.current_sim_hour += stride
self.current_day = math.floor(self.current_sim_hour / TimeSystem.PERIOD)
self.current_hour = self.current_sim_hour % TimeSystem.PERIOD
def day(self):
return math.floor(self.hour_in_sim() / TimeSystem.PERIOD)
def hour_in_half_day(self):
return self.hour_in_a_day() % TimeSystem.HALF_PERIOD
def hour_in_a_day(self):
return self.hour_in_sim() % TimeSystem.PERIOD
def hour_in_sim(self):
return self.current_sim_hour
def __repr__(self):
day = self.day()
hour = int(self.hour_in_half_day())
rep = int(self.hour_in_a_day() / TimeSystem.HALF_PERIOD)
return '%dd%dh%s' % (day, hour, TimeSystem.PERIOD_REPRS[rep])
if __name__ == '__main__':
sys = TimeSystem(12)
print(sys)
|
5bff6f695dfe6f165edb5e5ca915688bdb9725d8 | 7286065491/python.py | /78.py | 65 | 3.734375 | 4 | rs=int(input())
if (rs%13==0):
print("yes")
else:print("no")
|
3dc84c5b2ae089b9a2932a77b14ed5c9655619d3 | BedaSBa6koi/Homework-16.04.2020 | /task20.py | 546 | 3.90625 | 4 | # Функция которая высчитывает являются ли введённые числа чётными или нет. Выводится в двух разных списках
def counting():
digits = list(map(int, input('Enter the numbers ').split()))
# digits = int
odd = []
even = []
for i in digits:
if i % 2 == 0:
even.append(i)
else:
odd.append(i)
print('Нечётные числа - ', odd)
print('Чётные числа - ', even)
counting()
|
b19b5c40f851553995e1f053ae58392678a6c199 | Saighi/2i013 | /Othello/Joueurs/joueur_humain.py | 489 | 3.625 | 4 | import sys
sys.path.append("../..")
import game
def saisieCoup(jeu):
""" jeu -> coup
Retourne un coup a jouer
"""
listc = jeu[2]
n = 0
print(" Coup possible :"+str(jeu[2])+"\n")
for coup in listc:
print("coup "+ str(n) + " x = " + str(coup[0]) + " y = " + str(coup[1]) + "\n")
n += 1
n = int(input("Quel coup choisissez vous : "))
while n < 0 or n >len(listc):
n = int(input("Quel coup choisissez vous : "))
return listc[n]
|
003af52274e4a38856d85d618bb578da353c3594 | LysanderGG/Advent-of-code-2019 | /day03.py | 1,280 | 3.65625 | 4 | from typing import Generator, Iterable, List, Tuple
def read_input(filepath) -> Generator[List[Tuple[str, int]], None, None]:
with open(filepath) as f:
for l in f.readlines():
yield [(x[0], int(x[1:])) for x in l.strip().split(',')]
def compute_wire(coordinates: List[Tuple[str, int]]) -> Generator[Tuple[int, int], None, None]:
dir_factors = {
"U": (0, 1),
"D": (0, -1),
"L": (-1, 0),
"R": (1, 0),
}
x, y = (0, 0)
for direction, dist in coordinates:
dx, dy = dir_factors[direction]
for _ in range(dist):
x += dx
y += dy
yield (x, y)
def intersection(w1: Iterable[Tuple[int, int]], w2: Iterable[Tuple[int, int]]) -> int:
intersections = set(w1) & set(w2)
return min(abs(c[0]) + abs(c[1]) for c in intersections)
def fewest_steps(w1: List[Tuple[int, int]], w2: List[Tuple[int, int]]) -> int:
intersections = set(w1) & set(w2)
return min(w1.index(i) + w2.index(i) + 2 for i in intersections)
if __name__ == "__main__":
c1, c2 = read_input("day03.txt")
wire_1 = list(compute_wire(c1))
wire_2 = list(compute_wire(c2))
print(f"Part1: {intersection(wire_1, wire_2)}")
print(f"Part2: {fewest_steps(wire_1, wire_2)}")
|
de749a5d1d617842d8cc83e743fa301c9fa3cdfe | ronaldomatias/ExerciciosPython | /20.py | 459 | 3.9375 | 4 | soma_pares = 0
soma_impares = 0
valor = 0
while valor <= 1000:
print("Para cancelar, insira um valor acima de 1000.")
valor = int(input("Digite um valor do tipo inteiro: "))
if (valor%2 == 0) and (valor < 1000):
soma_pares = valor + soma_pares
if (valor%2 == 1) and (valor < 1000):
soma_impares = valor + soma_impares
print("A soma dos pares foi: ", soma_pares)
print("A soma dos ímpares foi: ", soma_impares) |
4da3aa40c5595846c8171a4d1b8f57ce0c5c2f38 | Yosha2707/data_structure_algorithm | /asigments_files/recurssion1/power_of_number.py | 667 | 4.125 | 4 | # Write a program to find x to the power n (i.e. x^n). Take x and n from the user. You need to print the answer.
# Note : For this question, you can assume that 0 raised to the power of 0 is 1
# Input format :
# Two integers x and n (separated by space)
# Output Format :
# x^n (i.e. x raise to the power n)
# Constraints:
# 0 <= x <= 8
# 0 <= n <= 9
# Sample Input 1 :
# 3 4
# Sample Output 1 :
# 81
# Sample Input 2 :
# 2 5
# Sample Output 2 :
# 32
from sys import stdin
li = stdin.readline().rstrip().split(" ")
n = int(li[0])
m = int(li[1])
def squr(n, m):
if m == 0:
return 1
m = m - 1
return n * squr(n, m)
ans = squr(n,m)
print(ans)
|
b7d6c2e28d7f4eee9db8673b5c82191e54d1fea1 | SECCON/SECCON2019_online_CTF | /crypto/coffee_break/files/encrypt.py | 514 | 3.515625 | 4 | import sys
from Crypto.Cipher import AES
import base64
def encrypt(key, text):
s = ''
for i in range(len(text)):
s += chr((((ord(text[i]) - 0x20) + (ord(key[i % len(key)]) - 0x20)) % (0x7e - 0x20 + 1)) + 0x20)
return s
key1 = "SECCON"
key2 = "seccon2019"
text = sys.argv[1]
enc1 = encrypt(key1, text)
cipher = AES.new(key2 + chr(0x00) * (16 - (len(key2) % 16)), AES.MODE_ECB)
p = 16 - (len(enc1) % 16)
enc2 = cipher.encrypt(enc1 + chr(p) * p)
print(base64.b64encode(enc2).decode('ascii'))
|
1aee58b910fd18d8f69fe59880ce801a4c898870 | AndreBuchanan92/COSC_1336_Python | /Andre_Buchanan_Lab3a.py | 1,706 | 4.1875 | 4 | #Part A
print('Hello, cousin. I cannot understand your measurments! I created this program to help you in the US.')
km = int(input('\nPlease input your kilometers: '))
miles = km / 1.6
if km < 0 :
print ("Error: please re-enter a positive number.")
else :
print ('You have gone ', miles ,' miles')
#Part B
print ('\nOkay, now lets do temperature')
celsius = int(input('What is the temperature in celsius? '))
fahrenheit = (celsius * 9/5) + 32
if celsius > 1000 :
print ("Error: please re-enter less than 1000 degrees")
else:
print ('The temperature is ', fahrenheit, 'degrees.')
#Part C
print ('\nOkay, now lets do liters')
liters = int(input('How many liters do you have? '))
gallons = liters / 3.9
if liters < 0 :
print ("Error: please re-enter a positive number.")
else:
print ('You have ', gallons, 'gallons')
#Part D
print ('\nOkay, now lets do kilograms')
kilogram = int(input('How many kilograms do you have? '))
lbs = kilogram / .45
if kilogram < 0 :
print ("Error: please re-enter a postive number.")
else:
print ('You have ', lbs, 'pounds')
#Part E
print ('\nOkay, now lets do centimeters')
cm = int(input('How many centimeters do you have? '))
inches = cm / 2.54
if cm < 0 :
print("Error: please input a positive number.")
else:
print ('You have ', inches, 'inches')
|
75554766e10e2ebd6273f52abf5513d6987e6807 | jnhasard/IIC2233-Programacion_Avanzada | /Tareas/T02/Enfermedad.py | 2,589 | 3.53125 | 4 | from random import randint
from Listasjh import jhlist
class Infeccion:
def __init__(self, tipo):
self.tipo = tipo
if tipo == "Virus":
self.contagiosidad = 1.5
self.mortalidad = 1.2
self.resistencia = 1.5
self.visibilidad = 0.5
elif tipo == "Bacteria":
self.contagiosidad = 1
self.mortalidad = 1
self.resistencia = 0.5
self.visibilidad = 0.7
elif tipo == "Parásito":
self.contagiosidad = 0.5
self.mortalidad = 1.5
self.resistencia = 1
self.visibilidad = 0.45
def __repr__(self):
return self.tipo
class Cura:
def __init__(self, pob_inicial, infeccion):
self.dia = 0
self.gente_sana = pob_inicial -1
self.pob_inicial = pob_inicial
self.infeccion = infeccion
self.gente_infectada = self.pob_inicial - self.gente_sana
self.gente_muerta = 0
self.proba = 0
self.descubierto = False
self.progress = 0
self.cura = False
def descubrimiento(self, infecciones, muertes):
self.gente_sana -= infecciones
self.gente_infectada += infecciones - muertes
self.gente_muerta += muertes
self.dia += 1
self.proba = (self.infeccion.visibilidad * self.gente_infectada *
(self.gente_muerta**2)) / (self.pob_inicial**3)
random = randint(0,100)
if (self.proba*100) > random:
self.descubierto = True
print("Se ha descubierto oficialmente la INFECCION\n"
"Ahora se buscara la cura")
def progreso(self, infecciones, muertes, mundo):
self.gente_sana -= infecciones
self.gente_infectada += infecciones - muertes
self.gente_muerta += muertes
self.dia += 1
self.progress -= +self.gente_sana/(2*self.pob_inicial)
if (self.progress % 1) != 0:
self.progress = int(self.progress) + 1
else:
self.progress = int(self.progress)
print("\nProgreso:", "|" * self.progress, " "*(98-self.progress), "|\n")
if self.progress >= 100:
self.progress = 100
self.cura = True
vivos = jhlist()
for i in mundo:
if i.valor.clasificacion != "Muerto":
vivos.agregar(i)
pais = randint(0,len(vivos)-1)
print("Se ha descubierto la CURA\nEsta se encuentra en",
vivos[pais], "y comenzará inmediatamente a repartirla")
|
fcd8722695c5ae66f5216b82eef65af10d2097b5 | embatbr/whatever | /less-than-1-hour/problem2.py | 289 | 4.03125 | 4 | # assuming list are of the same length
# not using iteration either
def combine_lists(A, B):
length = len(A)
ret = list()
for i in range(length):
ret.append(A[i])
ret.append(B[i])
return ret
A = ['a', 'b', 'c']
B = [1, 2, 3]
print(combine_lists(A, B)) |
b6247c2673d9dadf3a5f99ded54be0fee7da1ab4 | lixuanhong/LeetCode | /PermutationSequence.py | 2,512 | 3.53125 | 4 | """
The set [1,2,3,...,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note:
Given n will be between 1 and 9 inclusive.
Given k will be between 1 and n! inclusive.
Example 1:
Input: n = 3, k = 3
Output: "213"
Example 2:
Input: n = 4, k = 9
Output: "2314"
"""
"""
http://bangbingsyb.blogspot.com/2014/11/leetcode-permutation-sequence.html
1234
1243
1324
1342
1423
1432
2134
2143
2314 <= k = 9
2341
2413
2431
3124
3142
3214
3241
3412
3421
4123
4132
4213
4231
4312
4321
最高位可以取{1, 2, 3, 4},而每个数重复3! = 6次。所以第k=9个permutation的s[0]为{1, 2, 3, 4}中的第9/6+1 = 2个数字s[0] = 2。
而对于以2开头的6个数字而言,k = 9是其中的第k' = 9%(3!) = 3个。而剩下的数字{1, 3, 4}的重复周期为2! = 2次。所以s[1]为{1, 3, 4}中的第k'/(2!)+1 = 2个,即s[1] = 3。
对于以23开头的2个数字而言,k = 9是其中的第k'' = k'%(2!) = 1个。剩下的数字{1, 4}的重复周期为1! = 1次。所以s[2] = 1.
对于以231开头的一个数字而言,k = 9是其中的第k''' = k''/(1!)+1 = 1个。s[3] = 4
"""
class Solution:
def getPermutation(self, n, k):
res = ''
k -= 1
fac = [1] * n
num = [str(i) for i in range(1, 10)]
for i in range(1, n):
fac[i] = fac[i-1] * i
for i in range(n, 0, -1):
first = k // fac[i-1]
k %= fac[i-1]
res += num[first]
num.pop(first)
return res
# My Solution - 这里用dfs超时,如果是java或者c++用dfs可以通过
class Solution(object):
def getPermutation(self, n, k):
def Permutation(arr, tmp, res):
if len(tmp) == n:
res.append(tmp)
for i in range(len(arr)):
if str(arr[i]) in tmp: #string里面没有append和pop, 要注意arr[i]是int, 要转换成str. 这个判断很重要,如果已经有了,要跳出当前循环,继续下一次!!
continue
tmp += str(arr[i])
Permutation(arr, tmp, res)
tmp = tmp[:-1] #取了tmp的substring要重新赋值给tmp
return res
arr = [i+1 for i in range(n)]
res = []
Permutation(arr, "", res)
return res[k-1]
obj = Solution()
print(obj.getPermutation(3, 3))
|
a19952a15eb8c4de58017efdbaeafc1ba32d66a0 | dinosaurz/ProjectEuler | /id035.py | 1,242 | 3.734375 | 4 | from time import clock
BADDIG = ['0', '2', '4', '5', '6', '8']
def is_circular(num):
'''Return whether the number is a circular prime'''
def _rotate(num):
'''Return a tuple of numbers with rotated digits'''
numlist = [i for i in str(num)]
rotate = []
for i, _ in enumerate(numlist):
newnum = numlist[i:] + numlist[:i]
rotate.append(''.join(newnum))
return rotate
def _is_prime(num):
'''Return boolean indicating whether num is prime'''
if num == 2:
return True
if num % 2 == 0:
return False
for i in range(3, int(num ** 0.5) + 1, 2):
if num % i == 0:
return False
return True
if _is_prime(num):
for i in BADDIG:
if i in str(num) and i != str(num):
return False
tests = _rotate(num)
for poss in tests:
if not _is_prime(int(poss)):
return False
return True
return False
def main():
start = clock()
total = sum([1 for i in xrange(2, 1000000) if is_circular(i)])
print "%s found in %s seconds" % (total, clock() - start)
if __name__ == '__main__':
main()
|
62bbc55d11172cef6812ffd809e71a2ad2d8fd80 | jpike/PythonProgrammingForKids | /BasicConcepts/Functions/FunctionWithSingleParameterFromUserInput.py | 296 | 4.34375 | 4 | # This is the definition for our function.
def PrintGreeting(name):
print("Hello " + name + "!")
# We can get the values we pass for parameters from anywhere.
# In this case, we're getting the value for the name parameter
# from the user.
name = input("Enter a name: ")
PrintGreeting(name)
|
eb0d41a5fce8ed0aed4bfa83ee50f70db169a3b8 | nologon/P4E | /P4I/Chapter7/exc7.1-shout.py | 350 | 4.5625 | 5 | #!/usr/bin/env python
#~ Exercise 7.1 Write a program to read through a file and print the contents of the
#~ file (line by line) all in upper case. Executing the program will look as follows:
file = 'mbox-short.txt'
#~ file = raw_input('what is the filename?: ')
file_opened = open(file)
for line in file_opened:
line = line.rstrip()
print line
|
ac073677ad57d3072260cd27c44d659e4dd37ead | Twicer/Homeworks | /Homework8-13.03/Task2.py | 1,224 | 3.953125 | 4 | """Задача 2
В текстовый файл построчно записаны фамилия и имя учащихся класса и его оценка за контрольную.
Вывести на экран всех учащихся, чья оценка меньше 3 баллов и посчитать средний балл по классу.
"""
# Создание файла + запись в него
with open("students.txt","w") as f:
data = ["Mark Avr 8", "Andrew Shvedov 2", "Jan Abc 3"]
f.writelines("\n".join(data))
print(data, "\n")
with open("students.txt","r") as f: # Закроет автоматически
summa = 0
c = 0 # для количества учащихся. Из условия можно взять и количество строк,
# но я проверяю каждую строку на наличие оценки
for i in f.readlines():
nums = [int(j) for j in i if j.isdigit()] # list comprehensions, только для чисел
summa += nums[0]
c += 1
if nums[0] <= 3:
print("The bad student is: ", i)
print("\nCредний балл по классу = {}".format(round(summa/c,2)))
|
f16e37c4205d2374078774c23c82c1a00713324b | gagandeepsinghbrar/codeSignal | /easyAssignmentProblem.py | 1,039 | 3.8125 | 4 | def easyAssignmentProblem(skills):
# special case where employee TWO does both jobs equally
if skills[1][0]==skills[1][1]:
# worry about how employee ONE would do
if skills[0][0]>skills[0][1]:
first = 1
second = 2
else:
first =2
second =1
else:
# special case where both employees do first job equally
if skills[0][0]==skills[1][0]:
# let's check if who does the second job better
if skills[0][1]> skills[1][1]:
first = 2
second = 1
else:
first =1
second = 2
else:
# no special case
# Store the better performer for first job
first = 1 if skills[0][0]> skills[1][0] else 2
# Similarly store the better performer for first job
second = 2 if first ==1 else 1
return [first,second]
|
15067f681da822f6a78882b6d4f64d079aef1213 | chlos/exercises_in_futility | /leetcode/merge_sorted_array.py | 1,723 | 4.0625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution_my_ugly(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
i1, i2 = 0, 0
i1_back_init = m
while i2 < n:
if nums1[i1] >= nums2[i2] or i1 >= i1_back_init:
i1_back = i1_back_init
while i1_back > i1:
nums1[i1_back] = nums1[i1_back - 1]
i1_back -= 1
nums1[i1] = nums2[i2]
i2 += 1
i1_back_init += 1
i1 += 1
def merge_hack(self, nums1, m, nums2, n):
nums1[m:] = nums2[:n]
nums1.sort()
# Three Pointers (Start From the End)
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
idx = m + n - 1
idx1 = m - 1
idx2 = n - 1
while idx >= 0:
if idx2 < 0:
break
if idx1 >= 0 and nums1[idx1] > nums2[idx2]:
nums1[idx] = nums1[idx1]
idx1 -= 1
else:
nums1[idx] = nums2[idx2]
idx2 -= 1
idx -= 1
s = Solution()
nums1 = [1, 2, 3, 0, 0, 0]
nums2 = [2, 5, 6]
s.merge(nums1, 3, nums2, len(nums2))
print nums1
assert nums1 == [1, 2, 2, 3, 5, 6]
print 'ok'
nums1 = [1, 1, 1, 0, 0, 0]
nums2 = [1, 1, 1]
s.merge(nums1, 3, nums2, len(nums2))
print nums1
assert nums1 == [1, 1, 1, 1, 1, 1]
print 'ok'
|
b2f801b14bf2da06f11b64bc379522fda9cbb561 | 19sProgrammersStudy/Byeongjun | /Programmers_Lv1/Programmers_lv1_정수 제곱근 판별.py | 255 | 3.609375 | 4 | #레벨1.정수 제곱근 판별
#https://programmers.co.kr/learn/courses/30/lessons/12934?language=python3
import math
def solution(n):
x=int(math.sqrt(n))
if x**2== n:
answer=(x+1)*(x+1)
else :
answer = -1
return answer |
3c046d3b284118dbad8e115779893f373be3227b | Roagen7/phy | /src/classes/Ball.py | 3,353 | 3.59375 | 4 |
class Ball:
def __init__(self,x, y, r, m, color, FPS):
self.x = x;
self.y = y;
self.r = r;
self.m = m;
#self.surface = surface
self.color = color
self.forces = []
self.FPS = FPS
deflect = False
@property
def ax(self):
return self.ax
@property
def ay(self):
return self.ay
@property
def vx(self):
return self.vx
@property
def vy(self):
return self.vy
@property
def v(self):
return self.v
@property
def angle(self):
return self.angle
@vx.getter
def vx(self):
return self.__vx
@vy.getter
def vy(self):
return self.__vy
@v.getter
def v(self):
import math
return math.sqrt(self.__vy**2 + self.__vx**2)
@ax.getter
def ax(self):
s = sum([f.value for f in self.forces if f.direction == 'x'])
return s/self.m
@ay.getter
def ay(self):
s = sum([f.value for f in self.forces if f.direction == 'y'])
return s/self.m
#angle between V and OX
@angle.getter
def angle(self):
import math
add = 0
if self.vx == 0 and self.vy == 0:
return 0
if self.vx == 0 and self.vy != 0:
if self.vy < 0:
return 3*math.pi/2
return math.pi/2
if self.vy == 0 and self.vx != 0:
if self.vx > 0:
return 0
return math.pi
deg = math.atan(abs(abs(self.vy)/abs(self.vx)))
quar = self.checkQuarter()
if quar == 1:
return deg
if quar == 2:
return math.pi - deg
if quar == 3:
return math.pi + deg
if quar == 4:
return 2*math.pi - deg
return 0
@angle.setter
def angle(self, ang):
import math
V = self.v
self.vx = math.cos(ang) * V
self.vy = math.sin(ang) * V
@vx.setter
def vx(self,vx):
self.__vx = vx
@vy.setter
def vy(self,vy):
self.__vy = vy
def move(self):
self.x += self.vx
self.y += self.vy
self.vx += self.ax/self.FPS
self.vy += self.ay/self.FPS
self.clear_forces()
def move_away(self):
self.x += self.vx/abs(self.vx) * self.r
self.y += self.vy/abs(self.vy) * self.r
def checkIfCollides(self,other):
if abs(other.x - self.x + other.vx) <= self.r:
if abs(other.y - self.y + other.vy) <= self.r + 3:
return True
return False
def checkQuarter(self):
if self.vx > 0:
if self.vy > 0:
return 1
if self.vy < 0:
return 4
if self.vx < 0:
if self.vy > 0:
return 2
if self.vy < 0:
return 3
def collision(self,other):
self.vx, other.vx = other.vx, self.vx
self.vy, other.vy = other.vy, self.vy
def apply_force(self,force):
self.forces.append(force)
def clear_forces(self):
self.forces = []
def draw(self, pygame, surface):
pygame.draw.circle(surface,self.color,[self.x,self.y],self.r,0)
|
8daa95d79b09bb218418d14cb92897e5c5b8ac11 | vamsigontla7/MyLearningRepo | /Python_Practice/draw_square_customize.py | 504 | 3.734375 | 4 | import turtle
def draw_square() :
window = turtle.Screen()
window.bgcolor("pink")
turtle.shape('turtle')
turtle.color('red')
turtle.speed(0)
brad = turtle.Turtle()
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
angie = turtle.Turtle()
angie.shape('arrow')
angie.color('blue')
angie.circle(100)
window.exitonclick()
draw_square()
|
dac68410a033ef191747ed887ae29d2a0e4fd792 | zanzydnd/yandex-algorithm-training | /div B/hw2/bench.py | 454 | 3.578125 | 4 | def popping_blocks(middle, blocks, k):
i = 0
while i < k:
if blocks[i] < middle < blocks[i] + 1:
return blocks[i]
if blocks[i] <= middle <= blocks[i + 1]:
return "" + str(blocks[i]) + " " + str(blocks[i + 1])
i += 1
if __name__ == '__main__':
l, k = list(map(int, input().split()))
blocks = list(map(int, input().split()))
middle = l / 2
print(popping_blocks(middle, blocks, k))
|
cc5b5d5355b15860d97f5d38cb95180497c59116 | llzxo/python_practice | /3.4.py | 80 | 3.6875 | 4 | a = input("input a:")
b = input("input b:")
sum = a + b
print("a + b = %d"%sum)
|
34c8d073fbe1e5f9ac2f6f3a004ad5788cdd6838 | hvl5451/HW4_New | /account.py | 1,551 | 4.125 | 4 | """
Accounts are accessible by customers and every employee.
Account information can be modified only by customers and managers.
Accounts can only be closed/deleted by managers.
"""
import datetime
class Account:
"""
Implementation of a customer's bank account.
Can hold and update a balance.
Can process withdrawals and deposits made by the account holder.
"""
def __init__(self, holder, created_on, account_number, account_type, balance=0.0):
self._holder = holder
self._created_on = created_on
self._account_number = account_number
self._account_type = account_type
self._balance = balance
def get_holder(self):
"""Returns the customer that holds the account."""
return self._holder
def get_created_on(self):
"""Returns the date the account was created on."""
return self._created_on
def get_account_number(self):
"""Returns the unique identification number of the account."""
return self._account_number
def get_account_type(self):
"""Gets the type of the account (savings, checking, etc.)"""
return self._account_type
def get_balance(self):
"""Returns the amount of money in the account."""
return self._balance
def update_balance(self, amount):
"""
Raises or lowers the balance in the account.
Args:
amount - quantity of money to be added to / removed from
the account balance
"""
self._balance += amount
|
9dcf0cabba53ab03c2ffac9d0b206ee273a1fde3 | lixiang2017/leetcode | /leetcode-cn/0628.1_Maximum_Product_of_Three_Numbers.py | 589 | 3.609375 | 4 | '''
approach: Sort
Time: O(NlogN)
# Space: O(N) O(logN)
执行结果:
通过
显示详情
执行用时:56 ms, 在所有 Python 提交中击败了76.51% 的用户
内存消耗:14.2 MB, 在所有 Python 提交中击败了11.11% 的用户
'''
class Solution(object):
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
maximum = -sys.maxint
mid1 = nums[0] * nums[1] * nums[-1]
tail = nums[-3] * nums[-2] * nums[-1]
maximum = max(maximum, mid1, tail)
return maximum
|
4788ad871ae36f41ad954990c11baa03952c223e | EruDev/Python-Practice | /菜鸟教程Python3实例/18.py | 509 | 3.953125 | 4 | # 斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13,
# 特别指出:第0项是0,第1项是第一个1。从第三项开始,每一项都等于前两项之和。
def fibo(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibo(n-1) + fibo(n-2)
def print_fibo(scope):
for i in range(scope):
print('%d,' % fibo(i), end='')
if __name__ == '__main__':
while True:
number = int(input('\n请输入需要输出的斐波那契数列的项数:'))
print_fibo(number)
|
44154f15022ab974065241f5bab6a3ac741e33cd | SuleimanMS/topshiriqlar | /masala 24.06.21/3) juft son rostlik.py | 204 | 3.859375 | 4 | while True :
n = int(input('\nSon kiriting:\n---> '))
if n == 0 :
print('Juft son emas!')
elif n%2 != 0 :
print('Juft son emas!')
else :
print('Juft son')
|
e9b1275ec8f5e52acb23c5c855a889a18149f0b9 | mjsterckx/CS5245 | /p01/p01_lorentz.py | 185 | 4.125 | 4 | s = float(input('Enter the velocity (m/s): '))
c = 3 * (10 ** 8)
lorentz = 1 / ((1 - (s ** 2 / c ** 2)) ** (1 / 2))
print('The Lorentz factor at', str(s), 'm/s is', str(lorentz) + '.')
|
5052a2104f60ed8b2af5158cc7e6fc3533d5af17 | bdebut01/projects | /ecosym/code/seablock.py | 2,556 | 3.578125 | 4 | # Seablock module
# Stores the unit of location used by the simulation
# which stores aspects of the ocean at the given location
# and coordinates the many creatures that can be resident therein
# Part of the EcoSym Project
from sets import Set
from helper_functions import with_lock
from threading import Lock
class SeaBlock :
# SeaBlock initializer
# Takes optional arguments for attributes which can also be set using
# provided functions
def __init__(self, salinity = 1, sun = 0, oxygen = 0, pressure = 0,
currentXImpact=0, currentYImpact=0):
self.__salinity = salinity
self.__sunlight = sun
self.__oxygen = oxygen
self.__pressure = pressure
self.__currentXImpact = currentXImpact
self.__currentYImpact = currentYImpact
self.__organisms = Set()
# stores which organisms are locally available
# to be used to see what is organisms neighbor another organism
self.__orgsLock = Lock()
# clears an organism from the block
# to be used if the organism dies or travels to a different block
def removeOrganism(self, organism):
def remove():
if organism in self.__organisms:
self.__organisms.remove(organism)
with_lock(self.__orgsLock, remove)
# adds this organism only to the block
# used when an organism enters the area or when a new one is added
def addOrganism(self, Creature) :
with_lock(self.__orgsLock, lambda : self.__organisms.add(Creature))
# getters and setters for the attributes of the block
def setSunlight(self, val) :
self.__sunlight = val
def getSalinity(self): return self.__salinity
def getSunlight(self): return self.__sunlight
def getOxygen(self): return self.__oxygen
def getPressure(self): return self.__pressure
# Returns a list of the organisms that are in the block at the time the
# function is called. The list is passed by value, not by reference
def getOrganisms(self):
def getOrgs():
orgsAsList = list(self.__organisms)
return orgsAsList[:] # return by value, not by reference
return with_lock(self.__orgsLock, getOrgs)
def getCurrent(self):
return (self.currentXImpact, currentYImpact)
def printAttributes(self):
print "Salinity: " + str(self.getSalinity())
print "Sunlight: " + str(self.getSunlight())
print "Oxygen: " + str(self.getOxygen())
print "Pressure: " + str(self.getPressure())
|
2d4c5f6a076bbb96ad01854d8245e9c900cd9f91 | darkcoders321/fahim | /Learn and Practice PyThOn/chepter-7 (String)/example1.py | 182 | 3.75 | 4 | str1=input("Upper:")
str1=str1.upper()
str2=input("lower:")
str2=str2.lower()
str3=int(input("integer:"))
str4=input("No conditon:")
print(str1,str2,str3,str4)
|
4c9698dbd8811ae8d31c8ecd926c3d20b392ba7d | coolhass-offical/how-to-python | /Python-Indentation-and-comments.py | 644 | 4.09375 | 4 | # A code block (body of a function, loop, etc.) starts with indentation and ends with the first unindented line.
# The amount of indentation is up to you, but it must be consistent throughout that block.
if True:
print('Hello')
a = 5
# The enforcement of indentation in Python makes the code look neat and clean.
# This results in Python programs that look similar and consistent.
for i in range(1, 11):
print(i)
if i == 5:
break
# We can have comments that extend up to multiple lines.
# One way is to use the hash( # ) symbol at the beginning of each line.
""" Another way of doing this is to use triple quotes """
|
2b55d0c415444ccd19eb75f8054480e7ddb52f0e | hakubishin3/nlp_100_knocks_2020 | /ch01/03.py | 467 | 3.8125 | 4 | """
03. 円周率
“Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.”という文を単語に分解し,
各単語の(アルファベットの)文字数を先頭から出現順に並べたリストを作成せよ.
"""
text = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
answer = [len(w) for w in text.replace(",", "").replace(".", "").split()]
print(answer)
|
62492b76f85cbd3b8e41cbd01a82e8f8c93f22fc | bhandari-nitin/Python-Code | /Python-Codes/Graph.py | 1,062 | 3.828125 | 4 | ###################
##### Graphs ######
###################
class Node(object):
def __init__(self, value):
self.value = value
self.edges = []
class Edges(object):
def __init__(self, value, node_from, node_to):
self.value = value
self.node_from = node_from
self.node_to = node_to
class Graph(object):
def __init__(self, nodes=[], edges=[]):
self.nodes = nodes
self.edges = edges
def insertNode(self, value):
new_node = Node(value)
self.nodes.append(new_node)
def insertEdge(self, new_edge_val, node_from_val, node_to_val):
from_found = None
to_found = None
for node in self.nodes:
if node_from_val == node.value:
from_found = node
if node_to_val == node.value:
to_found = node
if from_found == None:
from_found = Node(node_from_val)
self.nodes.append(from_found)
if to_found == None:
to_found = Node(node_to_val)
self.nodes.append(to_found)
new_Edge = Edge(new_edge_val, from_found, to_found)
from_found.edges.append(new_Edge)
to_found.edges.append(new_Edge)
self.edges.append(new_Edge)
|
1d8d7e4d21bb15a966086fbd32eeac0b3369d3b8 | matheusforlan/TST-P1 | /ex088.py | 509 | 3.734375 | 4 | #coding:utf-8
from random import randint
print "----------- JOGO DA MEGA SENA ------------ "
quantidade = int(raw_input("Quantos jogos serão feitos? "))
controlador = 1
jogos = []
lista = []
while controlador <= quantidade:
cont = 1
lista = []
while True:
numero = randint(1,61)
if numero not in lista:
lista.append(numero)
cont += 1
if cont > 6:
break
lista.sort()
jogos.append(lista[:])
controlador += 1
for c in range(len(jogos)):
print "jogo {}: {}".format(c+1, jogos[c])
|
f9ec6d7be34c9e81ffe1090e9a4f2f4fcf9e369a | phuongsover1/nenvbvagamma | /src/Spimi/compressed_spimi_vbencode.py | 14,403 | 3.515625 | 4 | """
This script index documents by using SPIMI indexing technique
"""
from nltk.corpus import stopwords
from collections import defaultdict
from src.Compress.VariableByteCode import VariableByteCode
from bitstring import BitArray
from os import listdir
import sys
import os
import string
import re
def rename_file(path, old, new):
"""
Rename a file
"""
for f in os.listdir(path):
os.rename(os.path.join(path, f),
os.path.join(path, f.replace(old, new)))
def getSortedBlockNames():
"""
Find block names from a dir and sort them based on block id
:return: Sorted block names and number of blocks
"""
def list_files(directory, extension):
return (f for f in listdir(directory) if f.endswith('.' + extension))
blockNames = list_files('Blocks/', 'txt') # List of blocks
blockNames_pos = [(int(filter(str.isdigit, blockName)), blockName) for blockName in blockNames] # (Block id, names)
sorted_blockID_Names = sorted(blockNames_pos, key=lambda x: x[0]) # Sort based on block id
blockNames = [name for id, name in sorted_blockID_Names] # Grab only block name from (block id, name) tuple
n_blocks = len(blockNames) # Number of blocks
return blockNames, n_blocks
def preprocessDoc(term):
"""
Stopword elimination, converting lower case, stemming, punctuation removal are done in this step
:param doc: string object (term)
:return: preprocessed string object
"""
# Remove numbers and stopwords
if term in stopwords.words('english'):
return ''
escape_set = set(string.punctuation) # Unwanted chars set
# Remove the chars in the escape_set if it exists from the beginning and end of the term
try:
if term[0] in escape_set:
term = ''.join(term[1:])
if term[len(term) - 1] in escape_set:
term = ''.join(term[:-1])
# If there is a numeric value in term
if not term.isalpha():
return ''
# Remove stopwords
# if term not in stopwords.words('english'):
# # Stem terms
# ps = PorterStemmer()
# term = ps.stem(term)
# return term.lower() # Convert to lower case and return
# else:
# return '' # Eliminate stop word
return term.lower()
except IndexError:
return ''
def safe_readline(_file, curr_line):
"""
At some lines x0a byte causes new lines and these bytes cause new line. Thus, the remaining posting lists passes
to the line below. This method checks whether this is the case.
Ex: x19\x20\xAB\x0a\x0b is represented as
x19\x20\xAB\
\x0b
:param curr_line: string object defining current line
:return:
"""
def isCurrentSafe(txt):
"""
This method checks whether the current line in a block is properly formatted. Safe means properly formatted.
E.g pir,{i}\n is properly formatted because a string is followed by ,{ and after { there are bytes. Finally at
the end there is }\n chars.
:param txt: String object
:return: True: properly formatted
False: otherwise
"""
regex = '[a-zA-Z]+,{.*}\\n'
if re.match(regex, txt) or txt == '':
return True
else:
return False
def isNextSafe(txt):
"""
Check whether next line is safe to read.
if it starts with char followed by ,{ then it is accepted to be safe
E.g
1-personally,{u}
2-pm,{jk
3-cds
4-}
In the example above the first line is considered to be current line and it is safe. The next line starts with
pm,{ so it is also safe. For 2nd line this method will return true
:param txt: string
:return: True: properly formatted
False: otherwise
"""
regex = '[a-zA-Z]+,{.*'
if re.match(regex, txt) or txt == '':
return True
else:
return False
# Check if the current line is safe to proceed
next_line = _file.readline()
if curr_line == '' and next_line == '':
return '', '', ''
if isCurrentSafe(curr_line) and isNextSafe(next_line):
_curr_dict, _curr_posting = curr_line.split(',', 1)
return _curr_dict, _curr_posting[1:-2], next_line
else:
"""
There are some cases as the example below. Even if the first line is safe the second line is not because
the posting list is 'csd}\nc' so we also need to check the next line even if the current line is safe.
E.g: personal,{csd}\n
c}
"""
while True:
if isNextSafe(next_line):
_curr_dict, _curr_posting = curr_line.split(',', 1)
return _curr_dict, _curr_posting[1:-2], next_line
else:
curr_line += next_line
next_line = _file.readline()
def invert_block(docs, path):
"""
The method creates a dictionary object of a fixed sized and try to add as much document as the capacity limit.
The key of dict include the terms and the posting list have the document ids
:param docs: List of string objects include multiple document
:return: dictionary object
"""
block_index = 0
# Create dict block
dictBlock = defaultdict(str)
vb_code = VariableByteCode()
# Iterate over docs
for doc_name in docs:
docID = int(doc_name.split('.')[0])
with open(path + doc_name, 'r') as doc:
doc = doc.read()
doc = string.replace(doc, '\n', ' ')
# TOKENIZE
for term in doc.split(' '):
term = preprocessDoc(term)
# Check whether term has a char (if it is a stop word than term == '')
if term != '':
# If term does not exist at keys before simply append doc ID
if dictBlock[term] == '':
vb_code_encoded = vb_code.VB_encode_number(docID)
dictBlock[term] += vb_code_encoded # Append encoded str
# Else append the difference between last doc ID and current doc ID
else:
lastDocID = sum(vb_code.VB_decode(dictBlock[term]))
currentDocID = docID
diff = currentDocID - lastDocID
gamma_code_diff = vb_code.VB_encode_number(diff) # Compress with gamma code
dictBlock[term] += gamma_code_diff # Append encoded str
if sys.getsizeof(dictBlock) > blockCapacityLimit:
# Append dictBlock object to blocks list object
saveBlockDict2Disc(block_index, dictBlock, 'wb', True)
# Empty dict block
dictBlock = defaultdict(str)
block_index += 1
# Save dictBlock object to disc
saveBlockDict2Disc(block_index, dictBlock, 'wb', True)
def saveBlockDict2Disc(blockIndex, block, format, isDict):
"""
Save dictBlock object to disc
:param blockIndex: name of block
:param block: list or dict object that has collection of dictionaries
:param format: string object that indicates the format of opening a file ('wb', 'r', 'w', 'a' etc)
:return:
"""
# Delete '' key from dict
if isDict:
try:
del block['']
except KeyError:
pass
# Sort dict block
sortedDictBlock = list(sorted(block.items(), key=lambda t: t[0]))
# Save dict block to disc
fileName = 'Blocks/%s.txt' % blockIndex
with open(fileName, format) as out:
# If the block is dict object
if isDict:
for key, values in sortedDictBlock:
try:
out.write(str(key) + ',{' + values + '}\n') # Write bytes into file
except UnicodeEncodeError:
print(key)
else: # If the block is list object
for values in block:
out.write(values)
def merge2CompressedPostingLists(posting1, posting2):
"""
This method merge two compressed posting lists
:param posting1: List Object
:param posting2: List Object
:return: merged posting list
"""
vb_code = VariableByteCode()
decoded_posting1 = VariableByteCode.VB_decode(BitArray('0x' + posting1).tobytes())
decoded_posting2 = VariableByteCode.VB_decode(BitArray('0x' + posting2).tobytes())
first_element_posting2 = decoded_posting2[0]
sum_posting1 = sum(decoded_posting1)
mergedPosting = decoded_posting1 + [(first_element_posting2 - sum_posting1)] + decoded_posting2[1:]
vb_encoded_merged_posting = vb_code.VB_encode(mergedPosting)
return vb_encoded_merged_posting
def merging2Blocks(block1, block2, blockCapacityLimit=1000):
path = 'Blocks/'
# Define files
block1_file = open(path + block1, 'rb')
block2_file = open(path + block2, 'rb')
isComplete = False
# Read first line of blocks
current_line_1 = block1_file.readline()
current_line_2 = block2_file.readline()
dict_key_1, posting_1, next_line_1 = safe_readline(block1_file, current_line_1)
dict_key_2, posting_2, next_line_2 = safe_readline(block2_file, current_line_2)
current_line_1 = next_line_1
current_line_2 = next_line_2
# Define a Default Dict to store merged postings in memory
cacheList = list()
while not isComplete:
# CASE 1: if keys are same
if dict_key_1 == dict_key_2:
block1_posting = posting_1.encode('hex')
block2_posting = posting_2.encode('hex')
merged_posting = merge2CompressedPostingLists(block1_posting, block2_posting)
cacheList.append(dict_key_1 + ',{' + merged_posting + '}\n')
# Skip to Next lines
dict_key_1, posting_1, next_line_1 = safe_readline(block1_file, current_line_1)
dict_key_2, posting_2, next_line_2 = safe_readline(block2_file, current_line_2)
current_line_1 = next_line_1
current_line_2 = next_line_2
# CASE 2: if first block keys is greater than second key
elif dict_key_1 > dict_key_2:
cacheList.append(dict_key_2 + ',{' + posting_2 + '}\n')
dict_key_2, posting_2, next_line_2 = safe_readline(block2_file, current_line_2)
current_line_2 = next_line_2
# CASE 3: if second block keys is greater than firs key
elif dict_key_1 < dict_key_2:
cacheList.append(dict_key_1 + ',{' + posting_1 + '}\n')
dict_key_1, posting_1, next_line_1 = safe_readline(block1_file, current_line_1)
current_line_1 = next_line_1
# If first block is red completely append all the remaining rows from second block
if dict_key_1 == '' and dict_key_2 != '':
while not isComplete:
cacheList.append(dict_key_2 + ',{' + posting_2 + '}\n')
dict_key_2, posting_2, next_line_2 = safe_readline(block2_file, current_line_2)
current_line_2 = next_line_2
if dict_key_2 == '':
isComplete = True
# If second block is red completely append all the remaining rows from first block
if dict_key_1 != '' and dict_key_2 == '':
while not isComplete:
cacheList.append(dict_key_1 + ',{' + posting_1 + '}\n')
dict_key_1, posting_1, next_line_1 = safe_readline(block1_file, current_line_1)
current_line_1 = next_line_1
if dict_key_1 == '':
isComplete = True
if dict_key_1 == '' and dict_key_2 == '':
isComplete = True
# If memory is used greater than a value write dict to disc and flush the memory
if sys.getsizeof(cacheList) > blockCapacityLimit:
block_index = '_' + block1
# Append dictBlock object to blocks list object
saveBlockDict2Disc(block_index, cacheList, 'ab', False)
# Empty list block / Flush Memory
cacheList = list()
block_index = '_' + block1
# Append dictBlock object to blocks list object
saveBlockDict2Disc(block_index, cacheList, 'ab', False)
block1_file.close()
block2_file.close()
def deleteMergedBlocks(block1, block2):
"""
Delete merged blocks from disc
:param block1:
:param block2:
:return:
"""
path = 'Blocks/'
os.remove(path + block1)
os.remove(path + block2)
def mergeAllBlocks():
blockNames, n_blocks = getSortedBlockNames()
# Merge blocks until there are one big merged block left
while n_blocks > 1:
blockNames, n_blocks = getSortedBlockNames()
if n_blocks % 2 == 0: # If number of blocks are even
block_couples = [(i, i + 1) for i in range(0, n_blocks, 2)]
else:
block_couples = [(i, i + 1) for i in range(0, n_blocks - 1, 2)]
for couple in block_couples:
block1 = blockNames[couple[0]]
block2 = blockNames[couple[1]]
merging2Blocks(block1, block2) # Merge two blocks
deleteMergedBlocks(block1, block2) # Delete blocks after merging
blockNames, n_blocks = getSortedBlockNames()
merged_index_file_name = blockNames[0]
rename_file('Blocks/', merged_index_file_name, 'vb_index.txt')
def index_docs(docs, buffer, path):
"""
Main method that index the documents with SPIMI algorithm
:param docs: Documents include doc ids and body text
:param buffer_size: Maximum size of each block for SPIMI algorithm
:param path: path of documents
"""
print('--------------------------------------------')
print('Indexing has been started..')
global blockCapacityLimit
blockCapacityLimit = buffer
invert_block(docs, path)
print('All documents are inverted!')
mergeAllBlocks()
print('All inverted blocks are merged!')
print('--------------------------------------------')
# with open('Blocks/vb_code_index.txt', 'rb') as out:
# while True:
# key, value = safe_readline(out)
# value = value.encode('hex')
# decompressed_value = VariableByteCode.VB_decode(BitArray('0x' + value).tobytes())
# print(key, decompressed_value) |
35fb92389ed08510ccf2cd0e495f147220be50c5 | bssrdf/pyleet | /M/MinimumDeletionstoMakeArrayDivisible.py | 1,549 | 3.796875 | 4 | '''
-Hard-
*Sorting*
*GCD*
You are given two positive integer arrays nums and numsDivide. You can delete any number of elements from nums.
Return the minimum number of deletions such that the smallest element in nums divides all the elements of numsDivide. If this is not possible, return -1.
Note that an integer x divides y if y % x == 0.
Example 1:
Input: nums = [2,3,2,4,3], numsDivide = [9,6,9,3,15]
Output: 2
Explanation:
The smallest element in [2,3,2,4,3] is 2, which does not divide all the elements of numsDivide.
We use 2 deletions to delete the elements in nums that are equal to 2 which makes nums = [3,4,3].
The smallest element in [3,4,3] is 3, which divides all the elements of numsDivide.
It can be shown that 2 is the minimum number of deletions needed.
Example 2:
Input: nums = [4,3,6], numsDivide = [8,2,6,10]
Output: -1
Explanation:
We want the smallest element in nums to divide all the elements of numsDivide.
There is no way to delete elements from nums to allow this.
Constraints:
1 <= nums.length, numsDivide.length <= 105
1 <= nums[i], numsDivide[i] <= 109
'''
from typing import List
from math import gcd
from functools import reduce
class Solution:
def minOperations(self, nums: List[int], numsDivide: List[int]) -> int:
g = reduce(gcd, numsDivide)
for i,a in enumerate(sorted(nums)):
if g % a == 0: return i
if a > g: break
return -1
if __name__ == "__main__":
print(Solution().minOperations(nums = [2,3,2,4,3], numsDivide = [9,6,9,3,15]))
|
3c87c343db6cacabc092850d02948547d7d0bc73 | DocentSzachista/messenger-stats | /src/file_parser.py | 1,666 | 3.71875 | 4 | import json
#otworz plik JSON aby potem uzyskac slownik zawierajacy informacje o autorach i caly kontent wiadomosci
class FileParser:
"""class to process messenger JSON files"""
def __init__(self, filename) -> None:
self.jsonData=self.__parse_json(filename)
def __parse_json(self, filename)->dict:
"""read whole content of a JSON file
function saves the content of JSON file to a dictionary of lists of dictionaries.
files contens are decoded from latin and encoded to UTF-8 during saving into a data structure
Parameters
----------
filename: str
string containing information the name and location of a file to read
Returns
-------
dict that contains the data about conversation
"""
with open(filename, 'r', encoding='raw_unicode_escape') as file:
list_of_dictonaries= json.loads(file.read().encode('raw_unicode_escape').decode())
return list_of_dictonaries
def retrieve_authors(self)->list:
""" getter function to return a list of a conversation's participants
Returns
-------
list of conversation's participants
"""
listing = self.jsonData.get("participants")
listing = [element.get("name") for element in listing ]
return listing
def retrieve_messages(self)->list:
"""retrieve a list of dicts containing details about sent messages
Returns
-------
list of conversation's details
"""
return self.jsonData.get("messages")
|
94e2377769d2f1051b78358df852784f0e12d553 | mitchell-johnstone/PythonWork | /PE/P074.py | 1,548 | 3.8125 | 4 |
# The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145:
# 1! + 4! + 5! = 1 + 24 + 120 = 145
# Perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169; it turns out that there are only three such loops that exist:
# 169 ---> 363601 ---> 1454 ---> 169
# 871 ---> 45361 ---> 871
# 872 ---> 45362 ---> 872
# It is not difficult to prove that EVERY starting number will eventually get stuck in a loop. For example,
# 69 ---> 363600 ---> 1454 ---> 169 ---> 363601 (---> 1454)
# 78 ---> 45360 ---> 871 ---> 45361 (---> 871)
# 540 --> 145 (--> 145)
# Starting with 69 produces a chain of five non-repeating terms, but the longest non-repeating chain with a starting number below one million is sixty terms.
# How many chains, with a starting number below one million, contain exactly sixty non-repeating terms?
def sum_fact_digits(n, f):
return sum(f[int(i)] for i in list(str(n)))
def main():
facts = [1,1,2,6,24,120,720,5040,40320,362880]
count = 0
for start in range(3,10**6):
chain = [start]
curNum = sum_fact_digits(start, facts)
good = True
while curNum not in chain and good:
chain += [curNum]
curNum = sum_fact_digits(curNum, facts)
if len(chain)>60:
good = False
if len(chain) == 60 and good:
count+=1
print(count)
if __name__ == "__main__":
main()
|
10cca1331c624f8f0699d1494bf034c482ba921d | harshitpoddar09/InterviewBit-Solutions | /Programming/Tree Data Structure/Simple Tree Ops/Balanced Binary Tree.py | 637 | 3.84375 | 4 | # Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param A : root node of tree
# @return an integer
def isBalanced(self, A):
def height(root):
if not root:
return 0
return max(height(root.left),height(root.right))+1
if not A:
return 1
lh=height(A.left)
rh=height(A.right)
if abs(lh-rh)<=1 and self.isBalanced(A.right) and self.isBalanced(A.left):
return 1
return 0 |
5f0b428d7047defd81f2e7b993ae87fa32bb8577 | IanCBrown/practice_questions | /avg_of_levels_in_binary_tree.py | 1,074 | 3.8125 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
levels = height(root)
sol = level_order_helper(root, levels)
return sol
def level_order_helper(root, levels):
avgs = []
for i in range(1,levels + 1):
nodes = []
l = level_order(root, i, nodes)
avgs.append(sum(l)/len(l))
return avgs
def level_order(root, level,nodes):
if root is None:
return
if level == 1:
nodes.append(root.val)
if level > 1:
level_order(root.left, level - 1, nodes)
level_order(root.right, level - 1, nodes)
return nodes
def height(root):
if root is None:
return 0
left_max = height(root.left)
right_max = height(root.right)
return max(left_max, right_max) + 1
|
b6df4bc02d51444363bebce2bf1619fe051ed733 | uwasejeannine/showAndTell | /ShowAndTell.py | 3,124 | 3.609375 | 4 | Python 3.8.6 (default, Jan 27 2021, 15:42:20)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license()" for more information.
>>> #python Valiables(INt,Float and Boolean)
>>> studentNumber=2 # variable number is 2
>>> print(studentNumber)
2
>>> #Oparetors(Arthemetic)
>>> x=2
>>> y=3
>>> y+x
5
>>> # Assignment Oparetors
>>> x+=2 # adding 2 two the value of x
>>> print(x)
4
>>> y-=1
>>> print(y)
2
>>> # relational oparetors
>>> # relational oparetors( relatang two value using different sign)
>>> x<b
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
x<b
NameError: name 'b' is not defined
>>> x<y
False
>>> x==y # it's returs boolean(True of False)
False
>>> # Datatype (int, float,boolean,complex, string,list...)
>>> c=2+3j # complex method return complex number when Imaginary and real nbr has provided
>>> print(c)
(2+3j)
>>> #String method are build in fuction to chance appearence of a string output
>>> firstName="mukagasaraba"
>>> secondName="rachel"
>>> country="rwanda"
>>> district="rusizi"
>>> lendMoney=200,000
>>> payedBack=50,000
>>> currency="rwf"
SyntaxError: unexpected indent
>>> currency="rwf"
>>> print(f"Dear {firstName.capitalize()} {secondName.capitalize()} who is {2021-1978} years old from {country.upper()} in {district.title()}.We are extrimly excited to give you your remining {200000-5000} {currency.upper()}.")
Dear Mukagasaraba Rachel who is 43 years old from RWANDA in Rusizi.We are extrimly excited to give you your remining 195000 RWF.
>>> # datastrucure using a list(List can contain anything)
>>> foodList=["Bread","Cakes","Meat","Rolls"]
>>> foodList[2] # always index start from zero
'Meat'
>>> foodList[0:2]
['Bread', 'Cakes']
>>> foodList[-3:-1]
['Cakes', 'Meat']
>>> foodList.append("Marshmallow") # add value to the bottom of the list
>>> foodList.insert(1,"beans") # insert value to between index specified
SyntaxError: unexpected indent
>>> foodList.insert(1,"beans") # insert value to between index specified
>>> foodList.extend(["sweet potatoes","millet "]) # add alist to the bottom of list
>>> foodList.remove("Meat")# removes last item in the list
>>> foodList.sort() # sort items in accending manner
>>> foodList.reverse() #reverse item last became first
>>> print(foodList)
['sweet potatoes', 'millet ', 'beans', 'Rolls', 'Marshmallow', 'Cakes', 'Bread']
>>> foodList.clrean() # delet items in the list
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
foodList.clrean() # delet items in the list
AttributeError: 'list' object has no attribute 'clrean'
>>> foodList.clear() # delet items in the list
>>> print(foodList)
[]
>>> list=[1, 3, 5, 7, 9]
>>> for i in list:
a=i*2
print(a)
2
6
10
14
18
>>> # getting length of list
>>> length = len(list)
>>> print(lenght)
Traceback (most recent call last):
File "<pyshell#64>", line 1, in <module>
print(lenght)
NameError: name 'lenght' is not defined
>>> print(length)
5
>>> # make a list from a nother list
>>> a=[[1,2,3],[4,5,6],[7,8,9]]
>>> b=[]
>>> b=[e for sublist in a for e in sublist]
>>> print(b)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
|
87abf83bae46e78c695bede4c830554952898c1b | S-Downes/CI-Challenges | /Stream-3/01_python_challenges/solutions/challenge_3.py | 915 | 3.53125 | 4 | # Function(s)
def test_are_equal(actual, expected):
assert expected == actual, "Expected {0}, got {1}".format(expected, actual)
def test_not_equal(a, b):
assert a != b, "Did not expect {0}, but got {1}".format(a, b)
def test_is_in(collection, item):
assert item in collection, "{0} does not contain {1}".format(collection, item)
def test_between(val, lower_lim, upper_lim):
assert val > lower_lim and val < upper_lim, "{0} is between the range {1} and {2}".format(val, lower_lim, upper_lim)
## Here are some tests that might suffice for testing our new function.
test_set = ["Hello", 1, 5, 13, "", "Moon", "Sun", "Star"]
test_are_equal(True, True) # PASS
test_not_equal(2, 2) # FAIL
test_not_equal(7, 7) # FAIL
test_is_in(test_set, "World") # FAIL
test_is_in(test_set, [2, 3]) # FAIL
test_between(2, 3, 100) # FAIL
test_between(54, 3, 100) # PASS
print("All the tests passed") |
d21c4ada70f67aab45dc2ae3278c5289f2a5dda8 | ngalin/weather | /get_weather.py | 1,442 | 3.546875 | 4 | # make some api calls - and log weather hourly values in Sydney, AU
# on the hour make call to get current temperature in Sydney, and
# make call and record the 5 day 3hr forecast for Sydney.
# after get 24 x 5 x (24/3) values,
import requests
import schedule
import json
import datetime
import api_secret
CITY = 'Sydney'
COUNTRY = 'au'
QUERY = {"q": "Sydney,au", "APPID": api_secret.APPID}
HEADERS = {
'Accept': "*/*",
'Host': "api.openweathermap.org",
'Connection': "keep-alive",
'cache-control': "no-cache"
}
URL_NOW_WEATHER = "http://api.openweathermap.org/data/2.5/weather"
URL_FORECAST = "http://api.openweathermap.org/data/2.5/forecast"
CURRENT = open('data/current_weather.json', 'w')
FORECAST = open('data/forecast_weather.json', 'w')
def get_weather():
json.dump(obj=get_current_weather().json(), fp=CURRENT, sort_keys=True)
CURRENT.write('\n')
json.dump(obj=get_forecast_weather().json(), fp=FORECAST, sort_keys=True)
FORECAST.write('\n')
print('ran', datetime.datetime.now())
return
def get_current_weather():
return requests.request("GET", url=URL_NOW_WEATHER, headers=HEADERS, params=QUERY)
def get_forecast_weather():
return requests.request("GET", url=URL_FORECAST, headers=HEADERS, params=QUERY)
def main():
print("Hello World!")
schedule.every().hour.do(get_weather)
while True:
schedule.run_pending()
CURRENT.close()
FORECAST.close()
if __name__ == "__main__":
main()
|
6a12a390f4c68aebc4a6b1163085e628037138e4 | dekopossas/trybe-exercicios | /exercises/37_1/aula.py | 554 | 3.859375 | 4 | numeros = [1, 2, 2, 6, 6, 6, 6, 7, 10]
print(len(numeros))
def numero_que_aparece_um_quarto(numeros):
contador = dict()
for numero in numeros:
contador[numero] = contador.get(numero, 0) + 1
print(contador)
numero_mais_frequente = None
maior_contagem = 0
for numero, contagem in contador.items():
if contagem > maior_contagem:
numero_mais_frequente = numero
maior_contagem = contagem
return numero_mais_frequente
resultado = numero_que_aparece_um_quarto(numeros)
print(resultado) |
765aad363331dbf66ab32af8ac2b68a3ecccd809 | aravindbhaskar41/codejam | /invariant/plaban_nayak/invariant_main.py | 945 | 3.53125 | 4 | from invariant_algorithm import dynamic_prog , lookup_sorted
from invariant_print_table import print_table
def main_method(number_list):
#checking if all numbers are 4 digit numbers
if max(number_list) > 9999 or min(number_list) < 1000:
raise ValueError, "all numbers are not 4 digit numbers"
#dictionary to hold (Iterations:Total count of numbers)
iter_dict = {}
for number in number_list:
if number % 1111 != 0 and number!=6174:
no_of_iter = dynamic_prog(number)
# putting it into a dictionary
iter_dict[no_of_iter] = iter_dict.get(no_of_iter,0) + 1
# when the number is 6174 ,the no of iterations is zero
iter_dict[0] = 1
return iter_dict
if __name__ == "__main__":
try:
iter_dict = main_method(range(1000,9999))
print_table(iter_dict)
except ValueError ,e:
print e
|
5180716bff9ac2d84e4453ecbd2121123a8c1610 | tsartsaris/TSP | /tsp_distance.py | 1,445 | 3.984375 | 4 | # ! /usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Tsartsaris Sotiris"
__copyright__ = "Copyright 2014, The TSP Project"
__credits__ = ["Tsartsaris Sotiris"]
__license__ = "APACHE 2.0"
__version__ = "1.0.1"
__maintainer__ = "Tsartsaris Sotiris"
__email__ = "info@tsartsaris.gr"
__status__ = "Development"
"""
Provided a dictionary with city coordinates and a list
of the current tour it calculates the entire tour euclidean_distance
"""
import math
def euclidean_distance(p0, p1):
"""
Calculates the Euclidean distance between 2 points (x1,y1) and (x2,y2)
"""
xdiff = float(p1[0]) - float(p0[0])
ydiff = float(p1[1]) - float(p0[1])
return int(math.sqrt((xdiff * xdiff + ydiff * ydiff) + 0.5))
class TSPDistance:
def __init__(self, tourlist, citydict):
self.cities_best = []
self.tourlist = tourlist
self.citydict = citydict
for i in self.tourlist:
self.cities_best.append(self.citydict.get(i))
self.distance_cost = self.total_distance(self.cities_best)
def total_distance(self, cities_best):
"""
Iterates a list of coordinate tuples and calculates the Euclidean
distance between 2 points found sequential in the list representing
the tour. Then sums everything up and returns the result
"""
cities_best = self.cities_best
return sum(euclidean_distance(v, w) for v, w in zip(cities_best[:-1], cities_best[1:])) |
3ce5eaabbb7eab6f33b5528445f62f17adf58efd | rwakulszowa/Skater_pygame | /skater/image.py | 2,240 | 3.5 | 4 | import random
import numpy as np
import pygame
from .rendering.point import Point
from .rendering import shape
class Image:
"""
A wrapper around a pygame image class. It provides a common interface for
drawable elements.
The code outside of this class should not use any other image-related APIs.
`self.shape` is a pygame.rect instance for now.
Will be replaced by another class once non-rectangular shapes are supported
"""
def __init__(self, raw_image, shape):
self.raw_image = raw_image
self.shape = shape
@classmethod
def load(cls, path):
"""
Loads and prepares an image from a local file
"""
raw_image = pygame.image.load(path)
raw_image.convert_alpha()
pyrect = raw_image.get_rect()
rectangle = shape.rectangle(
Point(pyrect.left, pyrect.top),
Point(pyrect.right, pyrect.bottom)
)
return Image(
raw_image,
rectangle)
@classmethod
def create(cls, size, color=None):
"""
Creates a new rectangular surface
"""
# If no color was specified, just create a random one
color = color or cls.random_color()
left, bottom = size
rectangle = shape.rectangle(
Point(0, 0),
Point(left, bottom)
)
# Build the shape mask
mask = rectangle.build_surface_mask()
# Flip the mask - we'll use a flipped coordinate system for pixel access
mask = mask.transpose()
width = mask.shape[0]
height = mask.shape[1]
# Create a surface with a per-pixel alpha value
surface = pygame.Surface(
(width, height),
flags=pygame.SRCALPHA)
surface.fill(color)
# Set pixels outside of the figure as fully transparent
alpha = pygame.surfarray.pixels_alpha(surface)
alpha[:] = mask * 255
return Image(surface, rectangle)
@staticmethod
def random_color():
# colors are integers of value <0, 255>
lo = 0
hi = 255
return [
random.randint(lo, hi)
for _ in range(3)
] |
43792737c78effd38b7513744d84dee366bc0e15 | MeParas324/Python-programs | /pythontuts/tut16.py | 868 | 3.765625 | 4 | # list1=["Paras","Elsa","Murti","Ramdev"]
# for item in list1:
# print(item)
# list1=[["Paras",2],["Elsa",4],["Murti",8],["Ramdev",16]]
# for item in list1:
# print(item)
# list1=[["Paras",2],["Elsa",4],["Murti",8],["Ramdev",16]]
# for item,lollypop in list1:
# print(item,lollypop)
# list1=[["Paras",2],["Elsa",4],["Murti",8],["Ramdev",16]]
# for item,lollypop in list1:
# print(item,"and lolly is",lollypop)
# list1=[["Paras",2],["Elsa",4],["Murti",8],["Ramdev",16]]
# dict1=dict(list1)
# print(dict1)
# for item,lollypop in list1:
# print(item,"and lolly is",lollypop)
# list1=[["Paras",2],["Elsa",4],["Murti",8],["Ramdev",16]]
# dict1=dict(list1)
# for item,lollypop in dict1.items():
# print(item,"and lolly is",lollypop)
list1=[["Paras",2],["Elsa",4],["Murti",8],["Ramdev",16]]
dict1=dict(list1)
for item in dict1:
print(item)
|
10b4970e6d20d3e513ea2c266fc604bcf69a49bc | Funsom/leetcodes | /946.验证栈序列.py | 1,055 | 3.609375 | 4 | #
# @lc app=leetcode.cn id=946 lang=python3
#
# [946] 验证栈序列
#
# @lc code=start
class Solution:
def validateStackSequences(self, pushed, popped) -> bool:
#if pushed == popped: return True
# 至多有一个逆序
dic = {}
n = len(popped)
nin = len(pushed)
if n != nin: return False
for ind,ele in enumerate(pushed):
dic[ele] = ind
if popped[0] not in dic: return False
count = 0
for i in range(1,n):
if popped[i] not in dic: return False
if dic[popped[i]] - dic[popped[i-1]] > 1:
return False
elif dic[popped[i]] - dic[popped[i-1]] == 1:
count += 1
if count > 1:
return False
# if count == 1 and pushed[:2] == popped[-2:]:
# return False
return True
if __name__ == "__main__":
s = Solution()
pushed = [2,1,0]
poped = [1,2,0]
print(s.validateStackSequences(pushed,poped))
# @lc code=end
|
f166ce761de68cb484969af0477ec82a057291be | AkankshaKaple/Python_Data_Structures | /removeFirstOccurance.py | 688 | 4.0625 | 4 | #This program deletes the first occurrence of a perticular
# element in an array
from array import *
UserArray = array('i' , []) #Array given by user
size = int(input("Enter size of array : "))
print("Enter elements in array : ")
for i in range(size) :
item = int(input())
UserArray.append(item)
element =int(input("Enter the element whose first occurrence you want remove : "))
for i in range(size) :
if element == UserArray[i] :
UserArray.remove(UserArray[i]) #Remove the first occurrence of an element
break # Break to avoid deleting other occurrences
elif element != UserArray[i] :
print("Element is not present in array")
print(UserArray) |
4672b0fccfa4167d81d99c110a7a3352a7c9aad8 | code4tots/c4 | /c4/parser.py | 12,843 | 3.625 | 4 | """parser.py
This module has two components:
1. the Parse function, and
2. the Parser class.
Parse is a convenience function around Parser.
For most intents and purposes, I don't think you will need to use the Parser class directly.
The Parser class is enormous, but is divided into six logical parts.
-- context
-- lexical analysis
-- module parsing
-- expression parsing
-- statement parsing
-- type expression parsing
As of this writing, the Parser class is ~350 lines long.
-- About ~150 lines of it is expression parsing.
-- About ~100 lines of it is lexical analysis.
"""
import collections
from . import ast
CHAR_STARTER = ("r'", "'")
STRING_STARTER = ('r"', '"')
# To see that the symbols listed here match with the ones used during the parse, the regex
# ;(?!(?:f|i|s|v|t|sizeof)\b)\w+
# may be useful.
SYMBOLS = tuple(reversed(sorted([
# special symbols
';f', ';i', ';s', ';t', ';v',
';sizeof', # For distinguishing sizeof(type) vs sizeof(expression).
# operators
'++', '--',
'*', '/', '%', '+', '-',
'<<', '>>',
'<', '<=', '>', '>=',
'==', '!=',
'&', '^', '|', '&&', '||',
'=', '+=', '-=', '*=', '/=', '%=',
'<<=', '>>=', '&=', '^=', '|=',
# delimiters
'[', ']', '(', ')', '{', '}',
';', ',', '.', '->', '~', '?', ':', '!',
])))
ID_CHARS = frozenset('abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'0123456789_')
KEYWORDS = frozenset([
'auto',
'break',
'case', 'const', 'continue',
'default', 'do',
'else', 'enum', 'extern',
'for',
'goto',
'if',
'register', 'return',
'signed', 'sizeof', 'static', 'struct', 'switch',
'typedef',
'union', 'unsigned',
'volatile',
'while'
])
Token = collections.namedtuple('Token', 'type value')
def Parse(string, source):
return Parser(string, source).Module()
class Parser(object):
## context
def __init__(self, string, source):
self.s = string
self.src = source
self.j = 0
self.i = 0
self.peek = self.NextTok()
@property
def done(self):
return self.j >= len(self.s)
@property
def char(self):
return self.s[self.i] if self.i < len(self.s) else ''
@property
def lineno(self):
return self.s.count('\n', 0, self.j) + 1
@property
def colno(self):
return self.j - self.s.rfind('\n', 0, self.j)
@property
def line(self):
start = self.s.rfind('\n', 0, self.j) + 1
end = self.s.find('\n', self.j)
end = len(self.s) if end == -1 else end
return self.s[start:end]
@property
def location_message(self):
return 'From %s, on line %s\n%s\n%s*\n' % (
self.src, self.lineno,
self.line,
' ' * (self.colno-1))
def Error(self, message):
return SyntaxError(self.location_message + message + '\n')
## lexical analysis
def SkipSpaces(self):
while not self.done and self.char.isspace() or self.char == '#':
if self.char == '#':
while not self.done and self.char != '\n':
self.i += 1
else:
self.i += 1
self.j = self.i
def NextTok(self):
self.SkipSpaces()
self.j = self.i
if self.done:
return Token('eof', 'eof')
# String literal
if self.s.startswith(STRING_STARTER + CHAR_STARTER, self.i):
type_ = 'str' if self.s.startswith(STRING_STARTER, self.i) else 'char'
raw = False
if self.char == 'r':
raw = True
self.i += 1
quote = self.s[self.i:self.i+3] if self.s.startswith(('"""', "'''"), self.i) else self.char
self.i += len(quote)
while not self.s.startswith(quote, self.i):
if self.i >= len(self.s):
raise self.Error("Finish your quotes!")
self.i += 2 if raw and self.char == '\\' else 1
self.i += len(quote)
return Token(type_, eval(self.s[self.j:self.i]))
# Symbol
symbol_found = False
for symbol in SYMBOLS:
if self.s.startswith(symbol, self.i):
self.i += len(symbol)
symbol_found = True
return Token(symbol, None)
# int/float
if self.char.isdigit() or (self.char == '.' and self.s[self.i+1:self.i+2].isdigit()):
self.j = self.i
while self.i < len(self.s) and self.char.isdigit():
self.i += 1
if self.s.startswith('.', self.i):
self.i += 1
while self.i < len(self.s) and self.char.isdigit():
self.i += 1
return Token('float', float(self.s[self.j:self.i]))
else:
return Token('int', int(self.s[self.j:self.i]))
# Identifier
if self.char in ID_CHARS:
while self.i < len(self.s) and self.char in ID_CHARS:
self.i += 1
val = self.s[self.j:self.i]
type_ = val if val in KEYWORDS else 'id'
return Token(type_, val if type_ == 'id' else None)
# Unrecognized token.
while self.i < len(self.s) and not self.char.isspace():
self.i += 1
raise self.Error("I don't know what this token is.")
def GetTok(self):
tok = self.peek
self.peek = self.NextTok()
return tok
def At(self, *toktype):
return self.peek.type in toktype
def Consume(self, *toktype):
if self.At(*toktype):
return self.GetTok()
def Expect(self, *toktype):
if not self.At(*toktype):
raise self.Error('Expected %s but found %s' % (toktype, self.peek.type))
return self.GetTok()
## module parsing
def Module(self):
stmts = []
while not self.done:
stmts.append(self.Statement())
return ast.Module(tuple(stmts))
## expression parsing
def Expression(self):
# c4 expressions are similar to C grammar, but is simplified a bit.
return self.Expression14()
def Expression00(self):
if self.At('id'):
return ast.Id(self.Expect('id').value)
elif self.At('int'):
return ast.Int(self.Expect('int').value)
elif self.At('float'):
return ast.Float(self.Expect('float').value)
elif self.At('str'):
return ast.Str(self.Expect('str').value)
elif self.At('char'):
return ast.Char(self.Expect('char').value)
elif self.Consume('('):
expr = self.Expression()
self.Expect(')')
return ast.ParentheticalExpression(expr)
else:
raise self.Error('Expected expression')
def Expression01(self):
expr = self.Expression00()
while True:
if self.Consume('('):
args = []
while not self.Consume(')'):
args.append(self.Expression())
self.Consume(',')
expr = ast.FunctionCall(expr, tuple(args))
elif self.Consume('['):
index = self.Expression()
self.Expect(']')
expr = ast.Subscript(expr, index)
elif self.At('++', '--'):
expr = ast.PostfixOperation(expr, self.GetTok().type)
elif self.Consume('.'):
expr = ast.MemberAccess(expr, self.Expect('id').value)
elif self.Consume('->'):
expr = ast.MemberAccessThroughPoniter(expr, self.Expect('id').value)
else:
break
return expr
def Expression02(self):
if self.At('++', '--', '+', '-', '!', '~', '*', '&'):
op = self.GetTok().type
return ast.PrefixOperation(op, self.Expression02())
if self.Consume(';sizeof'):
return ast.SizeofExpression(self.Expression())
if self.Consume('sizeof'):
self.Expect('(')
type_ = self.TypeExpression()
self.Expect(')')
return ast.SizeofType(type_)
return self.Expression01()
def Expression03(self):
expr = self.Expression02()
while self.At('*', '/', '%'):
op = self.GetTok().type
expr = ast.BinaryOperation(expr, op, self.Expression02())
return expr
def Expression04(self):
expr = self.Expression03()
while self.At('+', '-'):
op = self.GetTok().type
expr = ast.BinaryOperation(expr, op, self.Expression03())
return expr
def Expression05(self):
expr = self.Expression04()
while self.At('<<', '>>'):
op = self.GetTok().type
expr = ast.BinaryOperation(expr, op, self.Expression04())
return expr
def Expression06(self):
expr = self.Expression05()
while self.At('<', '<=', '>', '>='):
op = self.GetTok().type
expr = ast.BinaryOperation(expr, op, self.Expression05())
return expr
def Expression07(self):
expr = self.Expression06()
while self.At('==', '!='):
op = self.GetTok().type
expr = ast.BinaryOperation(expr, op, self.Expression06())
return expr
def Expression08(self):
expr = self.Expression07()
while self.At('&'):
op = self.GetTok().type
expr = ast.BinaryOperation(expr, op, self.Expression07())
return expr
def Expression09(self):
expr = self.Expression08()
while self.At('^'):
op = self.GetTok().type
expr = ast.BinaryOperation(expr, op, self.Expression08())
return expr
def Expression10(self):
expr = self.Expression09()
while self.At('|'):
op = self.GetTok().type
expr = ast.BinaryOperation(expr, op, self.Expression09())
return expr
def Expression11(self):
expr = self.Expression10()
while self.At('&&'):
op = self.GetTok().type
expr = ast.BinaryOperation(expr, op, self.Expression10())
return expr
def Expression12(self):
expr = self.Expression11()
while self.At('||'):
op = self.GetTok().type
expr = ast.BinaryOperation(expr, op, self.Expression11())
return expr
def Expression13(self):
expr = self.Expression12()
while self.Consume('?'):
cond = self.Expression()
self.Expect(':')
expr = ast.ConditionalExpression(expr, cond, self.Expression12())
return expr
def Expression14(self):
expr = self.Expression13()
while self.At('=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '&=', '^=', '|='):
op = self.GetTok().type
expr = ast.BinaryOperation(expr, op, self.Expression13())
return expr
## statement parsing
def Statement(self):
if self.Consume(';i'):
return ast.Include(self.Expect('char').value)
elif self.Consume(';v'):
name = ast.Id(self.Expect('id').value)
type_ = self.TypeExpression()
value = None
if self.Consume('='):
value = self.Expression()
self.Expect(';')
return ast.VariableDeclaration(name, type_, value)
elif self.Consume(';f'):
name = ast.Id(self.Expect('id').value)
type_ = self.TypeExpression()
body = self.Statement()
return ast.FunctionDefinition(name, type_, body)
elif self.Consume(';s'):
name = ast.TypeId(self.Expect('id').value)
bases = []
while not self.At('{'):
bases.append(self.TypeExpression())
body = self.Statement()
return ast.StructDefinition(name, tuple(bases), body)
elif self.Consume(';t'):
args = []
while not self.At(';f', ';s'):
args.append(ast.TypeId(self.Expect('id').value))
if self.At(';f'):
return ast.TemplateFunctionDefinition(tuple(args), self.Statement())
elif self.At(';s'):
return ast.TemplateStructDefinition(tuple(args), self.Statement())
else:
raise SyntaxError(self.peek)
elif self.Consume('while'):
cond = self.Expression()
body = self.Statement()
return ast.While(cond, body)
elif self.Consume('{'):
stmts = []
while not self.Consume('}'):
stmts.append(self.Statement())
return ast.Block(tuple(stmts))
elif self.Consume('return'):
expr = self.Expression()
self.Expect(';')
return ast.Return(expr)
else:
expr = self.Expression()
self.Expect(';')
return ast.ExpressionStatement(expr)
## type expression parsing
def TypeExpression(self):
if self.At('id'):
return ast.TypeId(self.Expect('id').value)
elif self.Consume('const'):
return ast.ConstType(self.TypeExpression())
elif self.Consume('volatile'):
return ast.VolatileType(self.TypeExpression())
elif self.Consume('*'):
return ast.PointerType(self.TypeExpression())
elif self.Consume('['):
if self.At('int'):
index = self.GetTok().value
self.Expect(']')
return ast.ArrayType(self.TypeExpression(), index)
else:
args = []
while not self.Consume(']'):
args.append(self.TypeExpression())
template_name = self.Expect('id').value
return ast.TemplateType(tuple(args), template_name)
elif self.Consume('('):
argnames = []
argtypes = []
while not self.Consume(')'):
argnames.append(ast.Id(self.Expect('id').value))
argtypes.append(self.TypeExpression())
self.Consume(',')
returns = self.TypeExpression()
return ast.FunctionType(tuple(argnames), tuple(argtypes), returns)
else:
raise self.Error('Expected type expression')
|
7cff7f6452b6f56411308bb48d4626286be87936 | vitaliivolodin/codewars | /pig_latin.py | 243 | 3.921875 | 4 | # http://www.codewars.com/kata/520b9d2ad5c005041100000f/train/python
def pig_it(text):
return ' '.join([x[1:] + x[0] + 'ay' if x.isalpha() else x for x in text.split()])
if __name__ == '__main__':
print(pig_it('Pig latin is cool')) |
f08435310c61ac0f16e352fe6a5bad34d915b784 | sureshmelvinsigera/linkedlist | /reverse.py | 594 | 4.25 | 4 | '''
Given pointer to the head node of a linked list, the task is to reverse the
linked list. We need to reverse the list by changing links between nodes.
Input : Head of following linked list
1->2->3->4->NULL
Output : Linked list should be changed to,
4->3->2->1->NULL
'''
from linkedlist import LinkedList
from linkedlist import Node
def reverse(l):
prev, current = None, l.head
while current:
current.next, prev, current = prev, current, current.next
l.head = prev
l = LinkedList()
[l.append(x) for x in range(1, 5)]
l.printList()
reverse(l)
l.printList()
|
c4650ed36f4500d3a4e603a85525093b4e6574ca | tapumar/Competitive-Programming | /Uri_Online_Judge/1168.py | 424 | 3.796875 | 4 | casos = int(input())
for i in range(casos):
led=0
num = input()
for j in num:
if j=="1":
led=led+2
elif j=="2" or j == "3" or j =="5":
led = led+5
elif j=="4":
led = led+4
elif j=="0" or j=="9" or j=="6":
led = led+6
elif j=="8":
led=led+7
elif j=="7":
led=led+3
print(str(led)+ " leds")
|
73887921856a87ad1df80163fd2df0094f28bcfb | Aasthaengg/IBMdataset | /Python_codes/p03633/s897890218.py | 156 | 3.75 | 4 | import math
def lcm(a,b):
return a*b//math.gcd(a,b)
N=int(input())
T=[int(input()) for _ in range(N)]
ans=1
for t in T:
ans=lcm(ans,t)
print(ans)
|
537213fcc15464b6c3ed67ef4fbda9247dac895d | Zhaoput1/Python | /Leetcode/highfre/66_59generateMatrix.py | 682 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
# @Time : 5/26/21
# @Author : Zhaopu Teng
"""
from typing import List
def generateMatrix(n: int) -> List[List[int]]:
res = [[0 for _ in range(n)] for _ in range(n)]
count, i, j, temp = 1, 0, 0, 0
while n > 0:
for i in range(temp,n):
res[j][i] = count
count += 1
for j in range(1+temp,n):
res[j][i] = count
count += 1
for i in range(n-2,-1+temp,-1):
res[j][i] = count
count += 1
for j in range(n-2,0+temp,-1):
res[j][i] = count
count += 1
n -= 1
temp += 1
return res
print(generateMatrix(n)) |
24bd8bf13c09063b6a4e8e179738ea13f1799b7c | ArneVogel/aoc18 | /day6/coordinates.py | 2,915 | 3.5 | 4 | import sys
def print_grid(grid, minX, maxX, minY, maxY):
for x in range(minX, maxX):
for y in range(minY, maxY):
if len(grid[(x,y)]) == 1:
print(grid[(x,y)][0][0], end="")
else:
print(".", end="")
print()
def get_areas(lines, overlap=1):
minX = min(int(l.split(", ")[0]) for l in lines)-overlap
maxX = max(int(l.split(", ")[0]) for l in lines)+overlap
minY = min(int(l.split(", ")[1]) for l in lines)-overlap
maxY = max(int(l.split(", ")[1]) for l in lines)+overlap
grid = {}
for x in range(minX, maxX):
for y in range(minY, maxY):
grid[(x,y)] = [(99999,9999999)] # (shortest node, distance to node)
for counter, line in enumerate(lines):
lx = int(line.split(", ")[0])
ly = int(line.split(", ")[1])
for x in range(minX, maxX):
for y in range(minY, maxY):
distance = abs(x - lx) + abs(y - ly)
if distance < grid[(x,y)][0][1]:
grid[(x,y)] = [(counter, distance)]
elif distance == grid[(x,y)][0][1]:
grid[(x,y)].append((counter, distance))
area = {}
for x in range(minX, maxX):
for y in range(minY, maxY):
if len(grid[(x,y)]) == 1:
area[grid[(x,y)][0][0]] = area.get(grid[(x,y)][0][0], 0) +1
#print_grid(grid, minX, maxX, minY, maxY)
return area
def part_one(lines):
offset1 = get_areas(lines, overlap=1)
offset3 = get_areas(lines, overlap=3)
max_area = 0
for o in offset1:
if offset1[o] == offset3[o] and offset1[o] > max_area:
max_area = offset1[o]
print("part one")
print(max_area)
def part_two(lines):
print("part two")
overlap = 1
minX = min(int(l.split(", ")[0]) for l in lines)-overlap
maxX = max(int(l.split(", ")[0]) for l in lines)+overlap
minY = min(int(l.split(", ")[1]) for l in lines)-overlap
maxY = max(int(l.split(", ")[1]) for l in lines)+overlap
grid = {}
points = []
for line in lines:
x = int(line.split(", ")[0])
y = int(line.split(", ")[1])
points.append((x,y))
for x in range(minX, maxX):
for y in range(minY, maxY):
total_distance = 0
for point in points:
total_distance += abs(point[0]-x) + abs(point[1]-y)
grid[(x,y)] = total_distance
#print(grid)
max_distance = 10000
sum_coordinates = 0
for p in grid:
if grid[p] < max_distance:
sum_coordinates += 1
print(sum_coordinates)
def main():
input_lines = []
if len(sys.argv) > 1:
for line in sys.argv[1:]:
input_lines.append(line)
else:
for line in sys.stdin:
input_lines.append(line)
part_one(input_lines)
part_two(input_lines)
if __name__ == "__main__":
main()
|
e6324fde5386e368117232251a22a18d7834174f | t0futac0/ICTPRG-Python | /Assingment 1.py | 1,152 | 4.28125 | 4 | #a. Read the specified details from the user (First Name, Last Name, Age)
# This will mean that your application must accept ANY name and age combination not just the ones from the examples.
#b. Process their age depending on your Student ID
#c. Generate and output a pipe (‘|’) separated email and password combo.
#i. This output will be like the example provided, but with the provided name and age used instead.
#d. Keep asking until the user has entered an empty first name
logins = []
while True:
first_name = input("First name: ")
if first_name == (''):
break
surname = input("Surname: ")
user_age = input (str("Age:"))
student_id_no = 3
generated_pwd = (int(user_age)) + (int(student_id_no))
part_1 = first_name[0]
domain = "@Huawow.io "
email_address = part_1.lower() + surname.lower() + domain
seperator = ('| ')
part_2 = surname[0]
initial_password = (first_name.lower() + part_2.upper() + '_' + str(generated_pwd))
output = (email_address + seperator + initial_password)
logins.append(output)
print("Your new login details are: ")
for x in logins:
print (x)
|
fd840cb9982235178d0f64216446ebd967ad13d2 | jamesmcgill/project-euler | /problem4/problem4.py | 800 | 3.921875 | 4 | def is_palindrome(x):
number_string = str(x)
num_digits = len(number_string)
for i in range(num_digits // 2):
if number_string[i] != number_string[-i-1]:
return False
return True
def main() :
left = 999
right = 999
max_product = 1
while True:
#print("Test {}x{} = {}".format(left, right, left*right))
product = left * right
if is_palindrome(product):
print("--->Palindrom found {}x{} = {}".format(left, right, product))
if product > max_product:
max_product = product
if left > 1:
left -= 1
elif right > 1:
right -= 1
left = right
else:
print("MAX -->{}".format(max_product))
return
main() |
10a68a58571ff37a2524021efa79edba49f8789c | guozhoahui/4-1 | /乘法表.py | 421 | 3.578125 | 4 | def chengfabiao(rows):
start = 1;
for row in range(start, rows):
str1 = ""
space = " "
for col in range(1, row + 1):
if (row == 3 and col == 2) or (row == 4 and col == 2):
space = " "
else:
space = " "
str1 += (str(row) + "*" + str(col) + "=" + str(row * col) + space)
print(str1)
chengfabiao(20) |
fcd99c694cf6bb7089a2e4c22918ef55651ff27f | SoundlessPython/BlackPython | /Python/new.py | 109 | 3.765625 | 4 | a = 5
b = 4
if a < b:
print("a is smaler than b")
print("I think so")
print("a is not smaller than b")
|
4cb74dc4c39c685de462c23997c4929a9c9673b8 | luzzyzhang/my-python-cookbook | /01-data-structures-and-algorithms/calculate_with_dict.py | 892 | 3.96875 | 4 | # -*- coding: utf-8 -*-
# Perform calculations on dictionary data
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
min_price = min(zip(prices.values(), prices.keys()))
max_price = max(zip(prices.values(), prices.keys()))
prices_sorted = sorted(zip(prices.values(), prices.keys()))
print min_price
print max_price
print zip(prices.values(), prices.keys())
print prices_sorted
# zip() creates an iterator can only be consumed once
prices_names = zip(prices.values(), prices.keys())
print min(prices_names) # OK
print max(prices_names) # Oh no
print 50*'*'
dct = {'AAA': 45.23, 'ZZZ': 45.23}
print min(zip(dct.values(), dct.keys()))
print max(zip(dct.values(), dct.keys()))
print 50*'~'
# Not well
print min(prices)
print min(prices.values())
print min(prices, key=lambda k: prices[k])
print prices[min(prices, key=lambda k: prices[k])]
|
a45bdaba001d089b9e4799f46ba9a1eeb03db2a2 | BHill96/TXSTproblemSolvers | /shuffleProblem.py | 3,608 | 4.0625 | 4 | import copy
import csv
import time
# Inserts every number between 1 and maxNumber into myList in reverse order
# i.e. 5, 4, 3, 2, 1
def populateList(myList, maxNumber):
for number in range(1, maxNumber + 1):
myList.append(number)
# Removes every other number and appends it to the bottom starting with the first number.
# This does not resemble the actual shuffling algorithm in the problem, but it gets the same result.
# I love this function because I found it by accident.
def shuffle(deck):
for index in range(0, len(deck)):
temp = deck.pop(index)
deck.append(temp)
# The list is backwards, so we reverse it
deck.reverse()
def trackNumber(trackedNumber, shuffledDeck1, shuffledDeck2 = [], shuffledDeck3 = []):
result = []
# if
for index in range(0, len(shuffledDeck1)):
if shuffledDeck1[index] == trackedNumber:
result.append(index + 1)
if (shuffledDeck2):
for index in range(0, len(shuffledDeck2)):
if shuffledDeck2[index] == trackedNumber:
result.append(index + 1)
else:
return result[0]
if (shuffledDeck3):
for index in range(0, len(shuffledDeck3)):
if shuffledDeck3[index] == trackedNumber:
result.append(index + 1)
else:
return "({}, {})".format(result[0], result[1])
return "({}, {}, {})".format(result[0], result[1], result[2])
def binaryForm(number):
return str(bin(number))[2:]
def partC(size):
deck = []
populateList(deck, size)
for num in range(0,3):
shuffle(deck)
print(deck[0])
def partD(size):
deck = []
result = []
# Populate the deck
populateList(deck, size)
# Shuffle the deck 'size' number of times
for num in range(1, size + 1):
shuffle(deck)
# Store the number at the top of the deck after each shuffle
result.append(trackNumber(1, deck))
# If the number at the top of the deck is 1, check if it's a one cycle
if deck[0] == 1:
result.sort()
# Check if each number from 1 to size is in result
# If true, size is an answer for part D
# If false, size is not an answer for partD
for index in range(0, size):
if result[index] != (index + 1):
return False
return True
else:
return False
def writeToCSV(n):
startTime = time.clock()
with open('/Users/blakehillier/programs/miscPython/shuffleData.csv','wb') as shuffleFile: #finds csv file 'shuffleData'
shuffleWriter = csv.writer(shuffleFile) #creates writing object to write to drinkData, delimiter defaulted to ','
shuffleWriter.writerow(('Size of Deck (n)', 'Binary form of n', 'Part A', 'Part B', 'Part C', 'Part D', 'Cycle of 1 after 3 Shuffles', 'Deck after 1 Shuffle', 'Deck after 2 Shuffles', 'Deck after 3 Shuffles'))
for num in range(1, n + 1):
deckA = []
populateList(deckA, num)
shuffle(deckA)
deckB = copy.deepcopy(deckA)
shuffle(deckB)
deckC = copy.deepcopy(deckB)
shuffle(deckC)
cycle = trackNumber(1, deckA, deckB, deckC)
shuffleWriter.writerow((num, binaryForm(num), deckA[0], deckB[0], deckC[0], partD(num), cycle, deckA, deckB, deckC))
shuffleFile.close()
endTime = time.clock()
print "Done"
print endTime - startTime |
b127984662a1786d2c7cc19966b566d4ab299b48 | FaouziDakir/PythonTraining | /ex1.py | 117 | 4.0625 | 4 | val = input("Hey what is your name ? : ")
if val != "" :
print("hello " + val)
else :
print("Hello, World!") |
b4268372bf68424aa0745f94c64f91bdce45a8a6 | AbhineetD/cryptopals-challenge | /set1/challenge2.py | 540 | 3.5625 | 4 | #Cryptopals Challenge Set 1 Challenge 2
import codecs
'''
This function gives XOR of 2 hex strings
@Input: 2 Hex strings of equal length
@Output: XOR output of 2 strings
'''
def xor_2_strings(hex_string_1, hex_string_2):
if (len(hex_string_1) == len(hex_string_2)):
return hex(int(hex_string_1, 16) ^ int(hex_string_2, 16))
else:
return 0
if __name__ == "__main__":
hex_string_1 = '1c0111001f010100061a024b53535009181c'
hex_string_2 = '686974207468652062756c6c277320657965'
print(xor_2_strings(hex_string_1, hex_string_2))
|
1fbeeed8f3135e44e3532ba046d0bbc994227d8e | marcosvnl/exerciciosPythom3 | /ex082.py | 804 | 3.8125 | 4 | # Crie um progrma que vai ler vários números e colocar em uma lista. depois disso, crie duas listas extras
# que vão conter apenas os valores pares e os valores impares digitados, respectivamente.
# Ao final, mostre o conteúdo das listas geradas.
principal = list()
listapar = list()
listaimpar = list()
while True:
principal.append(int(input('Digite um número:')))
resposta = ' '
while resposta not in 'SN':
resposta = str(input('Quer digitar um novo número? [S/N] ')).upper().strip()[0]
if resposta == 'N':
break
print(f'Lista Principal - {principal}')
for indice, valor in enumerate(principal):
if valor % 2 == 0:
listapar.append(valor)
else:
listaimpar.append(valor)
print(f'Lista impar - {listaimpar}')
print(f'Lista par - {listapar}')
|
57489adbba2a55b2fdb92d46ad5c6eb046a686fb | metshein/python | /h6.4a.py | 266 | 3.75 | 4 | def tervitus(x):
print("Võõrustaja: \"Tere!\"")
print("täna "+str(x)+". kord tervitada, mõtiskleb võõrustaja.")
print("Külaline: \"Tere, suur tänu kutse eest!\"")
x = int(input("Sisestage külaliste arv: "))
for i in range(1,x+1):
tervitus(i) |
33a82f8cc608c1779d01a291a665139ff253282b | MarcosAllysson/python-basico-fundamento-da-linguagem | /prova-mundo-1.py | 2,104 | 4.71875 | 5 | """
Qual é o resultado calculado pelo Python para as expressões simples 19 // 2 e 19%2, respectivamente?
"""
primeiro_resultado = 19 // 2
segundo_resultado = 19 % 2
#print('Primeiro resultado \033[1;36m{}\033[m, segundo resultado \033[4;39m{} \033[m.'.format(primeiro_resultado, segundo_resultado))
"""
Se o nosso programa Python precisar calcular a raiz quadrada de um número, seria interessante
incluir qual linha como primeiro comando desse programa?
"""
#print('from math import sqrt')
"""
Considerando as variáveis n='José' e i=25, qual das opções abaixo é a única válida como uma
string formatada que funcionaria em Python?
"""
n = 'José'
i = 25
#print('Você se chama {0} e tem {1} anos de idade.'.format(n, i))
"""
Considere a string x = 'curso de python no cursoemvideo'. Qual dos comandos abaixo retornaria a palavra 'curso'?
"""
x = 'curso de python no cursoemvideo'
#print(x.split(' ')[0])
#print(x[:5])
"""
Qual das opções a seguir completa as lacunas da afirmação abaixo?
A Linguagem Python foi criada no ano de ___ , pelo programador ______________.
Das opções abaixo, a única que preenche corretamente as lacunas é:
"""
#print('Ano {}, programador {}.'.format(1982, 'Guido Van Hossum'))
"""
Qual dos comandos a seguir é capaz de escrever uma mensagem na tela usando Python?
"""
#print('O print().')
"""
Para o Python, os valores verdadeiro e falso são do tipo ________ e são representados pelos
valores ________ e ________. Qual das opções a seguir é a única que contém as palavras que
completam as lacunas da frase anterior, na ordem?
"""
#print('bool, True e False. ')
"""
Qual é o resultado calculado pelo Python para a expressão composta 3 * 5 + 4 ** 2?
"""
#print('Expressão composta 3 * 5 + 4 ** 2 = {}'.format((3 * 5) + (4 ** 2)))
"""
O nome da linguagem Python foi escolhido pelo seu criador para homenagear o que?
"""
#print('Um programa de TV chamado Month Python.')
"""
Das opções abaixo, apenas uma NÃO É uma característica da linguagem Python. Marque a opção inválida da lista a seguir:
"""
print('É nativamente compilada.')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.