blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
ec8f4237a7cecca0e6e3d53beb5d69a9e94fbf7e | lovekobe13001400/pystudy | /py-cookbook/4.迭代器和生成器/3.使用生成器创建新的迭代模式.py | 392 | 3.96875 | 4 |
#
def frange(start,stop,increment):
x = start
while x<=stop:
yield x
x += increment
for i in frange(0,4,0.5):
print(i)
#函数底层机制
def countdown(n):
print("starting to count from",n)
while n > 0:
yield n
n -= 1
print('Done')
c = countdown(3)
next(c)
next(c)
next(c)
#Stopiteration
next(c) |
c551b28e8d2a07383115b135b52a15ad01a82710 | wingarlo/DailyProgrammer | /2018-6-18.py | 444 | 3.796875 | 4 | import random
import math
'''
[2018-06-18]Challenge #364 [Easy] Create a Dice Roller
Logan Wingard
8/9/2018
'''
random.seed()
def roll(com):
nums = com.split("d")
rolled = [0] * int(nums[0])
for i in range(0,int(nums[0])):
rolled[i] += random.randint(1,int(nums[1]))
sumed = sum(rolled)
return (rolled, sumed)
while(1):
thing = raw_input()
if(thing == "q" or thing == "quit"):
break
rolled, summed = roll(thing)
print summed, ":", rolled |
cbcac0c22d776d699b8316709cb38c664b535db6 | hjkqubit/CS134-Sudoku-Solver | /sudoku solver/solver.py | 13,200 | 4.03125 | 4 | #!/usr/bin/env python3
# (c) 2018 Hyeongjin Kim
# a script to solve (or attempt to solve) Sudoku
from module import * # importing useful data structures from module
import ast # used in evaluating a string repr of a list
__all__ = ["solve", "safesolve", "countsolve"]
squares = squares() # list of 81 squares/points
peers = peers() # dictionary of peers
boxes = boxes() # dictionary of squares in boxes
_rows = 'ABCDEFGHI'
_columns = '123456789'
def kandidates(db):
"""Returns a dictionary of each 81 squares as key and a string of
'123456789' if square is blank or the string of value itself
if already filled in from initial clues.
db: initial Sudoku dictionary processed from sudoku_data method
result: dictionary
key: string of points
value: '123456789' or str(value) if filled
"""
candList = dict()
for point in squares:
if db[point] != '0':
candList[point] = str(db[point])
else:
candList[point] = '123456789'
return candList
def isSolved(candidates):
"""Returns True if candidates dictionary corresponds
to a dictionary of a solved Sudoku board else False if not solved.
candidates: dictionary
result: boolean
"""
for point in candidates:
if len(candidates[point]) != 1: # a solved Sudoku must have a unique solution
return False
for column in columnsNum(candidates):
if sum(column) != 45:
return False
for row in rowsNum(candidates):
if sum(row) != 45:
return False
for box in boxesNum(candidates):
if sum(box) != 45:
return False
return True
def eliminate(candidates):
"""Single Possibility Rule: Returns a dictionary of possible candidates (value)
for each square (key) after eliminating impossible candidates by
excluding any value from the square's SOLVED peers.
candidates: dictionary
result: dictionary
key: string of points
value: string of possible candidates
"""
solvedPoints = [point for point in candidates if len(candidates[point]) == 1] # list of solved points
for point in solvedPoints:
for peer in peers[point]:
value = candidates[point]
candidates[peer] = candidates[peer].replace(value,'') # eliminating value from solved peer
return candidates
def slicing(candidates):
"""Slicing Dicing / Hidden Singles Method: Returns a dictionary of
possible candidates (value) for each square (key) by assigning a value, say x,
to a square if such square is the only point within its box that contains x.
candidates: dictionary
result: dictionary
key: string of points
value: string of possible candidates
"""
for point in candidates:
for value in candidates[point]:
values = '' # string of all possible candidates in squares of point's box excluding itself
for box in boxes[point]:
values += candidates[box]
if value not in values: # point is the only square within box with value as its candidate(s)
candidates[point] = value # that point must be filled with value
return candidates
def subgroupRowsExclusion(candidates):
"""Subgroup Exclusion by Row: Returns a dictionary of possible candidates (value)
for each square (key) by eliminating possible candidates via subgroup exclusion.
Given a subgroup (a group of two or three squares within SAME box), in this case by row,
if a given candidate value, say x, within the subgroup does not appear in any of the candidates
of the squares within the same row, then x cannot be one of the possible candidates for squares
within the subgroup's box, of course excluding the subgroup squares themselves. The reverse is true
if we look for candidate x within squares of same box and work our way through the squares in the row.
Refer to README for further details, for this method is difficult to grasp.
candidates: dictionary
result: dictionary
key: string of points
value: string of possible candidates
"""
for subrow in subgroupsRows().keys(): # subgroup is given as a string repr of list of three points
subrowValues = '' # the candidate numbers within subgroup points
for subrowPoint in ast.literal_eval(subrow): # ast.literal_eval to evaluate the string repr of list
subrowValues += candidates[subrowPoint]
rowgroupValues = '' # the candidate numbers within points of same row as subgroup
for rowgroupPoint in subgroupsRows()[subrow]:
rowgroupValues += candidates[rowgroupPoint]
# Construct a set of value(s) in subgroup but NOT in other squares within the same row
values = set(map(int,subrowValues)).difference(set(map(int,rowgroupValues)))
for value in values:
for rowboxPoint in boxgroupsRows()[subrow]:
# Remove such value(s) from candidates of squares within same box as subgroup
candidates[rowboxPoint] = candidates[rowboxPoint].replace(str(value), '')
# Iterate the process in reverse order
boxgroupValues = '' # the candidate numbers within points of same box as subgroup
for boxgroupPoint in boxgroupsRows()[subrow]:
boxgroupValues += candidates[boxgroupPoint]
# Construct a set of value(s) in subgroup but NOT in other squares within the same box
values = set(map(int,subrowValues)).difference(set(map(int,boxgroupValues)))
for value in values:
for subrowPoint in subgroupsRows()[subrow]:
# Remove such value(s) from candidates of squares within same row as subgroup
candidates[subrowPoint] = candidates[subrowPoint].replace(str(value), '')
return candidates
def subgroupColumnsExclusion(candidates):
"""Subgroup Exclusion by Column: Returns a dictionary of possible candidates (value)
for each square (key) by eliminating possible candidates via subgroup exclusion.
Given a subgroup (a group of two or three squares within SAME box), in this case by column,
if a given candidate value, say x, within the subgroup does not appear in any of the candidates
of the squares within the same column, then x cannot be one of the possible candidates for squares
within the subgroup's box, of course excluding the subgroup squares themselves. The reverse is true
if we look for candidate x within squares of same box and work our way through the squares in the column.
Refer to README for further details, for this method is difficult to grasp.
candidates: dictionary
result: dictionary
key: string of points
value: string of possible candidates
"""
for subcolumn in subgroupsColumns().keys():
subcolumnValues = '' # the candidate numbers within subgroup points
for subcolumnPoint in ast.literal_eval(subcolumn):
subcolumnValues += candidates[subcolumnPoint]
columngroupValues = '' # the candidate numbers within points of same column as subgroup
for columngroupPoint in subgroupsColumns()[subcolumn]:
columngroupValues += candidates[columngroupPoint]
# Construct a set of value(s) in subgroup but NOT in other squares within the same column
values = set(map(int,subcolumnValues)).difference(set(map(int,columngroupValues)))
for value in values:
for columnboxPoint in boxgroupsColumns()[subcolumn]:
# Remove such value(s) from candidates of squares within same box as subgroup
candidates[columnboxPoint] = candidates[columnboxPoint].replace(str(value), '')
# Iterate the process in reverse order
boxgroupValues = '' # the candidate numbers within points of same box as subgroup
for boxgroupPoint in boxgroupsColumns()[subcolumn]:
boxgroupValues += candidates[boxgroupPoint]
# Construct a set of value(s) in subgroup but NOT in other squares within the same box
values = set(map(int,subcolumnValues)).difference(set(map(int,boxgroupValues)))
for value in values:
for subcolumnPoint in subgroupsColumns()[subcolumn]:
# Remove such value(s) from candidates of squares within same column as subgroup
candidates[subcolumnPoint] = candidates[subcolumnPoint].replace(str(value), '')
return candidates
def nakedpairs(candidates):
"""Naked Pairs (Triplets, Quartets) Elimination: Returns a dictionary of possible candidates (value)
for each square (key) by eliminating possible candidates via naked pairs principle.
Given a region (row, column, or box) if a pair of numbers, say x and y, only appear in TWO squares,
then no other squares within its region and POTENTIALLY other interacting region cannot have x and y
as their possible candidates.
This principle can apply for triplet, or even quartet, of numbers given that there are three or four
squares, respectively, that have the same combination of numbers.
Refer to README for further details, for this method will take more words to explain.
candidates: dictionary
result: dictionary
key: string of points
value: string of possible candidates
"""
for row in rowify(candidates): # convert candidates to be ordered by rows
flipped = flipify(row) # flip the dictionary so that its keys are the values and vice versa
# Construct a dictionary of pair/triplet/quartet numbers corresponding to the points that have such combinations
nakedrowpairs = {key:value for key,value in flipped.items() if len(value) > 1 and len(value) == len(key)}
for pairNum,pairs in nakedrowpairs.items():
rowReference = pairs[0][0] # rowReference indicates which row the pair is in
for point in rowDict()[rowReference]:
for num in pairNum:
if point not in pairs:
candidates[point] = candidates[point].replace(num,'')
# The same format of iteration applies for columns
for column in columnify(candidates):
flipped = flipify(column)
nakedcolumnpairs = {key:value for key,value in flipped.items() if len(value)>1 and len(value) == len(key)}
for pairNum,pairs in nakedcolumnpairs.items():
columnReference = pairs[0][1]
for point in columnDict()[columnReference]:
for num in pairNum:
if point not in pairs:
candidates[point] = candidates[point].replace(num,'')
# This is implemented for two reasons:
# 1) The pair/triplet/quartet of numbers may not appear in the same
# row or column, that is they are adjacent diagonally.
# 2) If the pair/triplet/quarter appear in a row or column and
# are in the same box, then the elimination principle should
# apply for squares within the same box, which was not implemented
# in the previous two iterations.
for box in boxify(candidates):
flipped = flipify(box)
nakedboxpairs = {key:value for key,value in flipped.items() if len(value)>1 and len(value) == len(key)}
for pairNum,pairs in nakedboxpairs.items():
boxReference = pairs[0]
for point in boxes[boxReference]:
for num in pairNum:
if point not in pairs:
candidates[point] = candidates[point].replace(num,'')
return candidates
def hiddenpairs(candidates):
pass
def XWings(candidates):
pass
def solve(db):
"""This function should run all of the previous functions to solve Sudoku.
result: solved sudoku
"""
candidates = kandidates(db)
while not isSolved(candidates):
candidates = eliminate(candidates)
candidates = slicing(candidates)
candidates = subgroupRowsExclusion(candidates)
candidates = subgroupColumnsExclusion(candidates)
candidates = nakedpairs(candidates)
return candidates
def safesolve(db):
"""This function should run all of the previous functions to solve Sudoku.
result: solved sudoku if solved else None
"""
candidates = kandidates(db)
for _ in range(30):
candidates = eliminate(candidates)
candidates = slicing(candidates)
candidates = subgroupRowsExclusion(candidates)
candidates = subgroupColumnsExclusion(candidates)
candidates = nakedpairs(candidates)
if not isSolved(candidates):
return None
else:
return candidates
def countsolve(db):
"""This function should run all of the previous functions to solve Sudoku.
result: 1 if sudoku is solved else 0
"""
candidates = kandidates(db)
for _ in range(30):
candidates = eliminate(candidates)
candidates = slicing(candidates)
candidates = subgroupRowsExclusion(candidates)
candidates = subgroupColumnsExclusion(candidates)
candidates = nakedpairs(candidates)
if not isSolved(candidates):
return 0
else:
return 1 |
f14e54d64a3c3d60f941a5431f4917ae80a8836c | cbielby27/COP1500 | /IntegrationProject3.py | 8,648 | 4.3125 | 4 | # Chelsea Bielby
# Welcome to my integration project! Here, I will showcase what I
# have learned in COP1500 thus far. :)
greeting = "Hi!" * 10
print(greeting)
print("Sorry, I get a little excited sometimes.")
print("Anyway, ", end="")
print("Welcome to my integration project!")
print("What is your name?")
name = input()
str1 = "Hi, "
str2 = "!! I am so glad to have you here!"
print(str1 + name + str2)
print("Enter the value of what interests you today.")
print("1. Math Magic")
print("2. A joke")
print("3. Random password generator")
print("4. Guess a number")
print("5. Guestbook")
print("6. Quit")
keepPlaying = True
while keepPlaying:
pick = int(input())
if pick == 1:
print("Choose your favorite whole number and I'll tell you mine!")
# The answer will always be 27 (a math "magic trick").
#My favorite number.
while True:
try:
num1 = int(input())
num2 = num1 * 2
# multiplies number chosen by 2
num3 = num2 + 9
# adds nine to result
num4 = num3 - 3
# subtracts 3 from result
num5 = num4 / 2
# divides result by 2
num6 = num5 - num1
# subtracts original number from result
num7 = num6 ** 3
# raises num7 to the third power
num8 = num7 % 6
# divided num8 by 6 and gives the remainder
num9 = num8 ** 3
# raises num8 to the third power
num10 = num9 // 1
# divides num 7 by 1 and gives the integer result
print(num1, ": Great number!")
print("Mine is ", format(num9, '2.0f'), "!", sep="")
break
except ValueError:
print("Not a whole number. Try again: ")
print("\nChoose another value from the main menu.")
print("1. Math Magic")
print("2. A joke")
print("3. Random password generator")
print("4. Guess a number")
print("5. Guestbook")
print("6. Quit")
elif pick == 2:
print("Why was 6 scared of 7?")
ans = input()
if ans == "because 7 8 9":
print("Yes! Haha!")
print("\nChoose another value from the main menu.")
else:
num = 7
print("\nBecause", num, " ", end="")
num += 1
# += adds 1 to my assigned number of 7 and update the assignment
# end = "" will assure that the answer prints on one line
print(num, " ", end="")
num += 1
# Here, += will add 1 to 8 because of the previous update
print(num, "Hehe!")
print("\nChoose another value from the main menu.")
print("1. Math Magic")
print("2. A joke")
print("3. Random password generator")
print("4. Guess a number")
print("5. Guestbook")
print("6. Quit")
elif pick == 3:
import random
# This password will contain 10 random characters. 3 uppercase letters,
# 2 lowercase letters, 3 numbers & 2 punctuation signs.
up1 = chr(random.randint(65, 90))
up2 = chr(random.randint(65, 90))
up3 = chr(random.randint(65, 90))
low4 = chr(random.randint(97, 122))
low5 = chr(random.randint(97, 122))
num6 = chr(random.randint(48, 57))
num7 = chr(random.randint(48, 57))
num8 = chr(random.randint(48, 57))
punc9 = chr(random.randint(33, 47))
punc10 = chr(random.randint(33, 47))
# While researching about what the random module is capable of, I came
# across a simplified list of characters from ASC11
def main():
"""Main assembles a password made up of lower and uppercase letters,
numbers and various punctuation."""
up = up1 + up2 + up3
low = low4 + low5
num = num6 + num7 + num8
punc = punc9 + punc10
password = up + low + num + punc
password = shuffle(password)
print("Your password is, ", password, end='')
def shuffle(characters):
"""Shuffle takes an assembled password made up of lower and
uppercase letters, numbers and punctuation and shuffles it
randomly."""
firstpass = list(characters)
random.shuffle(firstpass)
# I also learned how to shuffle from researching what the random
#module is capable of
return "".join(firstpass)
# I learned "join" from practicing on w3schools
main()
print("\n\nChoose another value from the main menu.")
print("1. Math Magic")
print("2. A joke")
print("3. Random password generator")
print("4. Guess a number")
print("5. Guestbook")
print("6. Quit")
elif pick == 4:
import random
computer_number = random.randint(1, 11)
# Computer chooses a random number and compares it to user input
user_number = int(input("Guess a number between 1 and 10: "))
guessingGame = True
while guessingGame == True:
if user_number < 1 or user_number > 10:
print("Invalid Entry.")
user_number = int(input("Enter a number between 1 and 10: "))
elif user_number == computer_number:
for x in range(3):
print("W")
print("Wo")
print("Woo")
print("Woo-")
print("Woo-H")
print("Woo-Ho")
print("Woo-Hoo")
print("Woo-Hoo!")
print("Woo-Hoo")
print("Woo-Ho")
print("Woo-H")
print("Woo-")
print("Woo")
print("Wo")
print("W")
guessingGame = False
print("You guessed the correct number!")
elif user_number != computer_number:
user_number = int(input("That's not it. Guess again: "))
else:
print("Invalid Entry.")
user_number = int(input("Enter a number between 1 and 10: "))
print("\nChoose another value from the main menu.")
print("1. Math Magic")
print("2. A joke")
print("3. Random password generator")
print("4. Guess a number")
print("5. Guestbook")
print("6. Quit")
elif pick == 5:
# This program will start fresh on each computer it is ran on.
# Once it has been ran on a computer, it will continue to add
#to the file.
print("Sign the guestbook!")
def guest_Book():
"""guest_Book takes user input, opens a file called guestbook,
writes it into that file,closes it and then prints the entire
file with the added name."""
sign = input("Enter the name to be entered into the guestbook: ")
file = open("guestbook.txt", 'a')
# This line of code opens a new file called guestbook
file.write(sign)
# This line allows the input to be added to the file
file.write("\n")
file.close()
# This line closes the file
guestbook = open('guestbook.txt')
gb = guestbook.read()
# These two lines open and read the file
n = len(open("guestbook.txt").readlines())
# This line determines how many lines are in the file for a
#future print statement
if n == 1:
print(gb + "has been here!")
# This if/else statement prints "has" if there is only
#one line in the file
else:
print(gb + "have been here!")
# This if/else statement prints "have" if there is more than
#one line in the file
guest_Book()
print("\nChoose another value from the main menu.")
print("1. Math Magic")
print("2. A joke")
print("3. Random password generator")
print("4. Guess a number")
print("5. Guestbook")
print("6. Quit")
elif pick == 6:
keepPlaying = False
# I included the kill feature that I learned from Prof.
#Vanselow's examples.
else:
print("That's not a valid entry. Try again.")
print("Thanks for stopping by! See you next time!")
|
739d34bfea52edfdd6076f339709714689d98401 | rgornik/testniprojekt | /objekt2.py | 773 | 3.859375 | 4 | class Person(object):
def __init__(self, ime, priimek, starost):
self.ime = ime
self.priimek = priimek
self.starost = starost
def show_person(self):
print "Ime: {}\nPriimek: {}\nStarost: {}".format(self.ime,
self.priimek,
self.starost)
def age_in_months(self):
return self.starost*12
if __name__ == '__main__':
oseba = Person("Janez", "Kranjski", 33)
oseba.show_person()
print oseba.age_in_months()
print type(oseba)
person_list = [Person("ime1", "fo", 99), Person("ime2", "kfi", 32), Person("ime3", "kfoe", 87)]
for o in person_list:
o.show_person()
print o.ime |
d37adb67860eb5a34a3b71f490631bdc9c2a1063 | arminAnderson/CodingChallenges | /ProjectEuler/Python/PandigitalPrime.py | 1,250 | 3.71875 | 4 | from math import factorial
def ReverseSectionOfArr(arr, start):
swapAmount = (len(arr) - start)//2
k = len(arr) - 1
for i in range(swapAmount):
i += start
temp = arr[i]
arr[i] = arr[k]
arr[k] = temp
k -= 1
return arr
def GetLexi(arr):
for i in range(factorial(len(arr))):
i = len(arr) - 1
k = len(arr) - 2
while(arr[k] > arr[k+1]):
k -= 1
if(k == -1):
print("FINISHED")
return
while arr[i] < arr[k]:
i -= 1
temp = arr[i]
arr[i] = arr[k]
arr[k] = temp
arr = ReverseSectionOfArr(arr, k + 1)
possible.append(tuple(arr))
def IsPrime(num):
if num % 2 == 0 and num > 2:
return 0
i = 3
while i * i <= num:
if num % i == 0:
return False
i += 2
return True
c = 10
for i in range(10):
array = list(range(1, c))
c -= 1
possible = []
possible.append(tuple(array))
GetLexi(array)
possible.reverse()
for perm in possible:
num = 0
for p in perm:
num *= 10
num += p
if IsPrime(num):
print(num)
exit() |
a8952a45d4005620456406f27a6f16c3f54825b7 | romanbatavi/kickstarter-python | /bab/bab-4/while4.py | 335 | 3.828125 | 4 | ######################################################
# Nama file: while4.py
######################################################
def main():
# melakukan pengulangan dari indeks 'a' sampai 'e'
ch = 'a'
while ch <= 'e':
print("%c: Hello World!" % ch)
ch = chr(ord(ch) + 1)
if __name__ == "__main__":
main()
|
915464e9b6fe07e5f154a200ef5ca2cf1dafc245 | karngyan/Data-Structures-Algorithms | /Tree/BinaryTree/Check_Balanced.py | 1,054 | 4.25 | 4 | # Check if a binary tree is height balanced
# abs(height[leftTree] - height[rightTree]) <= 1
# A Binary Tree node
class Node:
# Constructor to initialise node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def check_height(root):
if root is None:
return -1
left_height = check_height(root.left)
if left_height is float('inf'):
return float('inf')
right_height = check_height(root.right)
if right_height is float('inf'):
return float('inf')
height = abs(left_height - right_height)
if height > 1:
return float('inf')
else:
return max(left_height, right_height) + 1
def isBalanced(root):
return check_height(root) != float('inf')
if __name__ == '__main__':
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
if isBalanced(root):
print("Yes! the tree is balanced")
else:
print("No! the tree is not balanced") |
350270a530a218e464ffb346993323941e1b3f8d | Yash-barot25/DataStructresInPython | /Dictionaries/AdvantureGame.py | 1,318 | 3.84375 | 4 | Locations = {0: "You'r standing front of your computer learning python",
1: "You'r at your home 430 mcmurchy south ave",
2: "You'r at tuckshop of brampton towers",
3: "You'r in garden",
4: "You'r inside of shopper's drug-mart",
5: "You'r at 440 mcmurchy eve "}
exits = {0: {"Q": 0},
1: {"N": 4, "S": 5, "E": 3, "W": 2, "Q": 0},
2: {"N": 4, "S": 5, "Q": 0},
3: {"W": 1, "Q": 0},
4: {"W": 2, "S": 1, "Q": 0},
5: {"E": 3, "Q": 0}}
vocabulary = {"QUIT": "Q",
"WEST": "W",
"EAST": "E",
"SOUTH": "S",
"NORTH": "N"}
loc = 1
while True:
availableExits = ", ".join(exits[loc].keys())
# availableExits = ""
# for location in exits[loc].keys():
# availableExits += location + ", "
print(Locations[loc])
if loc == 0:
break
description = input("Available exits are " + availableExits + " => ").upper()
if len(description) > 1:
for word in vocabulary:
if word in description:
description = vocabulary[word]
if description in exits[loc]:
loc = exits[loc][description]
else:
print("You can't go in that direction")
|
658fd1073a798d5c3503b8b9ceb4a2076dc1974d | Jelle0Bol/nogmaals | /duizelig/even.py | 69 | 3.609375 | 4 | i=20
while(i<=50):
if(i%2==0):
print(i,end=" ")
i=i+1 |
bac32ba211c0c82d4fa164db4c821ce3fbd01516 | robjamesd220/kairos_gpt3 | /Programming_with_GPT-3/GPT-3_Python/semantic_search.py | 1,879 | 3.625 | 4 | # Importing Dependencies
from chronological import read_prompt, fetch_max_search_doc, main
# Creates a seamntic search over the given document 'animal.txt' to fetch the top_most response
async def fetch_top_animal(query):
# function read_prompt takes in the text file animals.txt and split on ',' -- similar to what you might do with a csv file
prompt_animals = read_prompt('animals').split(',')
# Return the top most response
# Default Config: engine="ada" (Fast and efficient for semantic search)
return await fetch_max_search_doc(query, prompt_animals, engine="ada")
# Creates a seamntic search over the given document 'animal.txt' to fetch the top-3 responses
async def fetch_three_top_animals(query, n):
# function read_prompt takes in the text file animals.txt and split on ',' -- similar to what you might do with a csv file
prompt_animals = read_prompt('animals').split(',')
# Return the top-3 responses
# Default Config: engine="ada" (Fast and efficient for semantic search), n=number of responses to be returned
return await fetch_max_search_doc(query, prompt_animals, engine="ada", n=n)
# Designing the end-to-end async workflow, capable of running multiple prompts in parallel
async def workflow():
# Making async call to the search functions
fetch_top_animal_res = await fetch_top_animal("monkey")
fetch_top_three_animals_res = await fetch_three_top_animals("monkey", 3)
# Printing the result in console
print('-------------------------')
print('Top Most Match for given Animal: {0}'.format(fetch_top_animal_res))
print('-------------------------')
print('Top Three Match for given Animal: {0}'.format(fetch_top_three_animals_res))
print('-------------------------')
# invoke Chronology by using the main function to run the async workflow
main(workflow) |
4c6ad64be432581e3695b7ac07979dc6a9187636 | netxeye/Python-programming-exercises | /answers/q18.py | 3,445 | 3.828125 | 4 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
import string
class Question18Password(object):
'''
Password Checking:
'''
__slots__ = ('_password')
def __init__(self, password='Welcome@20'):
self._password = password
@property
def password(self):
return self._password
@password.setter
def password(self, value):
self.password_verify(value)
self._password = value
def password_verify(self, value, debug=False):
_vailable_upper = False
_vailable_lower = False
_vailable_number = False
_vailable_chacter = False
if not isinstance(value, str):
raise ValueError('Password only accept str')
for upper_case in string.ascii_uppercase:
if upper_case in value:
_vailable_upper = True
break
for lower_case in string.ascii_lowercase:
if lower_case in value:
_vailable_lower = True
break
for number in string.digits:
if number in value:
_vailable_number = True
break
for chacter in '$#@':
if chacter in value:
_vailable_chacter = True
break
if not _vailable_upper:
raise ValueError('Password should contain at least 1 upper letter')
if not _vailable_lower:
raise ValueError('Password should contain at least 1 lower letter')
if not _vailable_number:
raise ValueError('Password should contain at least 1 number')
if not _vailable_chacter:
raise ValueError(r'Password should contain at least 1 from' +
' "$" "#" "@"')
if len(value) < 6:
raise ValueError('Minimum length of password should be 6')
if len(value) > 12:
raise ValueError('Manimum length of password should be 12')
if (debug and _vailable_lower and _vailable_upper and
_vailable_number and _vailable_chacter and
len(value) >= 6 and len(value) <= 12):
print('working Passworkd is: ')
print(value)
new_password1 = Question18Password()
new_password2 = Question18Password()
print(new_password1.password)
try:
password_input = input('Eneter your Password: ')
new_password2.password = password_input
except ValueError as error_message:
print('Error:', error_message)
print(new_password2.password)
while True:
password_input2 = input('Eneter your Password sequence separated comma'
+ ' (exit by empty) :')
if password_input2:
for password in password_input2.split(','):
try:
new_password2.password = password
except ValueError as error_message:
print(password + ' is not working, because of ', error_message)
else:
break
print(new_password2.password)
new_password3 = Question18Password()
while True:
password_input3 = input('Eneter your Password sequence separated comma'
+ ' (exit by empty)debug mode :')
if password_input3:
for password in password_input3.split(','):
try:
new_password3.password_verify(password, debug=True)
except ValueError as error_message:
print(password + ' is not working, because of ', error_message)
else:
break
|
9f24e9ece8196fadd5470c54ffac512deafb3b61 | Somjing/TestGit | /Python/Homework_Lecture_24.py | 190 | 3.8125 | 4 | Name = "Somjing"
Surname = "Pluejinda"
Age = 33
Weight = 62
Height = 170
print("My name's",Name,Surname)
print("Age",Age,"years old")
print("Weight",Weight,"kg")
print("Height",Height,"cm") |
8b4a42ba3793428ca9d602971ebc23eae3429db1 | alferesx/programmingbydoing | /SpaceBoxing.py | 804 | 4 | 4 | weight = float(input("Weight: "))
print("1-Venus")
print("2-Mars")
print("3-Jupiter")
print("4-Saturn")
print("5-Uranus")
print("6-Neptune")
planet = int(input("Choose a planet: "))
if planet == 1:
gravity = 0.78
weight = weight * gravity
print("Weight: " + weight)
elif planet == 2:
gravity = 0.39
weight = weight * gravity
print("Weight: " + weight )
elif planet == 3:
gravity = 2.65
weight = weight * gravity
print("Weight: " + weight )
elif planet == 4:
gravity = 1.17
weight = weight * gravity
print("Weight: " + weight )
elif planet == 5:
gravity = 1.05
weight = weight * gravity
print("Weight: " + weight )
elif planet == 6:
gravity = 1.23
weight = weight * gravity
print("Weight: " + weight )
else:
print("This option is not avaiable")
|
2d6fbde1050b4487e4255534276138e22cd8aa1e | sherwin090497/PYTHON | /Practice/PracticePython/PracticePython/PracticePython.py | 889 | 4.15625 | 4 |
print("Hello World!")
#Bounded itereration
# use the range function to produce a list of sequential integers
for i in range(5):
print(f"Square {i}: {i*i}")
total = 0
for i in range(1,5):
total = total + i
print(f"Running Sum {i}: {total}")
total = 0
for i in range(-5,0):
total = total + i
print(f"Running Sum {i}: {total}")
for i in range(0,10,2):
print(f"Up By Two {i}")
for i in range(10,0,-2):
print(f"Down By Two {i}")
# Step through the characters IN a string
prompt = "Fett"
for letter in prompt:
print(letter.upper())
# iterate through all the items in an array (list)
print("Iterate through a list . . .")
data = [1,2,3,25,28,29,37,38]
for item in data:
if item % 2 == 0:
print(item)
print("Another way of doing the above")
for item in (x for x in data if x % 2 == 0):
print(item) |
64d6857a08ef98089ca9fe1f0667f4cf1211ce7e | liubh1994/algorithm | /Python/select_sort.py | 3,018 | 3.609375 | 4 | def select_sort(data_array, sort_flag=0):
"""
选择排序 O(N^2)
:param data_array: 待排序数组
:param sort_flag: 0: 正序 1: 逆序
:return: 排序后的数组
"""
if len(data_array) <= 1:
return data_array
if sort_flag == 1:
for out_index in range(0, len(data_array)):
max_value = data_array[out_index]
index = out_index
sorted_flag = True
for in_index in range(out_index, len(data_array)):
if data_array[in_index] > max_value:
max_value = data_array[in_index]
index = in_index
sorted_flag = False
if sorted_flag is True:
continue
if index != out_index:
data_array[index], data_array[out_index] = data_array[out_index], data_array[index]
else:
for out_index in range(0, len(data_array)):
min_value = data_array[out_index]
index = out_index
sorted_flag = True
for in_index in range(out_index, len(data_array)):
if data_array[in_index] < min_value:
min_value = data_array[in_index]
index = in_index
sorted_flag = False
if sorted_flag is True:
continue
if index != out_index:
data_array[index], data_array[out_index] = data_array[out_index], data_array[index]
return data_array
def pop_sort(data_array, sort_flag=0):
"""
冒泡排序 O(N^2)
:param data_array: 待排序数组
:param sort_flag: 0: 正序 1: 逆序
:return: 排序好的数组
"""
if len(data_array) <= 1:
return data_array
if sort_flag == 1:
for out_index in range(0, len(data_array)-1):
sorted_flag = True
for in_index in range(0, len(data_array)-out_index-1):
if data_array[in_index] < data_array[in_index+1]:
data_array[in_index], data_array[in_index+1] = data_array[in_index+1], data_array[in_index]
sorted_flag = False
if sorted_flag is True:
break
else:
for out_index in range(0, len(data_array)-1):
sorted_flag = True
for in_index in range(0, len(data_array)-out_index-1):
if data_array[in_index] > data_array[in_index+1]:
data_array[in_index], data_array[in_index + 1] = data_array[in_index + 1], data_array[in_index]
sorted_flag = False
if sorted_flag is True:
break
return data_array
print(select_sort([1, 3, 2, 7, 5, 8, 9]))
print(select_sort([1, 3, 2, 7, 5, 8, 9], 1))
print(select_sort([1, 3, 2, 7, 5, 8, 9], 0))
print(select_sort([]))
print(select_sort([1]))
print(pop_sort([1, 3, 2, 7, 5, 8, 9]))
print(pop_sort([1, 3, 2, 7, 5, 8, 9], 1))
print(pop_sort([1, 3, 2, 7, 5, 8, 9], 0))
print(pop_sort([]))
print(pop_sort([1]))
|
a6d14e3bfb4ea04d3975fbf75b253b2ca2960dde | mbod/py4corpuslinguistics | /workshops/Nottingham_18July2011/scripts/Task3.py | 1,777 | 4.03125 | 4 | '''
Python for Corpus Linguistics Workshop
University of Nottingham 18 July 2011
Task 3 - Split the reader comments into separate files (one per comment)
'''
import os
import re
#First write a function to output the list of comments to a file
#1. specify name and the arguements required
def output_comments(comment_list, file_name):
#2. specify the files directory and basic file name for output
comments_dir = '../output/simpleGTech_split/separated_comments'
base_file_name = file_name[:-4]
#3. loop through the list of comments with a counter
for i, comment in enumerate(comment_list[1:]):
#4. set file name for the current comment using base file name and counter i
comments_file = base_file_name + '_%d.txt' % (i + 1)
file_path = os.path.join(comments_dir, comments_file)
#5. write the comment to the file
open(file_path, mode='w', encoding='utf-8').write(comment)
#6. return total of the comments printed
return i + 1
#The main script
#1. specify location of input directory
dir_path = '../output/simpleGTech_split/comments'
#2. loop through all the files in the directory
for file_name in os.listdir(dir_path):
#3. combine the file name with the directory path
file_path = os.path.join(dir_path, file_name)
#4. read the file into a string
text = open(file_path, mode='r', encoding='utf-8').read()
#5. split the comments
comment_list = re.split('<ul .*?class="comment b2".*?>', text)
#6. send the data to the function to print the comments
comment_count = output_comments(comment_list, file_name)
#7. print some feedback
print('outputted %d comments from %s' % (comment_count, file_name))
|
1ac284a3b18cad5b0965cf2feedf0688ad7e3304 | cathuan/LeetCode-Questions | /python/q527.py | 2,408 | 3.890625 | 4 | from collections import defaultdict
class TrieNode(object):
def __init__(self):
self.count = 0
self.children = defaultdict(TrieNode)
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
node = self.root
for i in range(len(word)):
w = word[i]
node = node.children[w]
node.count += 1
def search(self, word):
node = self.root
for i, w in enumerate(word):
assert w in node.children
node = node.children[w]
if node.count == 1:
break
else:
assert False, word
return i
class Solution(object):
def wordsAbbreviation(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
ret = [None] * len(words)
groups = defaultdict(list)
for word, index in sorted([(word, index) for index, word in enumerate(words)]):
groups[(word[0], word[-1], len(word))].append((word, index))
for wordGroup in groups.values():
wordGroup = sorted(wordGroup)
for index, (word, origIndex) in enumerate(wordGroup):
maxIndex = 1
if index >= 1:
curMaxIndex = self.compare(wordGroup[index-1][0], word)
maxIndex = max(maxIndex, curMaxIndex+1)
if index <= len(wordGroup)-2:
curMaxIndex = self.compare(wordGroup[index+1][0], word)
maxIndex = max(maxIndex, curMaxIndex+1)
length = len(word) - 1 - maxIndex
if length <= 1:
newWord = word
else:
newWord = word[:maxIndex] + str(length) + word[-1]
ret[origIndex] = newWord
return ret
def compare(self, word1, word2):
for index, (w1, w2) in enumerate(zip(word1, word2)):
#print "???", w1, w2, word1, word2
if w1 != w2:
return index
if __name__ == "__main__":
print Solution().wordsAbbreviation(["like", "god", "internal", "me", "internet", "interval", "intension", "face", "intrusion"]) |
e52bd3558f4ab9903cbe6a69ea183e896861e604 | wiput1999/Python101 | /1 Class 1/Homework/7.py | 469 | 3.90625 | 4 | a = int(input("A :"))
b = int(input("B :"))
c = int(input("C :"))
d = int(input("D :"))
f = int(input("F :"))
total = a+b+c+d+f
result = (4*a + 3*b + 2*c + 1*d + 0*f)/total
print(result)
'''
defs = (
('A', 4),
('B', 3),
('C', 2),
('D', 1),
('F', 0)
)
sums = 0
weight_sums = 0
for letter, weight in defs:
value = int(input(letter + ":"))
sums += value
weight_sums += value * weight
print("Result", weight_sums / sums)
''' |
3149ded825e364499e128d876e90078a2d82071c | TriggerDark/StudyCodes | /PycharmProjects/PythonCodes/01-Based/12-异常/01-异常.py | 610 | 3.875 | 4 |
# 统计一段数字的平均值,要求连输输入,遇到非法字符,提示非法
# 输入的过程中,要继续输入,提示:继续输入?yes继续,no停止
list = []
while True:
x = input("请输入数值")
try:
list.append(float(x))
except:
print("数字非法")
while True:
flag = input("继续输入吗?[yes/no]")
if flag.lower() not in ('yes', 'no', 'y', 'n'):
print("只能输入yes/s or no/n")
else:
break
if flag.lower() == 'no' or flag.lower() == 'n':
break
print(sum(list) / len(list))
|
25cd373f1a3d43dc71b17738610c918b381e932c | mikeferguson/sandbox_rosbuild | /ex_vision/src/capture.py | 1,618 | 3.671875 | 4 | #!/usr/bin/env python
"""
Example code of how to convert ROS images to OpenCV's cv::Mat
This is the solution to HW2, using Python.
See also cv_bridge tutorials:
http://www.ros.org/wiki/cv_bridge
"""
import roslib; roslib.load_manifest('ex_vision')
import rospy
import cv
from cv_bridge import CvBridge, CvBridgeError
from std_msgs.msg import String
from sensor_msgs.msg import Image
class image_blur:
def __init__(self):
# initialize a node called hw2
rospy.init_node("hw2")
# create a window to display results in
cv.NamedWindow("image_view", 1)
# part 2.1 of hw2 -- subscribe to a topic called image
self.image_sub = rospy.Subscriber("image", Image, self.callback)
def callback(self,data):
""" This is a callback which recieves images and processes them. """
# convert image into openCV format
bridge = CvBridge()
try:
# bgr8 is the pixel encoding -- 8 bits per color, organized as blue/green/red
cv_image = bridge.imgmsg_to_cv(data, "bgr8")
except CvBridgeError, e:
# all print statements should use a rospy.log_ form, don't print!
rospy.loginfo("Conversion failed")
# we could do anything we want with the image here
# for now, we'll blur using a median blur
cv.Smooth(cv_image, cv_image, smoothtype=cv.CV_MEDIAN, param1=31, param2=0, param3=0, param4=0)
# show the image
cv.ShowImage("image_view", cv_image)
cv.WaitKey(3)
if __name__ == '__main__':
image_blur()
try:
rospy.spin()
except KeyboardInterrupt:
print "Shutting down"
cv.DestroyAllWindows()
|
d0ed36ef8221058b53e455d55671ab4ab7b7cf89 | vaibhavranjith/Heraizen_Training | /Assignment1/Q45.py | 169 | 3.890625 | 4 | n=int(input('Enter a number:\n'))
sum=n
while sum>9:
sum=0
while n>0:
sum+=n%10
n=n//10
n=sum
print(f"The single digit sum is {sum}") |
5ea9b97c89f3c023ccaa36fae171c42238300aed | gibson1395/CS0008-f2016 | /Chapter 3 Exercise 1.py | 529 | 4.15625 | 4 | number = int(input('Enter a number between 1 and 7: '))
if number == 1:
print('The day of the week is Monday')
elif number == 2:
print('The day of the week is Tuesday')
elif number == 3:
print('The day of the week is Wednesday')
elif number == 4:
print('The day of the week is Thursday')
elif number == 5:
print('The day of the week is Friday')
elif number == 6:
print('The day of the week is Saturday')
elif number == 7:
print('The day of the week is Sunday')
else:
print('Invalid number entry') |
2b8bfaa0dc8dfa96660d67a04db47a383c548c39 | ajeet2808/learn_py | /1essentials/ch3/a10lists.py | 1,259 | 4.65625 | 5 | # list starts with an open square bracket and ends with a closed square bracket
number = [] #empty list
numbers = [10, 5, 7, 2, 1]
# The elements inside a list may have different types. Some of them may be integers, others floats, and yet others may be lists.
mixed = ["Some string", 10, 10.5, True, [1,"a"]]
# Indexing lists
# starts with index zero
numbers = [10, 5, 7, 2, 1]
print("Original list content:", numbers) # Printing original list content.
numbers[0] = 111
print("New list content: ", numbers) # Current list content.
# Accessing list content
print(numbers[0])
print(numbers)
# The len() function
print(len(numbers))
# Removing elements from a list
# Any of the list's elements may be removed at any time - this is done with an instruction named del (delete). Note: it's an instruction, not a function.
del numbers[1]
print(len(numbers))
print(numbers)
# Negative indices are legal
# An element with an index equal to -1 is the last one in the list.
print(numbers[-1])
# Adding elements to a list: append() and insert()
# list.append(value)
# list.insert(location, value)
numbers.insert(1, 333)
print(numbers) #[111, 333, 7, 2, 1]
#for with list
my_list = [10, 1, 8, 3, 5]
total = 0
for i in my_list:
total += i
print(total) |
ab9a1d60d27384bb11ea45b4db9f71696499a23b | saurabh1907/leetcode-programming | /src/main/leetcode/detect_capital.py | 502 | 3.6875 | 4 | class Solution(object):
def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
if word.upper() == word or word.lower() == word:
return True
else:
word_first = word[0:1]
word_rest = word[1::]
if word_first == word_first.upper() and word_rest == word_rest.lower():
return True
else:
return False
s= Solution()
print(s.detectCapitalUse("ABCD")) |
d9521293fc036142297d102303e11d54e4939d19 | parvathy25/assignment-2 | /que3.py | 205 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 24 13:27:46 2020
@author: HP
"""
def sum_list(items):
sum = 0
for x in items:
sum += x
return sum
print(sum_list([1,2,4,8])) |
36ce87ab5be547f2e307a2016bc4f9aea41b815d | YouFool/python-bible | /hello_you.py | 346 | 4.1875 | 4 | name = input("What is your name? ")
print(name)
age = input ("What is your age?")
print(age)
city = input ("What is your city?")
print(city)
love = input ("What you love doing?")
print("=" * 30)
string = "Your name is {} and you are {} years old. You live in {} and you love {}"
output = string.format(name, age, city, love)
print(output)
|
5e06d088fe71986b5530ee0d1bee01960eea1953 | Dyonn/Euler_Project | /euler17.py | 777 | 3.59375 | 4 | import time
start=time.time()
one =191*3
two =190*3
three =190*5
four =190*4
five =190*4
six =190*3
seven =190*5
eight =190*5
nine =190*4
ten =10*3
eleven =10*6
twelve =10*6
thirteen =10*8
fourteen =10*8
fifteen =10*7
sixteen =10*7
seventeen=10*9
eighteen =10*8
nineteen =10*8
twenty =100*6
thirty =100*6
forty =100*5
fifty =100*5
sixty =100*5
seventy =100*7
eighty =100*6
ninety =100*6
hundred =900*7
xand =891*3
thousand =1*8
ans=one+two+three+four+five+six+seven+eight+nine+ten+eleven+twelve+thirteen+fourteen+fifteen+sixteen+seventeen+eighteen+nineteen+twenty+thirty+forty+fifty+sixty+seventy+eighty+ninety+hundred+xand+thousand
print(ans,time.time()-start," seconds")
|
44e79bf6525082354c956837514f802fcde9414c | jlucasldm/ufbaBCC | /2021.2/linguagens_formais_e_automatos/listas/semana_13/leitura_multipla.py | 554 | 3.5 | 4 | def solucao(sequence, op):
count = 0
r = 0
for i in sequence:
if i == 'W' and r != 0:
count += 2
r = 0
elif i == 'W' and r == 0:
count += 1
elif i == 'R':
r += 1
if r == op:
count += 1
r = 0
if r != 0:
count += 1
return count
while 1:
try:
sequence = input()
op = int(input())
print(solucao(sequence, op))
except EOFError:
break
|
3ec22d8a57271bca153a3225e78d8a918661c479 | cehan-Chloe/Lintcode | /096PartitionList.py | 845 | 3.78125 | 4 | """
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list.
@param x: an integer
@return: a ListNode
"""
def partition(self, head, x):
if head is None:
return head
dummyHead1 = ListNode(0)
p1 = dummyHead1
dummyHead2 = ListNode(0)
p2 = dummyHead2
while head is not None:
if head.val < x:
p1.next = head
p1 = p1.next
else:
p2.next = head
p2 = p2.next
head = head.next
p2.next = None #reason? if no this statement there would cause an error
p1.next = dummyHead2.next
return dummyHead1.next
|
1e7538049e1f8a5636330337e3bb052331039a52 | seahrh/coding-interview | /src/branchbound/zero_one_knapsack.py | 3,916 | 3.8125 | 4 | """
0/1 Knapsack Problem
======================
Given weights and values of N items, put these items in a knapsack of capacity C
to get the maximum total value in the knapsack.
You cannot divide an item, either pick the whole item or don’t pick it (0-1 property).
A single solution is expressed as an boolean array that indicates whether the item is present in the knapsack.
Find all solutions.
SOLUTION: Least cost branch and bound
LC BB seeks the lowest cost so turn the problem into minimization with negative values.
Time O(2^N lg 2^N): expand almost all nodes in worst case. Heap insert time is O(lg N).
Space O(2^N): state space tree as min-heap.
Based on https://www.youtube.com/watch?v=yV1d-b_NeK8
"""
from heapq import heappush, heappop
from typing import NamedTuple, List, Tuple, Set, Union
Numeric = Union[int, float]
class Node(NamedTuple):
cost: float
upper: float
weight: float
partial: Tuple[bool, ...]
class LeastCostTree:
def __init__(
self,
capacity: Numeric,
weights: List[Numeric],
values: List[Numeric],
best_upper: float = 0,
):
self.capacity = capacity
self.weights = weights
self.values = values
self.best_upper = best_upper
self.min_heap: List[Node] = []
def __len__(self):
return len(self.min_heap)
def push(self, partial: List[bool]) -> None:
cost: float = 0
upper: float = 0
weight: float = 0
for i in range(len(self.weights)):
must_include = False
if i < len(partial):
if not partial[i]: # item is not in the bag
continue
must_include = True
if weight + self.weights[i] > self.capacity:
# solution is not feasible as the item cannot fit in the bag
if must_include:
return
remainder = self.capacity - weight
# take fraction: fill remaining capacity with "price per pound" of current item
cost -= self.values[i] / self.weights[i] * remainder
break
weight += self.weights[i]
upper -= self.values[i]
cost = upper
# at least one item is picked
if upper > self.best_upper and any(partial):
return
if upper < self.best_upper:
self.best_upper = upper
node = Node(partial=tuple(partial), weight=weight, cost=cost, upper=upper)
heappush(self.min_heap, node)
def pop(self) -> Node:
return heappop(self.min_heap)
def __repr__(self):
return f"""{self.__class__.__name__}(
best_upper={self.best_upper},
min_heap={repr(self.min_heap)},
capacity={self.capacity}
)
"""
def knapsack(
capacity: Numeric, weights: List[Numeric], values: List[Numeric]
) -> Set[Tuple[bool, ...]]:
if len(weights) == 0:
raise ValueError("Weights array must not be empty")
if len(values) == 0:
raise ValueError("Values array must not be empty")
if len(weights) != len(values):
raise ValueError("Both weights and values arrays must have equal length")
tree = LeastCostTree(capacity, weights, values)
tree.push(partial=[True])
tree.push(partial=[False])
candidates: Set[Node] = set()
while len(tree) != 0:
# get the least cost node
node: Node = tree.pop()
if len(node.partial) == len(weights):
candidates.add(node)
continue
partial = list(node.partial)
tree.push(partial=partial + [True])
tree.push(partial=partial + [False])
res: Set[Tuple[bool, ...]] = set()
for c in candidates:
if c.upper == tree.best_upper:
res.add(c.partial)
return res
|
a0110e545f3908f1dd24072d746fed76c1388ebb | Zed-chi/Skillsmart_func_python | /fp_task6.py | 1,005 | 3.734375 | 4 | """
State Monad
Пример с покупками
есть:
- условный человек = {корзина, счет}
- перечень продуктов = []
- условный результат покупок (человек, кол.покупок)
"""
from pymonad import curry, State, unit
@curry
def buy(what, to):
@State
def state_computation(old_state):
if what in items and to["money"]-items[what]>0:
to["items"].append(what)
to["money"]-=items[what]
return (to, old_state + 1)
else:
return (to,old_state)
return state_computation
items = {"apples":70,
"wine":300,
"milk":80,
"chips":100
}
user = {"items":[],"money":2000}
shoping = unit(State, user) >> buy("apples") >> buy("wine") >> buy("chips") >> buy("dasda")
print("Вы купили {0[1]} товар(а) - {0[0][items]}, у вас осталось {0[0][money]} монет"
.format(shoping(0)))
|
b690d637454ff0b623d063589e86f4f3ab0dab6b | isZengwen/PythonNotes | /timeit_demo.py | 565 | 3.59375 | 4 | import timeit
#测量代码块的执行时间
c ='''
sum=[]
for i in range(0,1000):
sum.append(i)
'''
t1 = timeit.timeit(stmt="[i for i in range(0,1000)]",number=100000)
t2 = timeit.timeit(stmt=c,number=100000)
print(t1,t2)
print("#"*20)
#测量不含参数函数的执行时间
def doIt():
n = 3
for i in range(n):
print(i)
t3 = timeit.timeit(stmt=doIt,number=10)
print(t3)
#测量含参数的函数执行时间
s = '''
def doIt(n):
for i in range(n):
pass
'''
t4 = timeit.timeit("doIt(n)",setup=s+"n=3",number=100000)
print(t4) |
89fe411b071b5a5d1b7f169efe3dcb71b5750c81 | JAKER3/Dice-Game | /Dice Game/Dice Game.py | 8,415 | 3.5 | 4 | import random
import time
import os
import uuid
import hashlib
import operator
def see_leaderboard():
see = True
while see == True:
reply = input("Would you like to see the whole leader board, enter y/n or \nq to completely quit the game: ")
if reply == 'q':
assure = input("Press enter to quit or n to go back: ")
if assure == 'n':
print("Returning...")
else:
print("Quitting game...")
exit()
if reply == 'y':
board = open('Winner.txt', 'r')
file_contents = board.read()
print(file_contents)
break
elif reply == 'n':
break
else:
print("Error, please enter y or n!")
i = 0
Player1Points = 0
Player2Points = 0
Winner_Points = 0
user1 = ''
user2 = ''
def hash_string(myString): # used to make the passwords unreadable in the txt file, to keep account protected
salt = uuid.uuid4().hex
return hashlib.sha256(salt.encode() + myString.encode()).hexdigest() + ':' + salt
def check_hashes(hashed_string, myString): # used to make the passwords readable for the code so it can chaeck if the password entered mataches
new_string, salt = hashed_string.split(':')
return new_string == hashlib.sha256(salt.encode() + myString.encode()).hexdigest()
def login(playerNo): #defines login
reg = False
#Get list of users
lines = ()
try:
file = open('Login.txt', 'r') # open file
lines = list(file) # read all lines in file
file.close()
except IOError:
ab = open('Login.txt', 'w')
ab.close()
UserList = {}
#Build a dictionary
for line in lines:
line = line.replace('\n', '').replace('\r', '') # uses this to format so the system can check user credentials later
if line and line.find(","):
username, password = line.split(',') # so the code knows which side is the password and username
if username.lower() in UserList:
print("Duplicate Registered User detected") # checks if more than 1 user has the same name in the file
else:
UserList.update( {username.lower() : password} )
while reg == False:
username1 = input("Player " + playerNo + ", Enter your username:").lower()
if username1.lower() in UserList:
password1 = input("Enter Password: ")
if check_hashes(UserList[username1.lower()], password1): # uses check_hashes to make the password readable
reg = True
return(username1.lower())
else:
print("password doesnt match registered user, choose a differnt username or try password again")
else:
register = input("Username " + username1 + " Not found would you like to register for the game yet? y/n ") # if username doesn't exist it prompts user to make an account
if register == 'y':
ab = open('Login.txt', 'a')
passwrd = input("Now enter a password: ")
ab.write(username1.lower()) # writes credentials to the file
ab.write(',')
ab.write(hash_string(passwrd))
ab.write(os.linesep)
ab.close()
reg = True
return(username1.lower())
def roll(myUser, mytotal, tied): # defines roll
input('\nPress enter for your turn :') # asks user to press enter to roll their dice
if tied:
die1 = random.randint(1,6)
dietotal = mytotal + die1
print(myUser, 'you rolled a',die1,'in you tied challenge. Your new total: ', dietotal)
return(dietotal)
else:
die1 = random.randint(1,6) # rolls both the dice
die2 = random.randint(1,6)
die3 = 0
if die1 == die2: # checks if the user rolled a double
die3 = random.randint(1,6)
dietotal = mytotal + die1 + die2 + die3
if die3 > 0: # checks if die3 was rolled, if it was it outputs the following messages
time.sleep(0.2)
print(myUser, 'you rolled a',die1,'and a', die2, ', You rolled a double!')
time.sleep(0.2)
print(myUser, 'Your bonus roll was', die3, 'Extra roll of the dice. Your new total: ', dietotal)
else:
time.sleep(0.2)
print(myUser, 'you rolled a',die1,'and a', die2, 'making your new total: ', dietotal)
if dietotal % 2 == 0: # checks to see if the total is odd or even
dietotal += 10 # This is even so it adds 10
time.sleep(0.2)
print(myUser, 'your total is even so you get bonus 10 points making your score: ', dietotal)
else:
if (dietotal - 5) < 0: # This is odd, it checks to see if it will go under 0, if so it will make it 0
time.sleep(0.2)
print(myUser, 'your total is odd so you lose', dietotal, 'making your score zero')
dietotal = 0
else:
dietotal -= 5 # Odd so it takes 5 as it knows it will not go under 0
time.sleep(0.2)
print(myUser, 'your total is odd so you lose 5 points making your score: ', dietotal)
return(dietotal)
see_leaderboard()
user1 = login("1") # makes the value of the variable
if user1 != '':
user2 = login("2") # makes the value of the second variable
else:
print("No")
print("Users ", user1, user2)
for i in range(0,5): # rolls for both players 5 times
Player1Points = roll(user1,Player1Points,0)
time.sleep(1)
Player2Points = roll(user2,Player2Points,0)
time.sleep(1)
#Player1Points = 10, this was used to test the draw system at the end of the game
#Player2Points = 10
while Player1Points == Player2Points: # checks if the players are tied and enters game to decide winner
time.sleep(0.2)
print('Tied scores entering roll off, highest roll wins')
Player1Points = roll(user1,Player1Points,1)
time.sleep(1)
Player2Points = roll(user2,Player2Points,1)
time.sleep(1)
if Player1Points>Player2Points: #checks who the winner is and defines the varibles for the leader board
Winner_Points = Player1Points
winner_User = user1
winner = (Winner_Points, user1)
elif Player2Points>Player1Points:
Winner_Points = Player2Points
winner = (Winner_Points, user2)
winner_User = user2
time.sleep(0.2)
print('Well done,', winner_User,'you won with',Winner_Points,'Points') # oututs winner for users to see
#winner = (Winner_Points, winner_User)
line = ()
try:
file = open('Winner.txt', 'r')
lines = list(file)
file.close()
except IOError:
ab = open('Winner.txt', 'w')
ab.close()
HighScoreTable = {}
#Build a dictionary
for line in lines:
line = line.replace('\n', '').replace('\r', '')
if line and line.find(","):
score, user = line.split(',')
if user in HighScoreTable: # checks if the user is in the leader board more than once
print("Duplicate User detected in high score table")
else:
HighScoreTable.update( {user : int(score)} )
if winner_User in HighScoreTable: # checks if the user is already in the file
if HighScoreTable[winner_User] <= Winner_Points: # checks if their new score is larger than their old score
HighScoreTable.update( {winner_User : Winner_Points} ) # if it is then it updates the file with the new score
else:
HighScoreTable.update( {winner_User : Winner_Points} )
#Update file
f = open('Winner.txt', 'w')
for usr, val in HighScoreTable.items(): # formats the file with the information
f.write(str(val))
f.write(',')
f.write(str(usr))
f.write(os.linesep)
f.close()
#Print high scores
HighScore_by_value = sorted(HighScoreTable.items(), key=operator.itemgetter(0),reverse=True)# sorting the txt file by score
d = sorted(HighScoreTable.items(),key=lambda x: (x[1], x[0]), reverse=True) # Value then Key
print("\nTop 5 Scores")
topcnt = 0
for usr, val in d:
topcnt += 1
print(val,usr)
if topcnt > 4: # outputs top users until it reaches 5
break
|
3227ce5391684687202d137a73127546b220c12d | iampaavan/Pure_Python | /Exercise-13.py | 281 | 4.125 | 4 | import calendar
"""Write a Python program to print the calendar of a given month and year."""
y = int(input(f"Enter the year: "))
m = int(input(f"Enter the month: "))
month = calendar.month(y, m)
print(f"Year and Month:{month}")
c = calendar.monthrange(2019, 4)
print(c)
|
0a6ab33f55d7ab380d94a25d89c0effb11cb7ca0 | prichakrabarti/python_guided_project | /q01_create_class/build.py | 1,904 | 4.25 | 4 | import math
class complex_number:
'''The complex number class.
Attributes:
attr1 (x): Real part of complex number.
attr2 (y): Imaginary part of complex number.
'''
#There are some functions you want to call as soon as you initialize my class- so as soon as I call the class, the thing with __init__ is called
class complex_number():
def __init__(self, real, imag):
self.real= real
self.imag=imag
def __str__(self):
if self.imag<0:
return '{0}-i{1}'.format(self.real,abs(self.imag))
else:
return '{0}+i{1}'.format(self.real,abs(self.imag))
#Method overriding
def __add__(self,other):
real_result= self.real+other.real
imaginary_result= self.imag+other.imag
result= complex_number(real_result,imaginary_result)
return result
def __sub__(self,other):
real_result= self.real-other.real
imaginary_result= self.imag- other.imag
result = complex_number(real_result,imaginary_result)
return result
def abs(self):
return math.sqrt(self.real**2+self.imag**2)
def __mul__(self,other):
real_result = self.real*other.real- self.imag*other.imag
imaginary_result= self.imag*other.real+ self.real*other.imag
result= complex_number(real_result, imaginary_result)
return result
def __truediv__(self,other):
#(a+bi)/(c+di)=(ac+bd)/c2+d2 + i(bcâad )/ c2+d2
num1 = ((self.real*other.real)+(self.imag*other.imag))
deno = (other.real**2) + (other.imag**2)
num2 = ((self.imag*other.real)-(self.real*other.imag))
return num1/deno,num2/deno
def conjugate(self):
return self.real+ -self.imag
def argument(self):
result= math.degrees(math.atan(self.imag/self.real))
return result
|
7e7a2e4a236ab71bad2d563a454191a68e14cba9 | dchang-pragma/cloudbit | /python3-tutorial/class_rabbit.py | 890 | 4.0625 | 4 | class Rabbit:
"""A simple example class"""
genus='Oryctolagus'
specie='cuniculus'
#tricks=[] #class variable
def __init__(self, name, breed, color):
self.name = name
self.breed = breed
self.color = color #instance variable
self.tricks = [] # creates a new empty list for each dog
def add_trick(self, trick):
self.tricks.append(trick)
bunny1 = Rabbit('Mocha', 'Holland Lop', 'chestnut')
bunny2 = Rabbit('Tofu', 'Netherlands Dwarf', 'white')
bunny3 = Rabbit('Sesame', 'Netherlands Dwarf', 'black')
# bunny4 = Rabbit('Fluffy')
# bunny5 = Rabbit('Ray')
# bunny6 = Rabbit('Brownie')
# bunny1.breed = 'Holland Lop'
bunny1.add_trick('play cute')
bunny2.add_trick('growl gu gu')
#print ('name of bunny 1 is', bunny1.name, '.','he can', bunny1.tricks[0])
#print (bunny2.tricks)
# print(bunny3.name)
# print(bunny1.breed)
|
7e4e274e60a51173e947e0febc15873e65747c47 | Toadstool/LearnPython | /Lab1/z3.py | 304 | 3.5 | 4 | from random import randrange
r = randrange(100)
u = int(input("podaj liczbe od 1 do 100"))
while(r!=u):
if(u>r):
print("za duzo")
else:
print("za malo")
i = input("sprobuj")
if(i=="q"):
break
u = int(i)
if(r==u):
print("zgadles")
|
f56b07726849a4ce0d96e8ea37b512420e9b9a0f | c-eng/holbertonschool-higher_level_programming | /0x0B-python-input_output/2-read_lines.py | 552 | 4.125 | 4 | #!/usr/bin/python3
"""Read n lines function
"""
def read_lines(filename="", nb_lines=0):
"""Reads n lines from a file
Args:
filename (str): filename/filepath
nb_lines (int): numbr of lines to read
"""
count = 0
if type(nb_lines) is int and type(filename) is str:
with open(filename) as fyle:
while (count < nb_lines or nb_lines <= 0):
read = fyle.readline()
if read == '':
break
print(read, end='')
count += 1
|
6918347c1d0b35a227edcc4b95dfa0db17a984ae | RatnamDubey/DataStructures | /Educative/Data Structures for Coding Interviews in Python/Challenge 1: Remove Even Integers from List.py | 425 | 3.84375 | 4 | ##########################################
### Remove the Even Integers from the List
###########################################
class operations_maths():
def remove_even(self,list):
newlist =[]
for values in list:
if values % 2 != 0:
newlist.append(values)
return newlist
c = operations_maths()
l = [10,23,45,89,20,12,13,16.17,10]
print(c.remove_even(l)) |
af884e44be7c39502058459bb629d9233f9c05d1 | catr1ne55/stepik_python_basics | /1/1.2.1.py | 117 | 3.609375 | 4 | objects = [1, 2, 1, 2, 3]
ans = []
for obj in objects:
if obj not in ans:
ans.append(obj)
print(len(ans)) |
aa64df827e7c301db3613a65a72b1009347aff17 | TheNite/Python3-BootCamp | /Milestone Project 1/tictactoe.py | 5,577 | 4.1875 | 4 | """
Play tic tac toe with a friend
"""
tic_tac_toe_board = {
"upper_left": " ",
"upper_middle": " ",
"upper_right": " ",
"middle_left": " ",
"middle_middle": " ",
"middle_right": " ",
"bottom_left": " ",
"bottom_middle": " ",
"bottom_right": " ",
}
player_piece = {
"player1": "",
"player2": "",
}
def display_board():
print(
f'{tic_tac_toe_board["upper_left"]} | {tic_tac_toe_board["upper_middle"]} | {tic_tac_toe_board["upper_right"]}')
print('-' * 10)
print(
f'{tic_tac_toe_board["middle_left"]} | {tic_tac_toe_board["middle_middle"]} | '
f'{tic_tac_toe_board["middle_right"]}')
print('-' * 10)
print(
f'{tic_tac_toe_board["bottom_left"]} | {tic_tac_toe_board["bottom_middle"]} | '
f'{tic_tac_toe_board["bottom_right"]}')
def update_board(player, choice):
choices = {
1: "upper_left",
2: "upper_middle",
3: "upper_right",
4: "middle_left",
5: "middle_middle",
6: "middle_right",
7: "bottom_left",
8: "bottom_middle",
9: "bottom_right",
}
if tic_tac_toe_board[choices[choice]] == " ":
tic_tac_toe_board[choices[choice]] = player_piece[player]
return True
else:
return False
def check_winner():
if tic_tac_toe_board["upper_left"] == tic_tac_toe_board["middle_left"] == tic_tac_toe_board["bottom_left"] != " ":
return [tic_tac_toe_board["upper_left"], True]
elif tic_tac_toe_board["upper_middle"] == tic_tac_toe_board["middle_middle"] == tic_tac_toe_board[
"bottom_middle"] != " ":
return [tic_tac_toe_board["upper_middle"], True]
elif tic_tac_toe_board["upper_right"] == tic_tac_toe_board["middle_right"] == tic_tac_toe_board[
"bottom_right"] != " ":
return [tic_tac_toe_board["upper_right"], True]
elif tic_tac_toe_board["upper_left"] == tic_tac_toe_board["upper_middle"] == tic_tac_toe_board[
"upper_right"] != " ":
return [tic_tac_toe_board["upper_left"], True]
elif tic_tac_toe_board["middle_left"] == tic_tac_toe_board["middle_middle"] == tic_tac_toe_board[
"middle_right"] != " ":
return [tic_tac_toe_board["middle_left"], True]
elif tic_tac_toe_board["bottom_left"] == tic_tac_toe_board["bottom_middle"] == tic_tac_toe_board[
"bottom_right"] != " ":
return [tic_tac_toe_board["bottom_left"], True]
elif tic_tac_toe_board["bottom_left"] == tic_tac_toe_board["middle_middle"] == tic_tac_toe_board[
"upper_right"] != " ":
return [tic_tac_toe_board["bottom_left"], True]
elif tic_tac_toe_board["bottom_right"] == tic_tac_toe_board["middle_middle"] == tic_tac_toe_board[
"upper_left"] != " ":
return [tic_tac_toe_board["bottom_right"], True]
else:
return [False, False]
def user_piece_choice(player):
valid_inputs = ["x", "o"]
choice = input(f"Please Choose X or O for {player}: ")
if choice.lower() in valid_inputs:
if choice.lower() == "x":
player_piece["player1"] = choice.upper()
player_piece["player2"] = "O"
return True
else:
player_piece["player1"] = choice.upper()
player_piece["player2"] = "X"
return True
else:
print("Please Choose X or O")
return False
def choose_move(player, valid_choice=False):
if valid_choice:
player_choice = input(f"{player}, Which square would you like to play? 1-9: ")
try:
player_choice = int(player_choice)
except:
print("Please enter a number 1-9")
if player_choice in range(1, 10):
return update_board(player, player_choice)
def clear_board_display():
print("\n" * 30)
def get_key(player_piece_choice):
for key, value in player_piece.items():
if value == player_piece_choice:
return key
def display_winner(player):
player = get_key(player)
if winner:
clear_board_display()
print(f'{player} has won the game!')
display_board()
return True
return False
def check_for_full_board():
count = 0
for value in tic_tac_toe_board.values():
if value != " ":
count += 1
if count == 9:
print("No Winner!")
return True
else:
return False
print("Welcome to Tic-Tac-Toe")
display_board()
while True:
player, winner = check_winner()
if winner:
display_winner(player)
break
if check_for_full_board():
break
valid_input = user_piece_choice("player1")
if valid_input:
while True:
player, winner = check_winner()
if check_for_full_board():
break
if winner:
break
player1_valid = choose_move("player1", True)
if player1_valid:
display_board()
while True:
player, winner = check_winner()
if check_for_full_board():
break
if winner:
break
player2_valid = choose_move("player2", True)
if player2_valid:
display_board()
break
else:
print("Please choose a valid Square!")
continue
else:
print("Please choose a valid Square!")
continue
|
23ea054cc4481b2515a4475d8668bf3f5dd41f23 | bouzidnm/python_intro | /notes_20Feb2019.py | 1,752 | 4.4375 | 4 | ## Notes for 20 Feb 2019
## Lists, Indexing, Slicing
## Lists
## Square brackets, are ordered and changeable
nums = [1, 2, 3, 4, 5] #same element types, int
fruit = ['apple', 'banana', 'strawberry'] #same element types, str
random = ['bob', 2, 3.14, True]
# Review from last week
type(nums)
# it's a class list
## Indexing
## data going forward always start at 0
## data doing backwards always start at -1
#variable_name[index]
s = "PYTHON"
# index the string s
s[0] #first letter, p
s[-1] #last letter, n
# Indexing exercises
s = 'hello world!'
# first letter, h
s[0]
s[-12]
s[-len(s)]
# get length of string
len(s)
s[len(s)-1] # forwards, get end of string, '!'
s[-len(s)] # backwards, get beginning of string, 'h'
# double indexing; usually won't see anything more than triple indexing
# add another set of brackets
# get 'a' in 'apple'
fruit[0][0]
# indexing lists
animals = ['dog', 'cat', 'bird', 'fish']
animals[2] # grabs 'cat'
animals[2][1] # grabs 'a' in 'cat'
## Slicing
## grab multiple values with a colon
## Format: variable_name[index : index]
## grabs everything up until, BUT NOT INCLUDING, the second index
# Slicing strings
s = 'hello world!'
s[0:2] # grabs the first 2 letters
s[1:5] # grabs 'ello'
s[1:6] # grabs 'ello ' with space
s[3:] # grabs everything from 'l' to end, s[3:], 'lo world!'
# Slicing lists
fruit = ['apple', 'banana', 'strawberry', 'orange']
## Lists within lists
## lists can have other lists as elements
family = [['bob', 21], ['dave', 24], ['emma', 19], ['jen', 22]]
family[0][1] # bob's age
family[0][0][0] # 'b' in 'bob', shouldn't do more than triple
## another example
lol = [['dog', 'cat', 'bird'], ['car', 'boat', 'plane'], ['red', 'yellow', 'green']]
## ecology for a crowded plant, LMM and R |
240adeb28c223fd42ce8f5b99d4f630b85550b5a | tonylattke/hsb_gesture_recognition | /oldVersions/HandTrackingOnly/Triangle.py | 1,285 | 3.5 | 4 | # HSB - Computational Geometry
# Professor: Martin Hering-Bertram
# Authors: Filips Mindelis
# Tony Lattke
from numpy import sqrt, arccos, rad2deg
class Triangle:
cent = []
rect1 = []
rect2 = []
# Contructor
def __init__(self, cent, rect1, rect2):
self.cent = cent # tupleToList(cent)
self.rect1 = rect1 # tupleToList(rect1)
self.rect2 = rect2 # tupleToList(rect2)
# Calculates the angle between two lines
def angle(self):
v1 = (self.rect1[0] - self.cent[0], self.rect1[1] - self.cent[1])
v2 = (self.rect2[0] - self.cent[0], self.rect2[1] - self.cent[1])
dist = lambda a: sqrt(a[0] ** 2 + a[1] ** 2)
angle = arccos((sum(map(lambda a, b: a * b, v1, v2))) / (dist(v1) * dist(v2)))
angle = abs(rad2deg(angle))
return angle
# def averagePoint(pointA, pointB):
# x = (pointA[0] + pointB[0]) / 2
# y = (pointA[1] + pointB[1]) / 2
# return [x, y]
# def obtainCenterOfHand(triangles):
# center = [0, 0]
# for triangle in triangles:
# center[0] += triangle.defect[0]
# center[1] += triangle.defect[1]
# if len(triangles) > 0:
# center[0] /= len(triangles)
# center[1] /= len(triangles)
# else:
# center = [-1,-1]
# return center
|
e3e5764e25d6a10d2121c64f4f4d870805a7b6c3 | abhi7542/hello | /abhi kr.py | 391 | 3.671875 | 4 | print('hello world')
a ='abhishek kumar'
b =22
print(b)
print(a)
'''yrfrf6yurfwy6rfy'''
print('heappy learning \n \nwelcom to python')
ac=10
bc=['abhishek','5']
print(ac,bc)
a,b,c=20,30,40
print(a,b,c)
f=10.45
print(type(f))
print(bc)
bc[1]='prince'
print(bc)
print(c>a)
print(4*567)
print(40%7)
today='wednesday'
yoga_day='sunday'
print(yoga_day is today)
print(today)
|
6b650deb24d3cdc9656de68240a12db934ca73b3 | AntaresT/PyRP19 | /RegEx/python_brasil_19_talk-master/arquivos/1.py | 507 | 3.84375 | 4 | # -*- coding: utf-8 -*-
import re
# Ver todas as funções e constantes
# print(dir(re))
# findal sempre retorna uma lista com string do pattern que foi encontrado
from re import findall
print(re.findall("f", "fff"))
result = re.findall("xu", "xu")
print(type(result), len(result))
print(result)
result = re.findall("xu", "xuxu")
print(type(result), len(result))
print(result)
# Como é feita a leitura?
# ele nao volta, le somente 1 - 'ff' | faz a leitura e descarta
print(re.findall("ff", "fff"))
|
72ba8dca05d9a480f57dc1db308cd9923f2d3d8e | hancse/model_rowhouse | /House model_2R2C_Python/house_model/configurator.py | 6,553 | 3.6875 | 4 | """
A certain Python style gives the modules (*.py files) names of a profession:
in this style, the module that encapsulates the parameter configuration can be called
configurator.py
the module performs the following tasks:
1. read the input parameters for the model simulation from a configuration file
"Pythonic" configuration file types are *.ini, *.yml, *.toml and *.json
The *.yml can cope with array parameters. This makes it more useful than the *.ini format
The *.json format can also represent arrays. It is used when the input data comes from a database.
2. convert the input parameters to a dict
3. optionally, convert the dict to a dataclass object
4. get additional parameters from NEN5060
5. perform calculations to prepare for ODE integration
"""
import yaml
"""
The predefined variables are now defined in a configuration file
All parameters read from configuration (*.yml) file
"""
def load_config(config_name: str):
with open(config_name) as config_file:
hp = yaml.safe_load(config_file) # hp = house_parameters
return hp
def save_config(hp):
with open("../config2R2C.yml", "w") as config_outfile:
yaml.dump(hp, config_outfile, indent=4)
# Variables from Simulink model, dwelling mask (dwelling mask???????)
# Floor and internal walls construction.
# It is possible to choose between light, middle or heavy weight construction
"""
# Facade construction
# It is possible to choose between light, middle or heavy weight construction
the parameters c_internal_mass, th_internal_mass and rho_internal_mass
c_facade, th_facade and rho_facade are now lists
the indices to these lists are N_internal_mass an N_facade
"""
# It is assumed that furniture and the surface part of the walls have the same temperature
# as the air and the wall mass is divided between the air and wall mass.
# Thus, the capacity of the air node consists of the air capacity,
# furniture capacity and capacity of a part of the walls.
# Appendix I presents the coefficients in the dwelling model.
# In the resistance Rair_outdoor the influence of heat transmission through the outdoor walls
# and natural ventilation is considered.
def calculateRC(hp: dict):
"""
Args:
hp:
Returns:
Rair_wall :
Cwall :
Rair_outdoor :
Cair :
"""
# assignment to local variables from hp: dict
# Envelope surface (facade + roof + ground) [m2]
A_facade = hp['dimensions']['A_facade']
# Floor and internal walls surface [m2]
A_internal_mass = hp['dimensions']['A_internal_mass']
# Internal volume [m3]
V_dwelling = hp['dimensions']['V_dwelling']
# Envelope thermal resistance, R-value [m2/KW]
Rc_facade = hp['thermal']['Rc_facade']
# Window thermal transmittance, U-value [W/m2K]
Uglass = hp['thermal']['U_glass']
CF = hp['ventilation']['CF']
# Ventilation, air changes per hour [#/h]
n = hp['ventilation']['n']
# Facade construction
# Light_weight = 0 / Middle_weight = 1 / Heavy_weight = 2
N_facade = hp['construction']['N_facade']
# Floor and internal walls construction
N_internal_mass = hp['construction']['N_internal_mass']
# Initial parameters file for House model
##Predefined variables
rho_air = hp['initial']['rho_air'] # density air in [kg/m3]
c_air = hp['initial']['c_air'] # specific heat capacity air [J/kgK]
alpha_i_facade = hp['initial']['alpha_i_facade']
alpha_e_facade = hp['initial']['alpha_e_facade']
alpha_internal_mass = hp['initial']['alpha_internal_mass']
c_internal_mass = hp['thermal']['c_internal_mass'][N_internal_mass] # Specific heat capacity construction [J/kgK]
th_internal_mass = hp['construction']['th_internal_mass'][N_internal_mass] # Construction thickness [m]
rho_internal_mass = hp['construction']['rho_internal_mass'][N_internal_mass] # Density construction in [kg/m3]
c_facade = hp['thermal']['c_facade'][N_facade] # Specific heat capacity construction [J/kgK]
th_facade = hp['construction']['th_facade'][N_facade] # Construction thickness [m]
rho_facade = hp['construction']['rho_facade'][N_facade] # Density construction in [kg/m3]
A_glass = sum(hp['glass'].values()) # Sum of all glass surfaces [m2]
A_glass -= hp['glass']['g_value']
print(A_glass)
# Volume floor and internal walls construction [m3]
V_internal_mass = A_internal_mass * th_internal_mass
# A_internal_mass: Floor and internal walls surface [m2]
qV = (n * V_dwelling) / 3600 # Ventilation, volume air flow [m3/s],
# n: ventilation air change per hour; V_dwelling : internal volume m3
qm = qV * rho_air # Ventilation, mass air flow [kg/s]
# Dwelling temperatures calculation
# Calculation of the resistances
Rair_wall = 1.0 / (A_internal_mass * alpha_internal_mass) # Resistance indoor air-wall
U = 1.0 / (1.0 / alpha_i_facade + Rc_facade + 1 / alpha_e_facade) # U-value indoor air-facade
Rair_outdoor = 1.0 / (A_facade * U + A_glass * Uglass + qm * c_air) # Resistance indoor air-outdoor air
# Calculation of the capacities
Cair = rho_internal_mass * c_internal_mass * V_internal_mass / 2.0 + rho_air * c_air * V_dwelling # Capacity indoor air + walls
Cwall = rho_internal_mass * c_internal_mass * V_internal_mass / 2.0 # Capacity walls
return Rair_wall, Cwall, Rair_outdoor, Cair
# Time base on 1 hour sampling from NEN
"""
time = Irr.qsunS[0]
# time = first row of Irr.qsunSouth (time axis) in seconds [0, 3600, 7200, ...]
print("ID time: ", id(time), ", ID Irr.qsunS[0]: ", id(Irr.qsunS[0]))
the "new" variable time is NOT at the same memory address as
the "old" variable Irr.qsunS[0]!
because the value of the first element of an array is assigned to a scalar (float)
the instruction now has COPIED the variable
this asks for extreme programmer awareness!
# define window surface in m2
# Windows surface [E,SE,S,SW,W,NW,N,NE] [m2]
# -90 (E), -45 (SE), 0 (S), 45 (SW), 90 (W), 135 (NW), 180 (N), 225 (NE)
# Window solar transmittance, g-value
# Calculate Qsolar on window
Qsolar = (Irr.qsunE[1] * hp['glass']['E'] + Irr.qsunSE[1] * hp['glass']['SE'] +
Irr.qsunS[1] * hp['glass']['S'] + Irr.qsunSW[1] * hp['glass']['SW'] +
Irr.qsunW[1] * hp['glass']['W'] + Irr.qsunNW[1] * hp['glass']['NW'] +
Irr.qsunN[1] * hp['glass']['N'] + Irr.qsunNE[1] * hp['glass']['NE']) * hp['g_value']
# with input NEN5060, glass and g_value, qsun can give a single result Qsolar
""" |
964743dda3bcca61966097b4af145a9a7d202d96 | JonyHM/BOT-DepreciacaoVeicular | /CalculaDepreciacao.py | 1,491 | 3.5625 | 4 | # encoding: utf-8
from datetime import datetime
import locale
locale.setlocale(locale.LC_ALL, '')
class CalculaDepreciacao(object):
def __init__(self):
self.ano = 0
self.valorVeiculo = ''
self.anoAtual = datetime.now().year
self.idadeCarro = 0
self.caracteres = 'R$ '
def calcular(self, ano, valor):
self.ano = ano
self.valorVeiculo = valor
if self.ano > self.anoAtual:
self.idadeCarro = 0
self.ano = self.anoAtual
else:
self.idadeCarro = self.anoAtual - self.ano
self.valorVeiculo = self.valorVeiculo.replace(self.caracteres, '')
self.valorVeiculo = locale.atof(self.valorVeiculo)
if self.idadeCarro >= 5:
self.valorVeiculo -= self.valorVeiculo * 0.1
self.valorVeiculo = locale.currency(self.valorVeiculo, grouping=True,symbol=True)
return u'\nSeu veículo valerá, aproximadamente,\n{}'.format(self.valorVeiculo)
## Como seu veículo tem mais de 5 anos, o cálculo de depreciação realizado é
# de -10% do valor atual anualmente
else:
self.valorVeiculo = locale.currency(self.valorVeiculo, grouping=True,symbol=True)
return u'Seu veículo começará a depreciar efetivamente a partir de 5 anos de fabricação (em {})'.format(self.ano + 5)
# return self.valorVeiculo |
86784a8dab74b99064fb2ab93bec56d59f99796a | NihalAnand/practice | /longest_prefix.py | 225 | 3.78125 | 4 | def longest_prefix(s):
n=len(s)
for res in range(n//2,0,-1):
prefix=s[0:res]
suffix=s[n-res:n]
if(prefix==suffix):
return res
return -1
s='xxnihalxx'
print(longest_prefix(s)) |
7948b8a00c4865bf3191171862c32daca2bbda81 | skjaas/oops | /oop/inheritance/in8.py | 1,518 | 4 | 4 | class Calculator:
def addition(self,num1,num2):
self.a=num1
self.b=num2
return (self.a+self.b)
def sub(self,num1,num2):
self.a=num1
self.b=num2
return (self.a-self.b)
def mul(self,num1,num2):
self.a=num1
self.b=num2
return (self.a*self.b)
def div(self,num1,num2):
self.a=num1
self.b=num2
return (self.a/self.b)
def modu(self,num1,num2):
self.a=num1
self.b=num2
return (self.a%self.b)
obj=Calculator()
n=1
while(n==1):
print("1.Add 2.Sub 3.Mul 4.Div 5.Mod 0.End")
choice=int(input(":"))
if (0<choice<6):
a=float(input("Num1:"))
b=float(input("Num2:"))
if choice==1:
print(obj.addition(a,b))
elif choice==2:
print(obj.sub(a,b))
elif choice==3:
print(obj.mul(a,b))
elif choice==3:
print(obj.div(a,b))
elif choice==4:
print(obj.modu(a,b))
else:
print("Process Ending")
n=2
#or
class Calculator:
def __init__(self, a, b):
self.a = a
self.b = b
def add(self):
return self.a + self.b
def sub(self):
return self.a - self.b
def mul(self):
return self.a * self.b
def div(self):
return self.a / self.b
a=float(input(":"))
b=float(input(":"))
obj=Calculator(a, b)
print(obj.add())
print(obj.sub())
print(obj.mul())
print(obj.div())
#homewor
#book class |
5f8c561702d9390267dd0c7930d904d916514754 | ParkMyCar/MoneyManSpiff | /arbitrage/graph.py | 6,558 | 3.640625 | 4 | """
Graph objects used for Money Man Spiff's arbitrage engine
At it's core is a 2D Dictionary aka Dictionary of Dictionaries
Author: Parker Timmerman
"""
from decimal import *
from sys import float_info
from typing import List, Tuple
MAX_FLOAT = float_info.max
class Edge():
""" An edge object to be used for arbitrage """
def __init__(self, xrate, weight, vol, vol_sym, pair, ab, exch, timestamp):
self.xrate = xrate # exchange rate from the market, generally bid or 1/ask
self.weight = weight # edge weight used for neg cycle detection, -log(xrate)
self.vol = vol # volume associated with bid or ask price
self.vol_sym = vol_sym # currency which the volume is in terms of
self.pair = pair
self.ab = ab # ask or buy price
self.exch = exch # echange for which this edge comes from
self.timestamp = timestamp
# Getters and Setters
def getExchangeRate(self):
return self.xrate
def setExchangeRate(self, xrate): # Note: Exchange rate and weight should always be changed together
self.xrate = xrate # because weight is a derivative of exhange rate
def getWeight(self):
return self.weight
def setWeight(self, weight):
self.weight = weight
def getVolume(self):
return self.vol
def setVolume(self, vol):
self.vol = vol
def getVolumeSymbol(self):
return self.vol_sym
def setVolumeSymbol(self, vol_sym):
self.vol_sym = vol_sym
def getPair(self):
return self.pair
def setPair(self, pair):
self.pair = pair
def getAskOrBid(self):
return self.ab
def setAskOrBid(self, ab):
self.ab = ab
def Volume(self):
return (self.vol, self.vol_sym)
def getExchange(self):
return self.exch
def getTimestamp(self):
return self.timestamp
class Graph():
""" A graph data structure represented as a 2D Dictionary"""
def __init__(self):
self.G = {}
def addNode(self, name) -> bool:
""" Add a node to the graph, if the node already exists, return false """
if name in self.G:
print("Node already exists!")
return False
else:
self.G[name] = {}
return True
def addEdge(self, src, dest, xrate, weight, vol, vol_sym, pair, ab, exch, timestamp) -> bool:
""" Add an edge to the graph """
if src not in self.G:
print("Source node ({}) does not exist!".format(src))
return False
if dest not in self.G:
print("Destination node ({}) does not exist!".format(dest))
return False
if dest not in self.G[src]:
self.G[src][dest] = Edge(xrate, weight, vol, vol_sym, pair, ab, exch, timestamp)
elif timestamp > self.G[src][dest].getTimestamp():
# If the given edge is newer than the existing, replace it, no questions asked
self.G[src][dest] = Edge(xrate, weight, vol, vol_sym, pair, ab, exch, timestamp)
return True
elif weight < self.G[src][dest].getWeight():
# An edge already exists with the same timestamp, but we found an edge with a lower weight!
self.G[src][dest] = Edge(xrate, weight, vol, vol_sym, pair, ab, exch, timestamp)
return True
# If we reach here it means the edge we were trying to update is from the same cycle
# and we already had an edge that was cheaper
return False
def getEdge(self, a, b):
""" Get the edge from a to b """
if b not in self.G[a]:
print("Edge between {0} and {1} does not exist!".format(a, b))
return
else:
return self.G[a][b]
def getEdges(self):
""" Get a list of the edges in the graph """
return list([(src, dest, self.G[src][dest]) for src in self.G.keys() for dest in self.G[src].keys()])
def getNodes(self) -> List[str]:
"""" Returns a list of all the nodes in the graph """
return list(self.G.keys())
def getWeights(self) -> List[Tuple[str, str, float]]:
""" Returns a list of tuples in the following format (first node, second node, arbitrage weight) """
return list([(src, dest, self.G[src][dest].getWeight()) for src in self.G.keys() for dest in self.G[src].keys()])
def print(self):
""" String representation of the graph """
for src in self.G.keys():
print("{}:".format(src))
for dest in self.G[src].keys():
print("\t{0} -- weight: {1} on {2} --> {3}".format(src, self.G[src][dest].getWeight(),
self.G[src][dest].getExchange(), dest)
)
def traceback(self, start, preds):
""" Given a starting node and a dictionary of predecessors, performs a traceback to ID a negative loop """
traveled = {node: False for node in self.G.keys()}
path = []
def aux(start, traveled, preds, path):
if traveled[start] == True:
path.append(start)
return list(reversed(path))
else:
traveled[start] = True
path.append(start)
return aux(preds[start], traveled, preds, path)
return aux(start, traveled, preds, path)
def BellmanFordWithTraceback(self, src):
""" Perform Bellman-Ford on graph and test for negative cycle """
# Initalize distance to all nodes to be infinity, then set distance to souce node to be 0
dist = {node: MAX_FLOAT for node in self.G.keys()}
pred = {node: None for node in self.G.keys()}
dist[src] = 0
num_nodes = len(self.G.keys())
# Find shortest path
for _ in range (num_nodes - 1):
for u, v, w, in self.getWeights():
if dist[u] != MAX_FLOAT and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
pred[v] = u
# This is a really slow way to find negative cycles, but ya gotta start somewhere
# Loop for number of edges
for u, v, w in self.getWeights():
if dist[u] != MAX_FLOAT and dist[u] + w + 0.001 < dist[v]:
print("Graph contains a negative cycle!")
return self.traceback(v, pred)
|
e5187d1106908965a1ab81f09896465f95980405 | chiffa/Karyotype_retriever | /src/basic_drawing.py | 231 | 3.546875 | 4 | import numpy as np
from matplotlib import pyplot as plt
def show_2d_array(data, title=False):
if title:
plt.title(title)
plt.imshow(data, interpolation='nearest', cmap='coolwarm')
plt.colorbar()
plt.show() |
f50c4dd2c07db5b1b8d6f74d7b7b9ef52c719ed7 | Sfreeman99/Gas-Pump | /gas_shell.py | 1,749 | 3.53125 | 4 | import time
import gas_core
import disk
from os.path import isfile
def prepay():
inventory = disk.open_inventory()
money = input("How much money would you like to put in?\n$: ")
gas_type = input("Which gas would you like to choose?: \n\tpremium = 2.49\n\tregular = 2.07\n\tmid grade = 2.10\n")
print('pumping...')
time.sleep(2)
gallons = gas_core.gas_pump(gas_type, money)
disk.purchase_history(gas_type,money,gallons)
print('With $',money,'you get',gas_core.gas_pump(gas_type,money),'gal.')
message = gas_core.update_inventory(inventory, gas_type, gallons)
disk.write(message)
def pay_after():
inventory = disk.open_inventory()
print('Head to the cashier to continue')
time.sleep(2)
money = input("How much money did you give the cashier?\n$: ")
gas_type = input('Which gas did you choose?\n\tpremium \n\tregular \n\tmid grade\n')
gallons = gas_core.gas_pump(gas_type, money)
disk.purchase_history(gas_type,money,gallons)
print('With $',money,'you get',gas_core.gas_pump(gas_type,money),'gal.')
message = gas_core.update_inventory(inventory, gas_type, gallons)
disk.write(message)
def decision():
input("Welcome to Shedlia's gas Station!! How are you doing? \n")
paying_type = input('would you like to prepay with a card?\n\tYes\n\tNo\n').upper().strip()
if paying_type == 'YES':
prepay()
elif paying_type == 'NO':
pay_after()
else :
print(".......")
time.sleep(2)
print("Well you can hit the door!!!")
def main():
if isfile('tank.txt'):
decision()
if not isfile('tank.txt'):
disk.initiate_tank()
decision()
if __name__ == '__main__':
main() |
8a066c578a1bc603693e22f3dea8d7a86d80fc1b | osamamohamedsoliman/Strings-1 | /Problem-1.py | 993 | 3.703125 | 4 | # Time Complexity :if two arrays sorted average O(n)
# Space Complexity :O(n)
# Did this code successfully run on Leetcode : yes
# Any problem you faced while coding this : no
import collections
class Solution(object):
def customSortString(self, S, T):
"""
:type S: str
:type T: str
:rtype: str
"""
ans = []
# get all frequencies of all chars in big string
frequencies = collections.Counter(T) #gets all frequencies of each letter
# loop through short string
for letter in S:
# if letter in frequencies
if letter in frequencies:
#append letter frequencies time
ans.append(letter * frequencies[letter])
#delete it
del frequencies[letter]
#write the rest
for letter in frequencies:
ans.append(letter * frequencies[letter])
# join and return
return ''.join(ans)
|
a62f6f216ab58d07dc2d44b08eabf58c503b0575 | peiranli/AI | /2048/ai.py | 9,334 | 3.515625 | 4 | from __future__ import print_function
import copy
import random
MOVES = {0: 'up', 1: 'left', 2: 'down', 3: 'right'}
ACTIONS = [(0, -1), (-1, 0), (0, 1), (1, 0)]
class State:
# the tile matrix, player's turn, score, previous move
def __init__(self, matrix, player, score, pre_move):
self.tileMatrix = copy.deepcopy(matrix)
self.player = player
self.score = score
self.pre_move = pre_move
# override comparation operator
def __eq__(self, other):
return self.tileMatrix == other.tileMatrix and self.player == other.player and self.score == other.score and self.pre_move == other.pre_move
# compute the largest tile in the grid
def highest_tile(self):
self.max_tile = 0
for row in self.tileMatrix:
for tile in row:
self.max_tile = max(self.max_tile, tile)
return self.max_tile
# compute the summation of difference between each pair of neighbor
def penalty(self):
penalty = 0
for i in range(0, len(self.tileMatrix)):
for j in range(0, len(self.tileMatrix)):
for m, n in ACTIONS:
neighbor = (i+m, j+n)
if 0 <= neighbor[0] < len(self.tileMatrix) and 0 <= neighbor[1] < len(self.tileMatrix):
penalty += abs(self.tileMatrix[i][j] - self.tileMatrix[neighbor[0]][neighbor[1]])
return penalty
# compute the number of empty tile
def empty_tile(self):
count = 0
for row in self.tileMatrix:
for tile in row:
if not tile:
count += 1
return count
def heuristic_function(self):
return self.score + 2*self.highest_tile() - self.penalty() + 2*self.empty_tile()
# Node class for game tree
class Node:
def __init__(self, state, depth):
self.state = copy.deepcopy(state)
self.children = []
self.reward = 0
self.depth = depth
def __eq__(self, other):
return self.state == other.state and self.children == other.children
# class for virtual stack
class Snapshot:
def __init__(self, value, node, returnVal, returnTo):
self.value = value
self.node = copy.deepcopy(node)
self.returnVal = returnVal
self.returnTo = returnTo
self.checkedchildren = 0
self.childindex = 0
class Gametree:
"""main class for the AI"""
# Hint: Two operations are important. Grow a game tree, and then compute minimax score.
# Hint: To grow a tree, you need to simulate the game one step.
# Hint: Think about the difference between your move and the computer's move.
def __init__(self, root, depth, score): #root node
self.maxdepth = depth # max depth of tree
self.nodes = [] # nodes in tree
self.root = Node(State(root, True, score, 4), 0) # root node
self.nodes.append(self.root)
self.frontier = []
def traverse(self):
for node in reversed(self.nodes):
print("depth: ", node.depth)
print("reward: ", node.reward)
# grow the tree one level deeper
def grow_once(self, state, depth):
# find current node
curr = self.find_node(state)
# max player
if(state.player):
# simulate each move
for direction in MOVES:
si = Simulator(state.tileMatrix, state.score)
si.move(direction)
# check to see difference
if(si.tileMatrix == state.tileMatrix):
continue
child = Node(State(si.tileMatrix, False, si.total_points, direction), depth)
curr.children.append(child)
# put children in nodes
self.nodes.extend(curr.children)
# chance player
elif not state.player:
tempMatrix = copy.deepcopy(state.tileMatrix)
# compute all possible random tile 2
for i in range(len(tempMatrix)):
for j in range(len(tempMatrix[i])):
if(tempMatrix[i][j] == 0):
tempMatrix[i][j] = 2
child = Node(State(tempMatrix, True, state.score, 4), depth)
tempMatrix[i][j] = 0
curr.children.append(child)
# put children in nodes
self.nodes.extend(curr.children)
return curr
# grow the tree from root
def grow(self, height):
curr_height = 0
curr = self.root
stack = [curr]
# grow the tree by depth
while(curr_height < height):
# print("frontier: ", len(self.frontier))
stack.extend(self.frontier)
self.frontier = []
# print("stack: ", len(stack))
while stack:
curr = stack.pop()
curr = self.grow_once(curr.state, curr_height+1)
self.frontier.extend(curr.children)
curr_height += 1
# print("frontier: ", len(self.frontier))
# expectimax for computing best move
def minimax(self, state):
"""Compute minimax values on the three"""
"""
depth-5 algorithm incomplete
curr = self.find_node(state)
value = float('-inf')
main = Snapshot(value, curr, 0, -1)
stack = [main]
while stack:
length = len(stack)
currsnapshot = stack[length-1]
curr = self.find_node(currsnapshot.node.state)
if not curr.children:
curr.reward = curr.state.score + 2*curr.state.highest_tile() - curr.state.penalty() + 2*curr.state.empty_tile()
currsnapshot.returnVal = curr.reward
returnsnapshot = stack[currsnapshot.returnTo]
if returnsnapshot.node.state.player:
stack[currsnapshot.returnTo].value = max(stack[currsnapshot.returnTo].value, curr.reward)
elif not returnsnapshot.node.state.player:
stack[currsnapshot.returnTo].value += curr.reward/len(curr.node.children)
stack.pop()
elif curr.state.player:
value = 0
for child in curr.children:
stack.append(Snapshot(value, child, 0, length-1))
elif not curr.state.player:
value = float('-inf')
for child in curr.children:
stack.append(Snapshot(value, child, 0, length-1))
"""
# get current node
curr = self.find_node(state)
# terminal node
if not curr.children:
curr.reward = curr.state.heuristic_function()
# print("terminal: ",curr.reward)
# max player
elif(curr.state.player):
value = float('-inf')
# find the maximum
for child in curr.children:
reward = self.minimax(child.state)
value = max(value, reward)
# print("max child reward: ", reward)
curr.reward = value
# chance player computer
elif not curr.state.player:
value = 0
# compute expectation value of next state
for child in curr.children:
reward = self.minimax(child.state)/len(curr.children)
value = value + reward
# print("chance child reward: ",reward)
curr.reward = value
else:
raise ValueError
print("reward: ",curr.reward)
return curr.reward
# function to return best decision to game
def compute_decision(self):
"""Derive a decision"""
# Replace the following decision with what you compute
self.grow(self.maxdepth)
# Should also print the minimax value at the root
maxvalue = self.minimax(self.root.state)
# self.traverse()
decision = 4
# find the corresponding decision
for child in self.root.children:
if (maxvalue == child.reward):
decision = child.state.pre_move
break
print(MOVES[decision])
return decision
def find_node(self, state):
for i in range(len(self.nodes)):
if(self.nodes[i].state == state):
return self.nodes[i]
class Simulator:
"""Simulation of the game"""
# Hint: You basically need to copy all the code from the game engine itself.
# Hint: The GUI code from the game engine should be removed.
# Hint: Be very careful not to mess with the real game states.
def __init__(self, matrix, score):
self.tileMatrix = copy.deepcopy(matrix)
self.total_points = score
self.board_size = 4
def move(self, direction):
for i in range(0, direction):
self.rotateMatrixClockwise()
if self.canMove():
self.moveTiles()
self.mergeTiles()
for j in range(0, (4 - direction) % 4):
self.rotateMatrixClockwise()
def moveTiles(self):
tm = self.tileMatrix
for i in range(0, self.board_size):
for j in range(0, self.board_size - 1):
while tm[i][j] == 0 and sum(tm[i][j:]) > 0:
for k in range(j, self.board_size - 1):
tm[i][k] = tm[i][k + 1]
tm[i][self.board_size - 1] = 0
def mergeTiles(self):
tm = self.tileMatrix
for i in range(0, self.board_size):
for k in range(0, self.board_size - 1):
if tm[i][k] == tm[i][k + 1] and tm[i][k] != 0:
tm[i][k] = tm[i][k] * 2
tm[i][k + 1] = 0
self.total_points += tm[i][k]
self.moveTiles()
def checkIfCanGo(self):
tm = self.tileMatrix
for i in range(0, self.board_size ** 2):
if tm[int(i / self.board_size)][i % self.board_size] == 0:
return True
for i in range(0, self.board_size):
for j in range(0, self.board_size - 1):
if tm[i][j] == tm[i][j + 1]:
return True
elif tm[j][i] == tm[j + 1][i]:
return True
return False
def canMove(self):
tm = self.tileMatrix
for i in range(0, self.board_size):
for j in range(1, self.board_size):
if tm[i][j-1] == 0 and tm[i][j] > 0:
return True
elif (tm[i][j-1] == tm[i][j]) and tm[i][j-1] != 0:
return True
return False
def rotateMatrixClockwise(self):
tm = self.tileMatrix
for i in range(0, int(self.board_size/2)):
for k in range(i, self.board_size- i - 1):
temp1 = tm[i][k]
temp2 = tm[self.board_size - 1 - k][i]
temp3 = tm[self.board_size - 1 - i][self.board_size - 1 - k]
temp4 = tm[k][self.board_size - 1 - i]
tm[self.board_size - 1 - k][i] = temp1
tm[self.board_size - 1 - i][self.board_size - 1 - k] = temp2
tm[k][self.board_size - 1 - i] = temp3
tm[i][k] = temp4
def convertToLinearMatrix(self):
m = []
for i in range(0, self.board_size ** 2):
m.append(self.tileMatrix[int(i / self.board_size)][i % self.board_size])
m.append(self.total_points)
return m
|
ad86cc27b27677585950cca7e29ec5bacd83b051 | daniel-reich/turbo-robot | /5xPh4eEAtpMdXNoaH_7.py | 810 | 4.03125 | 4 | """
Given a string `s`, return the length of the longest palindrome that can be
built with those letters.
### Examples
longest_palindrome("a") ➞ 1
longest_palindrome("bb") ➞ 2
longest_palindrome("abccccdd") ➞ 7
longest_palindrome("") ➞ 0
### Notes
N/A
"""
def longest_palindrome(s):
if len(s) == 0:
return 0
x,y=[], []
for ch in s:
if not ch in x:
x.append(ch)
y.append(1)
else :
y[x.index(ch)] +=1
if sum(y) == len(y):
return len(x[0])
left,mid,right='','',''
for indx, ch in enumerate(x):
count= y[indx]//2
left += ch * count
right = (ch * count)+ right
if (y[indx]%2 != 0):
mid = ch
return len(left + mid+ right)
|
eba37bc2916ed1a0e963e42e193e961e1679c48a | MDRODGERS17/Apprenticeship-Workspace | /Python Practice/mario.py | 367 | 4.0625 | 4 | from cs50 import get_int
while True:
# Prompts for height
height = get_int("Height: ")
# Reprompts for height if positive number 1-8 isn't inserted
if height >= 1 and height <= 8:
break
# Iterates through each row
for i in range(height):
# Prints spaces
print(" " * (height - i - 1), end="")
# Prints #
print("#" * (i + 1))
|
4c44784fdb0bedb4d5f9a34d867a10310d8824da | saumyaagrahari123/loop | /q53prime number.py | 198 | 4.1875 | 4 | prime=int(input("enter the number"))
a=1
b=0
while a<=prime:
if (prime%a==0):
b=b+1
a=a+1
if b==2:
print("it is a prime number")
else:
print("it is not prime number")
|
76d752fd634565f7aee4b36e841fa13f68f38829 | Nitin2611/15_Days-Internship-in-python-and-django | /DAY 3/task5.py | 110 | 3.703125 | 4 | x = 46
y = 53
if x > y:
print("x is greater number")
if y > x:
print("y is greater number")
|
261bf2e05686d0d622fe3b60b1a9e5f4e916e130 | shaurya950/code_forces | /81A.py | 277 | 3.71875 | 4 | t = int(input(""))
for j in range(t):
n = int(input(""))
if n == 2:
print(1)
elif n == 3:
print(7)
else:
temp = ""
if n % 2 == 0:
for i in range(n//2):
temp+="1"
else:
temp = "7"
n = n - 3
for i in range(n//2):
temp+="1"
print(int(temp))
|
3aadb6fe1391236c0f09b23175dc42e97fd8c5f8 | a01747686/Mision-03 | /AsientosEnEstado.py | 811 | 3.578125 | 4 | #Autor: Samantha MArtínez Franco A01747686
#Descripción: calcular cuanto va a pagar una persona por comprar boletos de un estadio en diferentes clases
def calcularPago(asientosA, asientosB, asientosC): #función que calcula pago total de los asientos
pagoA=asientosA*925
pagoB=asientosB*775
pagoC=asientosC*360
pagototal=pagoA+pagoB+pagoC
return pagototal
def main(): #función principal
asientosA = int(input("Número de boletos de clase A: ")) #llamar valores
asientosB = int(input("Número de boletos de clase B: "))
asientosC = int(input("Número de boletos de clase C: "))
pagototal=calcularPago(asientosA, asientosB, asientosC) #valor de pago total
print("El costo total es: $%.2f" % (pagototal)) #imprimir valores
#llamar función principal
main()
|
1756e503720a4abe403175e0badc53d1af92b0b1 | wolfcomm/python | /whatisyourname.py | 174 | 4.1875 | 4 | x = int(input('Enter digit?\n'))
print('Your digit is:')
print(x)
if x > 10 :
print('X is greater than 10')
if x < 10 :
print('X is fewer than 10')
print('All done')
|
713083164b492f393e507bf77efb8442949e8f99 | huesca92/Data_Science | /Python_Basico/ejercicios_reto/area_triangulo.py | 1,206 | 3.953125 | 4 | def run():
print('Calculemos el area de un triangulo')
base = float(input('Escribe el valor de la base: '))
altura = float(input('Escribe el valor de la altura: '))
A = area_triangulo(base,altura)
print('El area de tu triangulo es: ' + str(A))
decision = input('¿Quieres saber que tipo de triangulo que tienes? 1.- Si 2.- No ')
if int(decision) == 1:
print('Tu primer lado mide ' + str(base))
lado2 = input('Escribe el valor de tu segundo lado: ')
lado3 = input('Escribe el valor de tu tercer lado: ')
tipo_triangulo(base,float(lado2),float(lado3))
else:
print('Hasta Luego!')
def area_triangulo(b,h):
return (b*h)/2
def tipo_triangulo(l1,l2,l3):
if l1 == l2 and l2 == l3:
print('Tu triangulo es un equilatero')
elif (l1 == l2 and l1 != l3) or (l2==l3 and l2 != l1) or (l1 == l3 and l1 != l2):
print('Tu triangulo es isoceles')
elif l1 != l2 and l1 != l3:
print('Tu triangulo es escaleno')
if __name__ == '__main__':
run()
# a = ''
# for i in range(0,5,1):
# for j in range(0,20-i,1):
# a = a + '-'
# print(a)
# a= ''
|
19b6c4dd395805a1863eeb5b1f9fbf05058ad445 | effyhuihui/leetcode | /interviews/interview.py | 962 | 3.6875 | 4 | def twosum(root, target):
def dfs(root1, root2, target):
if not root1 or not root2:
return False
if root1.val+root2.val == target and root1 != root2:
return True
if root1.val + root2.val > target:
if root1 == root2:
return dfs(root1.left,root)
else:
return dfs(root1.left,root2) or dfs(root1, root2.left)
else:
if root1 == root2:
return dfs(root1.right,root2)
else:
return dfs(root1.right,root2) or dfs(root1, root2.right)
def lowestAncestor(a,b,root):
## if rootval = a or b, root is LCA
## if min(a,b) < rootval < max(a,b), root is LCA
if not root:
return None
rootval = root.val
if rootval > max(a,b):
return lowestAncestor(a,b,root.left)
elif rootval < min(a,b):
return lowestAncestor(a,b,root.right)
return root
def printtable(n):
res = []
for i in range(1,n+1):
res.append([])
for j in range(i,n+1):
res[-1].append(i*j)
print res
printtable(5)
|
6b0aac3c8edb07542651a14cccc4f304b520e753 | evillella/ProjectEuler | /Problem50.py | 1,870 | 3.84375 | 4 | """
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
Which prime, below one-million, can be written as the sum of the most consecutive primes?
"""
import math
def show_progress_bar(bar_length, completed, total):
bar_length_unit_value = (total / bar_length)
completed_bar_part = math.ceil(completed / bar_length_unit_value)
progress = "*" * completed_bar_part
remaining = " " * (bar_length - completed_bar_part)
percent_done = "%.2f" % ((completed / total) * 100)
print(f'[{progress}{remaining}] {percent_done}%', end='\r')
bar_length = 30
def is_prime(n,primes):
for p in primes:
if n%p == 0:
return False
return True
def gen_primes(n):
primes = {2}
primesums = [2]
p = 3
while p < n:
show_progress_bar(bar_length, p, n)
if is_prime(p,primes):
primes.add(p)
primesums.append(primesums[-1]+p)
p+=1
return primes, primesums
primes, primesums = gen_primes(1000000)
print('primes generated')
def valid_sum_len(n,primesums,primes):
if primesums[n-1] in primes:
return True
l = len(primesums)
for i in range(l-n):
if primesums[n+i] - primesums[i] in primes:
print('n',n,'sum',primesums[n+i]-primesums[i])
return True
return False
def binsearch(primesums,primes):
below = 539
above = len(primesums)
for m in range(below,above):
show_progress_bar(bar_length,below-539,above-539)
valid = valid_sum_len(m,primesums,primes)
if valid:
print('found len:',m)
binsearch(primesums,primes)
|
84e90681391399ab49551ecbfaf5566f25edc9ff | yangguolong828/HogwartsLG5-ygl | /sdf.py | 109 | 3.59375 | 4 | a,b = 0,1
while a < 10:
print(a)
print(b)
a,b = b, a+b
print("a的值为",a, "b的值为",b)
|
caefb9f41af9cfa0eaac48cda89db518b53a22c6 | zmcneilly/hackerrank | /default/primes.py | 1,691 | 3.890625 | 4 | from math import *
from bitarray import bitarray
class PrimeNumbers():
"""
This class is a special object for interacting with prime numbers
"""
def update_prime(self, new_max):
"""
This updates the object which contains the list of prime numbers
"""
self.primes = bitarray(new_max)
self.primes.setall(True)
self.primes[0] = False
self.primes[1] = False
for i in xrange(2,int(sqrt(new_max)),1):
if self.primes[i]:
for j in xrange(i*i,new_max,i):
self.primes[j] = False
self.MAX = int(new_max)
def is_prime(self,num):
"""
This method simply returns whether a number is prime or not
"""
if num < 0:
num = num*-1
if num <= 1:
return False
if num % 2 == 0:
return False
if num > self.MAX:
self.update_prime(num)
return self.primes[num]
def get_prime_list(self):
return list(self.plist)
def generate_prime_file(self):
self.update_prime(1000000000)
__f = open('primes.txt', 'w')
self.primes.tofile(__f)
__f.close()
def load_prime_file(self):
__f = open('primes.txt', 'r')
self.primes = bitarray()
self.primes.fromfile(__f)
__f.close
self.MAX = len(self.primes)
def __init__(self, max_prime=10000):
"""
This method is a constructor. If max_prime is passed it will set the
list of primes up to 10,000.
"""
self.MAX = 2
self.primes = bitarray(max_prime+1)
self.update_prime(max_prime)
|
d3dfe5b8d33ea82a8ab7a07b8ee1dec0d9e5a9cd | Kristjaan/Python_practice | /fizzbuzz.py | 305 | 4.09375 | 4 | #!usr/bin/env python3
# Homework 9.2: FizzBuzz
num = int(input("Select a number between 1 and 100: "))
for i in range(1, num+1):
if i % 5 == 0 and i % 3 == 0:
print("fizzbuzz")
elif i % 3 == 0:
print("fizz")
elif i % 5 == 0:
print("buzz")
else:
print(i)
|
c621b6b9a6d1b9f8c07ffd9a5fcbd5c334a1fd41 | karthik-siru/practice-simple | /array/Search_&_Sort/sortbysetbits.py | 848 | 3.6875 | 4 | class Solution:
def countBits(self,a):
count = 0
while (a):
if (a & 1 ):
count += 1
a = a>>1
return count
# Function to sort according to bit count
# This function assumes that there are 32
# bits in an integer.
def sortBySetBitCount(self,arr,n):
count = [[] for i in range(32)]
setbitcount = 0
for i in range(n):
setbitcount = self.countBits(arr[i])
count[setbitcount].append(arr[i])
j = 0 # Used as an index in final sorted array
# Traverse through all bit counts (Note that we
# sort array in decreasing order)
for i in range(31, -1, -1):
v1 = count[i]
for i in range(len(v1)):
arr[j] = v1[i]
j += 1
|
b477ae716637fb3d3f4478724bdb3eb138abfa0c | AErenzo/Python_course_programs | /TicTacToe.py | 4,605 | 4.03125 | 4 | import random
# function that prints of the board
def printBoard():
print('+---+---+---+')
print('|', board[0], '|', board[1], '|', board[2], '|')
print('+---+---+---+')
print('|', board[3], '|', board[4], '|', board[5], '|')
print('+---+---+---+')
print('|', board[6], '|', board[7], '|', board[8], '|')
print('+---+---+---+')
# fucntion to determine winner
def isWinner(char):
# horizontal winning combinations
if board[0] == char and board[1] == char and board[2] == char:
return True
elif board[3] == char and board[4] == char and board[5] == char:
return True
elif board[6] == char and board[7] == char and board[8] == char:
return True
# vertical winning combinations
elif board[0] == char and board[3] == char and board[6] == char:
return True
elif board[1] == char and board[4] == char and board[7] == char:
return True
elif board[2] == char and board[5] == char and board[8] == char:
return True
# diaganol winning combinations
elif board[0] == char and board[4] == char and board[8] == char:
return True
elif board[2] == char and board[4] == char and board[6] == char:
return True
else:
return False
# function to check if there is any blank spaces on the board - resulting in a tie
def isTie():
if ' ' not in board:
return True
else:
return False
# function to allow user to choose a side
def chooseSides():
side = ''
while not (side == 'X' or side == 'O'):
side = input('Do you want to be X or O? ').upper()
return side
# function determines which side goes first, using the randint
def Toss():
if random.randint(0, 1) == 0:
return 'X'
else:
return 'O'
# repeat condition flag
finished = False
# main loop - used to repeat the process if user wishes to play again
while not finished:
# board variable - list of empty spaces
board = [' ', ' ', ' ',
' ', ' ', ' ',
' ', ' ', ' ']
# condition - calling chooseSides function to determine which which side each player is
if chooseSides() == 'X':
print('Your are X')
else:
print('Your are O')
# empty player list
players = []
# conditional - help determine order or players using the Toss function
if Toss() == 'X':
print('X wins the toss')
players = ['X', 'O']
else:
players = ['O', 'X']
print('O wins the toss')
# call printBoard()
printBoard()
#Playing loop
while True:
# Player position loop
while True:
print(players[0], "'s turn -", end = ' ')
p1 = int(input('Choose a position on the board (1-9): ')) - 1
# if position chosen by p1 is blank - send the position to p1 side
if board[p1] == ' ':
board[p1] = players[0]
break
else:
print('That poisition is already taken')
continue
# call printBoard()
printBoard()
# conditional - calling isWinner function, checking for a winner after X's turn
if isWinner(players[0]):
print(players[0], 'has won')
break
# conditional - calling isTie function, checking for a tie
if isTie():
print('Its a tie!')
break
# Player position loop
while True:
print(players[1], "'s turn -", end = ' ')
p2 = int(input('Player # 2: Choose a position on the board (1-9)')) -1
# if position chosen by p2 is blank - send the position to p2 side
if board[p2] == ' ':
board[p2] = players[1]
break
else:
print('That poisition is already taken')
continue
printBoard()
# conditional - calling isWinner function, checking for a winner after O's turn
if isWinner(players[1]) == True:
print(players[1], 'has won')
break
# conditional - calling isTie function, checking for a tie
if isTie():
print('Its a tie!')
break
r = input('Do you want to play again? (y/n) ').lower()
if r == 'y':
continue
else:
print('Thanks for playing!')
finished = True
|
b772337eacbb8e8c943933401dca663eb286eeab | HeangSok-2/Tkinter | /test6_images.py | 517 | 3.515625 | 4 | # Acknowledgement: Dr John (codemy.com)
from tkinter import *
from PIL import ImageTk, Image
# tkinter accept only two type of image files (EX: gif); therefore, we use PIL to use more type of image file
root = Tk()
root.title('I am meow')
icon = 'totoro.jpg'
img = ImageTk.PhotoImage(Image.open(icon))
# icon= PhotoImage("totoro.jpg")
# root.iconbitmap(icon)
my_label = Label(root, image=img)
my_label.pack()
button_quit = Button(root, text= "Exit Program", command=root.quit)
button_quit.pack()
root.mainloop() |
92193cfae3c727a6938a13d563e1154fc3195145 | DaHuO/Supergraph | /codes/CodeJamCrawler/16_0_1_neat/16_0_1_rwd_problem1.py | 634 | 3.734375 | 4 | #input() reads a string with a line of input, stripping the \n at the end
def solution(n):
"""
:type n: int
:rtype : int
"""
if n is 0:
return 0
else:
dic={}
count=0
base=n
while True:
temp=n
while temp:
digit=temp%10
if digit not in dic:
dic[digit]=1
count+=1
if count is 10:
return n
temp//=10
n+=base
def main():
t=int(input()) #read a line with a single integer
for i in range(1,t+1):
n=int(input())
res=solution(n)
if res is 0:
print("Case #{}: {}".format(i,"INSOMNIA"))
else:
print("Case #{}: {}".format(i,res))
main() |
cefbd067730b07d0922a7f6030d7e91e7b160fae | ofarukaydin/ctci-python | /LinkedLists/intersection.py | 404 | 3.78125 | 4 |
def intersect(list1, list2):
if list1[-1] != list2[-1]:
return None
else:
longerList, smallerList = (list1, list2) if len(
list1) > len(list2) else (list2, list1)
offset = abs(len(list1) - len(list2))
for i in range(len(smallerList)):
if (smallerList[i] == longerList[i + offset]):
return smallerList[i]
return None
|
dcc4d2a6ef44114f8ba72e303f8ef95894931adc | dre1970/python-exercises | /list.py | 317 | 4.25 | 4 | list_len = int(input("How many elements are in your list? "))
u_list = []
for i in range(0, list_len):
u_list.append(float(input(f"What is the {i}th element of your list? ")))
bound = float(input("What do you want to search for numbers less than? "))
new_list = [x for x in u_list if x < bound]
print(new_list)
|
b0bbc149fd34675a2c023e02d3b3e8cf48cb8878 | WuPedin/LeetCodePractice | /LintCode/BFS/69_Binary Tree Level Order Traversal_Single Queue.py | 822 | 3.671875 | 4 | """
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: A Tree
@return: Level order a list of lists of integer
"""
def levelOrder(self, root):
res = []
# Check
if not root:
return res
# BFS
q = collections.deque([root])
while q:
val_this_lvl = []
for _ in range(len(q)):
node = q.popleft()
val_this_lvl.append(node.val)
# Append children
if node.left: q.append(node.left)
if node.right: q.append(node.right)
res.append(val_this_lvl)
return res |
99ffc93a22ed6b92398f06e1ece1b843dc220582 | martinseener/pycaesarcrypt | /pycaesarcrypt.py | 1,005 | 3.734375 | 4 | #!/usr/bin/env python
# # -*- coding: utf-8 -*-
__version__ = '1.0.0'
class pycaesarcrypt(object):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def caesar(self, string, shift):
result = ''
for char in string:
if char.isalpha():
index = (self.alphabet.find(char.lower()) + shift) % 26
if char.isupper():
result += self.alphabet[index].upper()
else:
result += self.alphabet[index]
else:
result += char
return result
def encrypt(self, plaintext, shift):
return self.caesar(plaintext, shift)
def decrypt(self, chiffre, shift):
return self.caesar(chiffre, -shift)
def rot13(self, string, mode=True):
if mode is True:
return self.encrypt(string, 13)
else:
return self.decrypt(string, 13)
if __name__ == '__main__':
print('You have to import this module in order to use it.')
|
8635ac59da24730ac55fcd1252b1f4b5adc8456d | nicolageorge/play | /amazon/graphs.py | 1,583 | 3.796875 | 4 | class Node:
def __init__(self, value, neighbors=None):
self.value = int(value)
if(isinstance(neighbors, list)):
self.neighbors = neighbors
elif(isinstance(neighbors, string)):
self.neighbors = neighbors.split(',')
def add_neighbor(self, node):
self.neighbors.append(node)
class UndirectedGraph:
def __init__(self):
self.nodes = []
self.adj_list = {}
def add(self, node):
self.nodes.append(node)
self.adj_list[node.value] = node.neighbors
def __str__(self):
return ', '.join([n.value for n in self.nodes])
def BFS(self, start):
level = {start:0}
parent = {start:None}
i = 1
frontier = [start] # level i-1
print('start: {}'.format(start))
while frontier:
nxt = [] # level i
for f in frontier:
# print('f:{}'.format(f))
for v in self.adj_list[f]:
if v not in level:
level[v] = i
parent[f] = f
nxt.append(v)
print('v: {}'.format(v))
frontier = nxt
i += 1
if __name__ == '__main__':
inp = input()
args = inp.split('#')
graph = UndirectedGraph()
for n in args:
nod = n.split(',')
val = int(nod[0])
neighbors = [int(n) for n in nod[1:]]
node = Node(val, neighbors)
graph.add(node)
print('main adj_list: {}'.format(graph.adj_list))
graph.BFS(0)
|
9597f6451cce734d98ee2201d9a3f50e2082e2b7 | vaibhav223007/Python_Code | /Random_Questions/03_split_string.py | 144 | 3.984375 | 4 | # WAP to split the string and store in a list
def splitting(string):
return string.split()
print(splitting("Hello world how are you?"))
|
cd9a5b158f92c453b790d9e8eb5febb3e4b3ea09 | sudeep0901/python | /src/8.functions.py | 741 | 3.765625 | 4 | a = 10
print(id(a))
def showvar(X=a): # Default argument will not change
print(X, id(X))
a = 20
print(id(a))
showvar()
def foo(x, items=[]):
items.append(x)
return items
print(foo(1))
print(foo(2))
print(foo(3))
print(foo(4))
def foo1(x, items=None):
if items is None:
items = []
items.append(x)
return items
print(foo1(1))
print(foo1(2))
print(foo1(3))
print(foo1(4))
# receiving arbitrary number of arguments
def recvParams(*args):
print(len(args))
for i in args:
print(i)
recvParams('a', 'b' , '1')
def fprintf(file, fmt, *args):
file.write(fmt % args)
# Use fprintf. args gets (42,"hello world", 3.45)
# fprintf(out,"%d %s %f", 42, "hello world", 3.45)
|
6902f385ee83e38a63d03b4d1547def55e6cace1 | chanbi-raining/m_g_stagram | /follow.py | 15,281 | 3.5625 | 4 | from bson.son import SON
def followNew(db, userid):
"""
Get the followers.
This function updates information that is user's followers or followings.
Note that if a user asks following to someone, the follower's information should be also updated.
Remember, you may regard duplicates and the situation that the follower does not exists.
"""
while True:
following = db.users.find_one({'id': userid}, {'following':1, '_id':0})
print('''
Please select the options below.
1. Search by ID
2. Search by name
3. Back
''')
try:
opt = int(input(''))
if opt == 1:
searchID(db, userid)
elif opt == 2:
searchName(db, userid)
else:
break
except:
raise
print('Failed following. Try again.')
#ins_res = db.users.insert_one({'id':id_, 'password':password, 'name':name, 'profile':profile, 'following':[], 'follower':[]})
def searchID(db, userid, follow = 1):
cont = '1'
while cont == '1':
foll_id = input('Search ID: ')
search = db.users.find_one({'id': foll_id}, {'_id':0, 'id':1, 'name':1, 'profile': 1})
if not search:
print('\nNo result. Would you like to try again? [1/0] ')
cont = input()
continue
elif foll_id == userid:
if follow == 1:
print('\nYou cannot follow yourself. Would you like to try again? [1/0] ')
else:
print('\nYou cannot blacklist yourself. Would you like to try again? [1/0]')
cont = input()
continue
print('\n\nSearch result\n')
print('ID'.ljust(15), 'Name'.ljust(15), 'Profile')
print(foll_id[:15].ljust(15), search['name'][:15].ljust(15), search['profile'])
if follow == 1:
follow_ok = input('\n\nWould you like to follow this user? [1/0] ')
if follow_ok != '1':
print('Going back to the user page')
break
else:
black = db.users.find_one({'id':foll_id, 'blacklist':userid})
dup = db.users.find({'id': userid, 'following': {'$in': [foll_id]}}).count()
if dup != 0:
print('You are already following', foll_id)
break
if not black:
try:
res1 = db.users.update_one({'id': userid}, {'$push':{'following': foll_id}})
res2 = db.users.update_one({'id': foll_id}, {'$push': {'follower': userid}})
if res1.modified_count == 1 and res2.modified_count == 1:
print('Successfully followed', foll_id)
break
else:
print('[ERROR] Failed following', foll_id, 'Would you like to try again? [1/0] ')
cont = input()
continue
except:
print('[ERROR] Failed following', foll_id)
break
else:
print('[ERROR] Failed following', foll_id)
break
else:
return foll_id
def searchName(db, userid, follow = 1):
cont, page, idxx = '1', 1, None
while cont == '1':
foll_name = input('Search Name: ')
search = list(db.users.find({'$text': {'$search': foll_name}}))
total_pages = len(search)//10 if len(search) % 10 ==0 else len(search)//10 + 1
if not search:
print('\nNo result. Would you like to try again? [1/0] ')
cont = input()
continue
print('\n\nSearch result\n')
print('Num'.ljust(10), 'ID'.ljust(15), 'Name'.ljust(15), 'Profile')
while page > 0:
for idx, user in enumerate(search[(page - 1) * 10:page * 10]):
print(str(idx).ljust(10), user['id'][:15].ljust(15), user['name'][:15].ljust(15), user['profile'])
print('\n',page,'/', total_pages)
a = 0
if total_pages != 1:
a = input('Do you wish to see another page? [1/0] ')
if a == '1':
try:
page = eval(input('\nWhat page do you want to see?: '))
while page > total_pages:
print('There are only', total_pages, 'pages.')
page = eval(input('\nWhat page do you want to see?: '))
continue
except:
print('[ERROR]')
else:
break
if follow == 1:
idxx = input('\nType the user number that you want to follow. Type q to search for another name. ')
else:
idxx = input('\nType the user number that you want to blacklist. Type q to search for another name. ')
if idxx == 'q': continue
foll_id = search[int(idxx)]['id']
if foll_id == userid:
if follow == 1:
print('You cannot follow yourself. Would you like to try again? [1/0] ')
else:
print('\nYou cannot blacklist yourself. Would you like to try again? [1/0]')
cont = input()
continue
black = db.users.find_one({'id':foll_id, 'blacklist':userid})
dup = db.users.find({'id': userid, 'following': {'$in': [foll_id]}}).count()
if dup != 0 and follow == 1:
print('You are already following', foll_id)
break
if follow == 1 and black:
print('\n[ERROR] Failed following', foll_id)
elif follow == 1 and not black:
try:
res1 = db.users.update_one({'id': userid}, {'$push':{'following': foll_id}})
res2 = db.users.update_one({'id': foll_id}, {'$push': {'follower': userid}})
if res1.modified_count == 1 and res2.modified_count == 1:
print('Successfully followed', foll_id)
break
else:
print('[ERROR] Failed following', foll_id, 'Would you like to try again? [1/0] ')
cont = input()
continue
except:
print('[ERROR] Failed following', foll_id)
else:
return foll_id
def unfollowNew(db, userid):
"""
Unfollow someone.
A user hopes to unfollows follwings.
You can think that this function is the same as the follow but the action is opposite.
The information apply to followings and followers both.
Again, the confimation is helpful whether the user really wants to unfollow others.
"""
while True:
menu = input('\nSelect Menu\n1. Unfollow \n2. Blacklist\n3. Exit\n')
if menu == '1':
following = db.users.find_one({'id': userid}, {'following':1, '_id':0})['following']
#print(following)
print()
print('Num'.ljust(10), 'ID'.ljust(15), 'Name'.ljust(15), 'Profile')
for k, i in enumerate(following):
person = db.users.find_one({'id': i}, {'_id':0})
print(str(k).ljust(10), i[:15].ljust(15), person['name'][:15].ljust(15), person['profile'])
print()
message = 'Type the user number that you want to unfollow. Type q to go back to the user page. '
idxx = input(message)
if idxx == 'q': break
try:
foll_id = following[int(idxx)]
message = 'Do you wish to unfollow '+str(foll_id)+'? [1/0] '
areyousure = input(message)
if areyousure != '1':
continue
res1 = db.users.update_one({'id': userid}, {'$pull': {'following': foll_id}})
res2 = db.users.update_one({'id': foll_id}, {'$pull': {'follower': userid}})
if res1.modified_count == 1 and res2.modified_count == 1:
print('Successfully unfollowed', foll_id)
break
else:
print('[ERROR] Failed unfollowing', foll_id, 'Would you like to try again? [1/0] ')
cont = input()
if cont != '1':
break
except IndexError:
print('[ERROR] Unavailable number')
except Exception as e:
print('[ERROR]')
elif menu == '2':
blackList(db, userid)
else:
break
def blackList(db, userid):
try:
while True:
print('''
Please select the options below.
1. Put on a blacklist
2. Remove from a blacklist
3. Back
''')
opt = int(input(''))
if opt == 1:
print('''
Please select the options below.
1. Search by ID
2. Search by name
3. Back
''')
want = int(input('Enter :'))
if want == 1:
blck_id = searchID(db, userid, 0)
elif want == 2:
blck_id = searchName(db, userid, 0)
else:
print('Going back to the menu')
break
if db.users.find_one({'id':userid, 'blacklist':blck_id}):
print(blck_id,' is already on the blacklist')
break
else:
message = 'Do you really want to put '+blck_id+' on your blacklist? [Y/N] '
before = input(message)
if before in ['Y', 'y', 'yes','YES','Yes']:
check = db.users.update_one({'id':userid}, {'$push':{'blacklist':blck_id}})
my_info = db.users.find_one({'id':userid})
if_following = int(blck_id in my_info['following'])
if_follower = int(blck_id in my_info['follower'])
#print(if_following, if_follower)
if check.modified_count == 1:
if if_following:
print('a')
res1 = db.users.update_one({'id': userid}, {'$pull': {'following': blck_id}})
res2 = db.users.update_one({'id': blck_id}, {'$pull': {'follower': userid}})
if if_follower:
print('b')
res3 = db.users.update_one({'id': userid}, {'$pull': {'follower': blck_id}})
res4 = db.users.update_one({'id': blck_id}, {'$pull': {'following': userid}})
if res1.modified_count + res2.modified_count + res3.modified_count + res4.modified_count == 4:
print('\n*** Successfully added to the blacklist ***')
else:
print('\n[ERROR] Failed blacklisting', blck_id, 'Would you like to try again? [1/0] ')
cont = input()
if cont != '1':
break
else:
print('c')
if res1.modified_count + res2.modified_count == 2:
print('\n*** Successfully blacklisting ***')
else:
print('\n[ERROR] Failed blacklisting', blck_id, 'Would you like to try again? [1/0] ')
cont = input()
if cont != '1':
break
elif if_follower:
print('d')
res3 = db.users.update_one({'id': userid}, {'$pull': {'follower': blck_id}})
res4 = db.users.update_one({'id': blck_id}, {'$pull': {'following': userid}})
if res3.modified_count + res4.modified_count == 2:
print('\n*** Successfully added to the blacklist ***')
else:
print('\n[ERROR] Failed blacklisting', blck_id, 'Would you like to try again? [1/0] ')
cont = input()
if cont != '1':
break
else:
print('\n*** Successfully added to the blacklist ***')
else:
print('\n[ERROR] Failed blacklisting', blck_id, 'Would you like to try again? [1/0] ')
cont = input()
if cont != '1':
break
else:
print('\n*** Going back to the menu ***')
break
elif opt == 2:
black_list = db.users.find_one({'id':userid})['blacklist']
if black_list:
print('** YOUR BLACKLIST **')
for i in range(len(black_list)):
print('{:>5} {:>10}'.format(i+1, black_list[i] ))
idxx = input('\nType the user number that you want to remove from your blacklist. Type q to go back to the user page. ')
if idxx == 'q': break
else:
before = input('Do you really want to remove from your blacklist? [Y/N]')
if before in ['Y', 'y', 'yes','YES','Yes']:
check = db.users.update_one({'id':userid},{'$pull':{'blacklist': black_list[int(idxx)-1]}})
if check.modified_count ==1:
print('\n*** Successfully removed ***')
else:
print('\n[ERROR] Failed removing', foll_id, ' from your blacklist. Would you like to try again? [1/0] ')
cont = input()
if cont != '1':
break
else:
print('\n*** Going back to the menu ***')
break
else:
cont = input('\nEmpty list...Would you like to try again? [1/0]')
if cont != '1':
break
else:
break
except:
raise
print('Failed following. Try again.')
|
737e36297577a685e90d9f114145d46a43c0f274 | farhantk/python | /15.MoreOnList.py | 296 | 3.5625 | 4 | data = ["meja","kursi","buku"]
print(data)
# Menambah list
data.append("kartu")
print(data)
# Meremove list
data.remove("kursi")
print(data)
# Menambah dibagian tertentu
data.insert(2,"meja")
print(data)
# Menghitung benda di list
jumlah = data.count("meja")
print("jumlah meja ada ",jumlah)
|
45d2f570f07ca47b8f06dbf780b2ace9bbfca5cd | qimanchen/Algorithm_Python | /python_interview_program/file_operate/get_file_path.py | 770 | 3.578125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Date : 2019-06-04 21:43:51
# @Author : Qiman Chen
# @Version : $Id$
"""
这个函数接收文件夹的名称作为输入参数
返回该文件夹中文件的路径
以及其包含文件夹中文件的路径
"""
import os
def print_directory_contents(s_path):
"""
:param s_path: 输入文件夹 -- 完整的路径
输出该文件夹包含文件和文件夹的所有完整路径
"""
for s_child in os.listdir(s_path):
s_child_path = os.path.join(s_path, s_child)
if os.path.isdir(s_child_path):
print_directory_contents(s_child_path)
else:
print(s_child_path)
def main():
s_path = input("请输入需要操作的文件名")
print_directory_contents(s_path)
if __name__ == "__main__":
main()
|
e39cce2bbff9bd1054852b3e5bdec6aa218731aa | lexusmem/Udemy_Python3 | /Fundamentos_Projetos/area_circulo_v6.py | 647 | 3.78125 | 4 | #! python
# Shibang - Indicação do interpretador que será utilizado p executar o script
# particionar o programa em varios arquivos diferentes
# podendo trabalhar com importações de
# pacotes e modulos
# ferramentas disponiveis no python
from math import pi
# Forma para importar apenas o PI do modulo Math
print(f'Valor de Pi = {pi}')
print('Valor de Pi (4 casas decimais)= %.4f' % (pi))
raio = input('Informe o Raio: ')
area = pi * float(raio)**2
print(f'Area do circulo: {area}')
# Nome do modulo principal __name__ (__main__) - Modulo Principal.
print('Nome do módulo', __name__)
print('Nome do pacote', __package__)
print(dir())
|
89b996cc0667d8394a951229e0ce75bd383de542 | DarNattp/python3-practice-by-snakify | /While loop/The largest element.py | 416 | 4.09375 | 4 | '''Given a list of numbers. Determine the element in the list with the largest value. Print the value of the largest
element and then the index number. If the highest element is not unique, print the index of the first instance.'''
a = input()
b = a.split()
for i in range(len(b)):
b[i] = int(b[i])
max_a = max(b)
print(max_a)
for i in range(len(b)):
if b[i] == max_a:
print(i)
break |
3de9649aeefbd27357fc9833a05a6842d9f02070 | PeterZhangxing/others | /test_random.py | 750 | 3.71875 | 4 | #!/usr/bin/python3.5
import random
def check_random(n):
if n.isdigit():
n = int(n)
else:
return "Invalid Input,we can only accept one number as parameter!Please retry!"
checkcode = ''
for i in range(n):
current_random = random.randrange(0,n)
if i == current_random:
tmp = chr(random.randint(65,90))
else:
tmp = random.randrange(1,10)
checkcode += str(tmp)
return checkcode
b_flag = True
while b_flag:
n = input("Please input how many numbers of checkcode member do you want: ").strip()
if n == "quit" or n == "exit" or n == "q":
b_flag = False
print("Exit the programme...")
else:
tt = check_random(n)
print(tt) |
fa2483e1dc1055c06a724da0f4204bdfd5c35ec4 | biyoner/-offer_python_code | /17打印从1到最大的n位数.py | 1,511 | 3.6875 | 4 | #coding=utf-8
# author:Biyoner
### Method 1
def print1ToN1(n):
if n<=0:
print 0
return 0
number = ["0"] *(n+1)
while not simulateADD(number):
PrintValue(number)
def simulateADD(number):
isOverflow = False
l = len(number)
for i in range(l-1,-1,-1):
if int(number[i])<9:
number[i] = str(int(number[i])+1)
break
else:
number[i] = '0'
if number[0] == '1':
isOverflow = True
return isOverflow
def PrintValue(val):
l = len(val)
s = ""
for i in range(l):
if str(val[i]) != "0":
break
for item in val[i:]:
s += str(item)
print s
### Method 2
def print1ToN2(n):
if n<=0:
print 0
return 0
number = ["0"]*(n)
PrintValueRecursive(number,0)
# for i in range(n):
# print PrintValueRecursive(number)
def PrintValueRecursive(number,index):
if index == len(number):
PrintValue(number)
return
for i in range(10):
number[index] = i
PrintValueRecursive(number,index+1)
### Method3 for python
def print1ToN_python(n):
maxNum = 0
for i in range(n):
maxNum = maxNum*10 + 9
print maxNum
count = 0
while count<maxNum:
count += 1
print count
if __name__ == "__main__":
print "test1"
print1ToN1(3)
print "test2"
print1ToN2(4)
# print1ToN_python(10) |
044888afa9b99c65872aa2dfd5542fb107220676 | MrHamdulay/csc3-capstone | /examples/data/Assignment_4/grcdea001/ndom.py | 710 | 3.578125 | 4 | def ndom_to_decimal(a):
stra = str(a)
decimals = 0
for i in range (len(stra)):
decimals = (decimals) + int(stra[i])
decimals = decimals*6
return decimals//6
def decimal_to_ndom(a):
stra = str(a)
sndom = ""
for i in range (len(stra)+1):
whole = a//6
rem = a%6
sndom = sndom + str(rem)
a = whole
sndom = sndom[::-1]
return int(sndom)
def ndom_add(a,b):
a = ndom_to_decimal(a)
b = ndom_to_decimal(b)
c = a+b
return (decimal_to_ndom(c))
def ndom_multiply(a,b):
a = ndom_to_decimal(a)
b = ndom_to_decimal(b)
c = a*b
return (decimal_to_ndom(c))
|
0240d97e74013d07c626fec7cc280f64afce56a8 | vishalkmr/Algorithm-And-Data-Structure | /Linked Lists/Merging.py | 1,486 | 4.3125 | 4 | '''
Merg two sorted linked-list into one linked-list
Assume that both the given linked-list are in Ascending order
Example :
list-1 contains 1,3,6,7,9
list-2 contains 2,4,8,10
meged list : 1,2,3,4,6,7,8,9,10S
'''
from LinkedList import LinkedList
def merg(first_linked_list,second_linked_list):
"""
Returns the merged list formed from merging first_linked_list and second_linked_list
Syntax: merg(first_linked_list,second_linked_list)
Time Complexity: O(m+n)
"""
first=first_linked_list.head
second=second_linked_list.head
output=LinkedList() #contains the merged linked-list
while first and second:
if second.data<first.data:
output.insert_end(second.data)
second=second.next
else:
output.insert_end(first.data)
first=first.next
while first:
output.insert_end(first.data)
first=first.next
while second:
output.insert_end(second.data)
second=second.next
return output
first_linked_list=LinkedList()
first_linked_list.insert_end(1)
first_linked_list.insert_end(3)
first_linked_list.insert_end(5)
first_linked_list.insert_end(9)
first_linked_list.insert_end(15)
first_linked_list.insert_end(30)
second_linked_list=LinkedList()
second_linked_list.insert_end(4)
second_linked_list.insert_end(12)
second_linked_list.insert_end(20)
print(first_linked_list )
print(second_linked_list )
output=merg(first_linked_list,second_linked_list)
print(output)
|
5a336adccd9c89951b9431bb01a1b3ac61f5a38a | nepomnyashchii/TestGit | /old/videos/practice.py | 1,589 | 4.125 | 4 | # print("Hello\nWorld")
# print("My\nmonkey")
# print("Alecismyfavourite\ncharacter")
# print(20==20)
# weather = "fall"
# if weather == "summer":
# print("Weather is good today")
# elif weather == "winter":
# print("Weather is horrible today")
# else:
# print("I am out today")
# weather = "summer"
# if not weather=="winter":
# print("I am enjoying my time today")
# test = [1,2,3, [1,2,3]]
# test[2] =5
# print(test)
# print(test[3][1])
# i=10
# while i>=5:
# print(i)
# i=i-1
# print("Program is finished")
# test =["Maria Rustaveli", "Dream Team", "Black Order"]
# if "Black Order" in test:
# print("Bach is playing extremelly loud music")
# else:
# print("We are the champions of the world")
# excellent = "news"
# test = {
# "milky way": "mama's music",
# "excellent day": "my favourite season is summer",
# "my favourite music": "my victory lap is in 10 days"
# }
# day = test["milky way"]
# morning=test["excellent day"]
# print(morning)
# print(day)
# test = []
# monkey = ("Ellen", "Jennifer", "Jack")
# test.append(monkey)
# test.reverse()
# print(monkey)
# print(test)
# test = [1,2,3,1,1,1]
# test.reverse()
# print(test)
# test =5
# print(list(range(5)))
# test =10
# print(list(range(1,9,2)))
# list = [6,7,8,9,10]
# for i in list:
# print(i)
# tuple = (1,2,3,4,5)
# for i in tuple:
# print(i)
apple = "apple"
orange = "orange"
name = "{} rediska {}".format(apple, orange)
print (name)
milk ="milk"
water = "water"
print('{0} {0}'.format(milk, water))
name = "apple " +"rediska " +"orange"
print(name)
#
|
e368572edb5e8313f14ac4a667eeafde6330f43d | sharmasourab93/CodeDaily | /ProblemSolving/CombinationsOfString.py | 237 | 3.765625 | 4 | def permute(a,l,r):
if l==r:
print(''.join(a))
for i in range(l,r+1):
a[l],a[i]=a[i],a[l]
permute(a,l+1,r)
a[l],a[i]=a[i],a[l]
string="ABC"
n=len(string)
a=list(string)
permute(a,0,n-1) |
0e31b5a9aece344d77faee6d05b8dd0ddf9ba8d9 | VagnerGit/PythonCursoEmVideo | /desafio_035_analisando_triângulo_v1.0.py | 482 | 4.125 | 4 | '''Exercício Python 35:
Desenvolva um programa que leia o comprimento de três retas e diga ao
usuário se elas podem ou não formar um triângulo.'''
a = float(input('\033[36mdigite comprimento da 1º reta '))
b = float(input('digite comprimento da 2º reta '))
c = float(input('digite comprimento da 3º reta\033[m '))
if a < b + c and b < a + c and c < a + b:
print()
print('\033[1:34m TRIANGULO \033[m')
else:
print()
print('\033[31m ñ é triangulo \033[m')
|
7bd5b8e777674670c054a036ab406f5a7b1fc0fd | abbybernhardt/Bernhardt-MATH361B | /NumberTheory/N5_Divisors_Bernhardt.py | 402 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 20:00:32 2019
@author: abigailbernhardt
"""
#%%
def divisors(n):
divisorlist = []
ii = 1
while ii < n: # proper divisor so not = to n
if (n % ii==0):
divisorlist.append(ii)
ii += 1
return divisorlist
mylist = divisors(500)
print('Here is a list of all proper divisors:', mylist)
|
5628ee497110a2386195bde95cc904fb82053f03 | bashir001/logistic-regression | /logistic regression.py | 1,054 | 3.78125 | 4 |
# logistic-regression
#import the necessary modules/packages
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
#read the datasets
df = pd.read_csv('[titanic (1).csv](https://github.com/bashir001/logistic-regression/files/6287173/titanic.1.csv)
')
data = pd.get_dummies(df, columns =['Siblings/Spouses', 'Pclass', 'Sex', 'Age', 'Fare'])
x = data.iloc[:, 1:]
y = data.iloc[:,0]
#spliting the data into training and testing
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=0)
classifier = LogisticRegression()
classifier.fit(x_test, y_test)
predicted_y = classifier.predict(x_test)
print(predicted_y)
print(x_test.shape)
#to iterate through the predicted values and print the accuracy of the train and test data
for x in range(len(predicted_y)):
if predicted_y[x] == 1:
print(x, end="\t")
print('accuracy: {:.2f}'. format(classifier.score(x_test, y_test)))
print('accuracy: {:.2f}'. format(classifier.score(x_train, y_train)))
print(df.shape)
|
d897e1fc497347aa60bcb7070815442b0c46da62 | omi23vaidya/MachineLearningFun | /dogs.py | 498 | 3.6875 | 4 | ##Learning how selection of a feature matters
import numpy as np
import matplotlib.pyplot as plt
greyhounds = 500
labs = 500
#greyhound's height would be between 24 and 32
greyhound_height = 28 + 4 * np.random.randn(greyhounds)
#lab's height would be between 20 and 28
lab_height = 24 + 4 * np.random.randn(labs)
# print(greyhound_height)
# print(lab_height)
# red color for greyhounds and blue for labs
plt.hist([greyhound_height, lab_height], stacked = True, color = ['r','b'])
plt.show() |
be9657f21e559443b23501c93cdc9bf8bdfa753d | edicley/WikiPython-Exercicios | /EstruturaDeDecisao/EstrutDecisao_17.py | 367 | 3.859375 | 4 | """
Faça um Programa que peça um número correspondente a um determinado ano e em seguida informe
se este ano é ou não bissexto.
"""
print('Informe um ano e lhe direi se ele é bissexto ou não.')
ano = int(input('Informe um ano: '))
if ano % 4 == 0 and ano % 400 == 0:
print(f'{ano} é um ano bissexto.')
else:
print(f'{ano} não é um ano bissexto.')
|
08341da568960ae210848db02a85d7e2be3e9b5e | buckeye-cn/ACM_ICPC_Materials | /solutions/buckeyecode/9.py | 199 | 3.625 | 4 | n = int(input())
lines = [
input().split(' ')
for i in range(n)
]
words = {
line[0]
for line in lines
}
print(len(set(
word
for line in lines
for word in line
) - words))
|
23c9ba644d6c01a7f88742c512bbbd0c427aaf93 | mfbx9da4/mfbx9da4.github.io | /algorithms/10.7_missing_int.py | 3,180 | 3.515625 | 4 | # An input file with four billion non-negative integers
# Generate an integer not contained by the file with 1GB of mem
# Follow up: what if all numbers are unique and you only
# have 10MB of memory
# p416
import random
import sys
max_64 = sys.maxsize
max_32 = 2**32 - 1
large_filename = 'large_number_of_ints.txt'
small_filename = 'small_number_of_ints.txt'
filename_32bit = '32bit_ints.txt'
#
# is it possible for 64 bit? =>
# 2**63 = 3 billion billion possible integers
#
# bit_vector = bytearray(array_size // 8)
# byte array overhead is 57 bytes
# each byte is then 1 byte after that
# bit_vector = bytearray((max_32 + 1) // 8)
# print(len(bit_vector))
# print(bit_vector[0])
# bit_vector[0] |= 1 << 5
# print(bit_vector[0])
# bit_vector |= 1 << 5
# print(bit_vector)
def solve(filename, largest_int):
"""
Solve with large bit vector.
- Create bit vector of length max_int_size
- Set bit every time int found
- Iterate through bit vector until first 0
If we have 64 bit integers the bit vector would
be too large to fit into mem. Instead we must
pass through the data in ranges of about (2**32)
or whatever our memory capacity for the bitvector
is.
"""
if largest_int > max_32:
raise TypeError('Largest int should be less than ' + str(max_32))
total = (largest_int + 1) # +1 for 0
num_bytes = total // 8
remainder = total % 8
if remainder:
num_bytes += 1
print('total', total, num_bytes)
bit_vector = bytearray(num_bytes)
# create bit vector
with open(filename) as file:
for line in file:
num = line.split('\n')[0]
if num:
num = int(num)
index = num // 8
remainder = num % 8
bit_vector[index] |= 1 << remainder
# TODO: special case of 0
for i in range(1, largest_int + 1):
index = i // 8
remainder = i % 8
has_bit = bit_vector[index] & 1 << remainder
if has_bit == 0:
return print('missing bit', i)
def write_random_ints(filename, number_of_ints=max_32, largest_int=max_32, chunk_size=100000):
# TODO: ensure unique
rand = lambda x: random.randint(x, largest_int)
with open(filename, "w") as file:
total = 0
while total < number_of_ints:
chunk = chunk_size
if chunk_size + total > number_of_ints:
chunk = number_of_ints - total
total += chunk_size
contents = ''.join(str(rand(i)) + '\n' for i in range(chunk))
file.write(contents)
prev = chunk
print('Wrote', total, 'lines')
print(max_32)
def write_small_file(number_of_ints=100, largest_int=100):
filename = small_filename
chunk_size = 50
write_random_ints(filename, number_of_ints=number_of_ints, \
largest_int=largest_int, chunk_size=chunk_size)
def solve_small():
largest_int = 10
number_of_ints = 10
write_small_file(number_of_ints=number_of_ints, largest_int=largest_int)
solve(small_filename, largest_int)
def write_32_bit():
largest_int = max_32
number_of_ints = max_32
write_random_ints(filename_32bit, number_of_ints=number_of_ints, largest_int=largest_int)
def solve_32_bit():
largest_int = max_32
solve(filename_32bit, largest_int)
# write_32_bit()
solve_32_bit()
|
2eef73c42a31960e45c1e183382bd36533058770 | cherryzoe/Leetcode | /42. (Lint)Maximum Subarray II.py | 1,756 | 3.84375 | 4 | # Given an array of integers, find two non-overlapping subarrays which have the largest sum.
# The number in each subarray should be contiguous.
# Return the largest sum.
# 这一题有点像buy stock III, 分割两边然后再求最大值的做法,所以采取类似的做法
# 如果采取maximum subarray的办法去求每一个index的两边,则需要 O(n^2)
# 这里才去和buy stock III类似的题目,但是略有不同 对于左边,用两个array left[]和leftMax[] left[i]表示以i为end的subarray的maximum sum leftMax[i]表示在[0:i]区间内的subarray的maximum sum (不一定以nums[i]为end)
# 右边同理,剩下的同buy stock iii
import sys
class Solution:
"""
@param: nums: A list of integers
@return: An integer denotes the sum of max two non-overlapping subarrays
"""
def maxTwoSubArrays(self, nums):
# write your code here
maxSum = -sys.maxint
size = len(nums)
# 初始化数组时不能用 left = right = array[], 这样会将left 和 right 指向同一个数组的起始地址,错误!不要问我怎么知道的
maxLeft = [0]*size
maxRight = [0]*size
left = [0]*size
right = [0]*size
left[0] = maxLeft[0] = nums[0]
for i in range(1, size):
left[i] = max(left[i-1]+nums[i], nums[i])
maxLeft[i] = max(left[i], maxLeft[i-1])
right[-1] = maxRight[-1] = nums[-1]
for i in range(size-2, -1, -1):
right[i] = max(nums[i], right[i+1]+nums[i])
maxRight[i] = max(right[i], maxRight[i+1])
for i in range(size-1):
curSum = maxLeft[i] + maxRight[i+1]
maxSum = max(maxSum,curSum)
return maxSum
|
4b14a51b9f6998bf0774d38bb47113887c85d197 | nmt/AdventOfCode | /2019/01/01-b.py | 729 | 3.8125 | 4 | #!/usr/bin/env python3
# IN: List of module masses, each on a separate line
# OUT: Sum of the fuel requirements for all modules (taking into account the fuel requirements for the fuel itself)
sumTotalFuelReqs = 0
def calculateFuel(mass):
fuel = mass/3 - 2
if fuel > 0:
return fuel + calculateFuel(fuel)
else: # fuel <= 0
return 0
# For each of the lines in the input
file = open('input.txt', 'r')
if file.mode == 'r':
for line in file:
# Add fuel calculation on to sum
sumTotalFuelReqs += calculateFuel(int(line))
print(sumTotalFuelReqs)
# Tests using example data
# print(calculateFuel(14) == 2)
# print(calculateFuel(1969) == 966)
# print(calculateFuel(100756) == 50346) |
f6a27a3567debbcd8ac543bda53ff524a89eaf6d | gabgerson/coding-challenges | /data-algo/fraudulent_notifications.py | 1,085 | 3.546875 | 4 | import bisect
def activityNotifications(expenditure, d):
#sort array from 0 to d -1
days = sorted(expenditure[0:d])
#middle = d//2
mid = d//2
#save num notifications to variable
notifications = 0
#loop through expenditures from d to end
for i in range(d, len(expenditure)):
#if median is even add item at index d//2 -1 and d //2 and divide by 2
if d % 2 == 0:
median = (days[mid] + days[mid - 1]) / 2
else:
#if d is odd median is d // 2 no remainder
median = days[mid]
#if item at median * 2 is greater than or equal to expenditure at i
if expenditure[i] >= 2 * median:
# add to notifications
notifications +=1
#get index of start of trailing days and pop from days list
days.pop(bisect.bisect_left(days, \
expenditure[i - d]))
# add current item in expenditure to days using insort to correct place
bisect.insort(days, expenditure[i])
return notifications
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.