blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
a6e995b5c2a43fbf7938761143ac76512137afc4 | Komal123Singh/notes | /inter.py | 641 | 4 | 4 | #Factorial
n=3
def factorial(n):
if n==1:
return 1
else:
return n*factorial(n-1)
print(factorial(n))
#armstrong
n=153
s=n
r=0
while n!=0:
d=n%10
n=n//10
r=r+d*d*d
if s==r:
print("Armstrong")
else:
print("not armstrong")
#Palindrome
n=163
p=n
r=0
while n!=0:
d=n%10
n=n//10
r=r*10+d
if p==r:
print("palindrome")
else:
print("not palindrome")
#prime number
n=int(input("enter a number: "))
if n>1:
for i in range(2,n):
if n%i==0:
print(" not prime")
break
else:
print(" prime")
|
e8b60a3b009ea53f31f9a784856bd44ba4776102 | alexandraback/datacollection | /solutions_5738606668808192_0/Python/naruaway/main.py | 996 | 3.53125 | 4 | import random
import math
def divisor(n):
if n == 1:
return 1
if n == 2:
return 1
if n == 3:
return 1
for d in range(2, min(n, 100)):
if n % d == 0:
return d
return 1
def build_number(r, base, n):
num = 1 + base ** (n - 1)
for i in range(1, n - 1):
num += r[i - 1] * base ** i
return num
def gen(N):
while True:
r = [random.randint(0, 1) for _ in range(N - 2)]
divisors = [divisor(build_number(r, b, N)) for b in range(2, 11)]
if any(d == 1 for d in divisors):
continue
return '1' + ''.join(str(i) for i in reversed(r)) + '1', divisors
def solve(N, J):
answers = dict()
while True:
digits, divisors = gen(N)
answers[digits] = divisors
if len(answers) == J:
break
print('Case #1:')
for digits, divisors in answers.items():
print('{} {}'.format(digits, ' '.join(map(str, divisors))))
solve(16, 50)
|
948fbf5caf7c9ae51918a0f83c920e05b4ec7f74 | MatiasTieranta/OOP | /Exercise 3/CoinToss.py | 2,360 | 4.21875 | 4 | # File: CoinTossingGame
# Author: Matias
# Description: Flipping coin game
import random
class Coin:
# The__init__ method initializes the sideup data attribute with 'Heads' and 'euros'
def __init__(self):
self.__sideup = 'Heads'
self.__currency = 'Euro'
# The toss method generate a random number
# int the range 0 to 3. If the number
# 0, then sideup is set to 'Heads'
# if 1 sideup is set to 'Tails'
# if 2 sideup is set to 'Upright'
# if 3 sideup is set to 'you missed the table'
def toss(self):
toss_result = random.randint(0, 3)
if toss_result == 0:
self.__sideup = 'Heads'
elif toss_result == 1:
self.__sideup = 'tails'
elif toss_result == 2:
self.__sideup = 'Coin land on Upright!'
elif toss_result == 3:
self.__sideup = 'Oh no you missed the table'
# Task 2 to add some currency's
def toss_currency(self):
toss_result = random.randint(0, 4)
if toss_result == 0:
self.__currency = 'Euro'
elif toss_result == 1:
self.__currency = 'Pound'
elif toss_result == 2:
self.__currency = 'Dollar'
elif toss_result == 3:
self.__currency = 'Ruble'
elif toss_result == 4:
self.__currency = 'Yen'
# The get_sideup method return the value referenced by sideup
# Task 4 to add self.sideup to private self.__sideup done here!
def get_sideup(self):
return self.__sideup
def get_currency(self):
return self.__currency
def set_currency(self, currency):
self.__currency = currency
# The main function
def main():
# Crete an object from Coin class.
my_coin = Coin()
my_coin.toss_currency()
# Currency
print("Currency is :", my_coin.get_currency())
# Display the side of the coin that is facing up.
print('This side is up : ', my_coin.get_sideup())
# Toss the coin
print("Im tossing the coin...")
my_coin.toss()
# Display the side of the coin that is facing up.
print('This side is up: ', my_coin.get_sideup())
# Task 3 Add a method that can change the currency of the coin.
my_coin.set_currency('Swedish krona')
print("Currency is :", my_coin.get_currency())
# Call the main function.
main()
|
6e8064d61f2ccb2f3b3a1898ccd366d9e2e22a6f | hlatki/coding-dojo | /game_of_life/akiesler/life.py | 2,446 | 3.59375 | 4 | #!/usr/bin/env python
import sys
DEAD, ALIVE = range(2)
# play with these and lets see what happens
neighbor_range = (-1,1)
stay_alive = (2,3)
birth = 3
class Life:
def __init__(self, size, board):
self._board = board
self._size = size
def getNeighbors(self, x, y, rng=neighbor_range):
neighbors = []
for row in self._board[max(x+rng[0], 0):min(x+rng[1], self._size[0])+1]:
neighbors.extend(row[max(y+rng[0], 0):min(y+rng[1], self._size[1])+1])
return neighbors
def getLivingNeighbors(self, x, y):
neighbors = self.getNeighbors(x, y)
return sum(neighbors) #yes its that easy
def live(self, gens=1):
for g in range(gens):
#this gives us a zeroed n x m board
next = [[0 for j in range(self._size[1])] for i in range(self._size[0])]
for (i,row) in enumerate(self._board):
for (j,cell) in enumerate(row):
#yes we count ourselves in our neighbors. don't ask.
living = self.getLivingNeighbors(i,j) - cell
if cell == ALIVE:
if living in stay_alive:
next[i][j] = ALIVE
if cell == DEAD:
if living == birth:
next[i][j] = ALIVE
self._board = next
def readBoard(file):
with open(file) as f:
lines = [line.strip() for line in f]
(x, y) = [int(i) for i in lines.pop(0).split()]
assert len(lines) == x, "expected %d, actual %d" % (x, len(lines))
for line in lines:
assert len(line) == y, "expected %d, actual %d %s" % (y, len(line), line)
return ((x,y), lines)
def convertBoard(board):
for (i, line) in enumerate(board):
line = line.replace('.','0')
line = line.replace('*','1')
board[i] = [int(x) for x in line]
return board
def revertBoard(board):
for (i, line) in enumerate(board):
line = ''.join([str(x) for x in line])
line = line.replace('0','.')
line = line.replace('1','*')
board[i] = line
return board
if __name__ == "__main__":
(size, board) = readBoard(sys.argv[1])
gens = int(sys.argv[2])
board = convertBoard(board)
life = Life(size, board)
life.live(gens)
board = revertBoard(life._board)
print gens
for row in board:
print row
|
23a5fd1a8157397de60046e8396c814f14c2fe83 | larsnohle/57 | /11/eleven.py | 991 | 3.984375 | 4 | import math
def get_positive_number_input(msg, to_float = False):
done = False
while not done:
try:
i = -1.0
if to_float == True:
i = float(input(msg))
else:
i = int(input(msg))
if i < 0:
print("Please enter a number > 0")
else:
done = True
except ValueError:
print("That was not a valid integer. Please try again!")
return i
# Get input.
number_of_euros = get_positive_number_input("How many euros are you exchanging? ")
exchange_rate = get_positive_number_input("What is the exchange rate? ", True)
# Perform calculations.
number_of_cents = number_of_euros * exchange_rate
number_of_cents_rounded = math.ceil(number_of_cents)
number_of_dollars = number_of_cents_rounded / 100.0
# Print output.
print("%d euros at an exchange rate of %.2f is %.2f U.S. dollars." % (number_of_euros, exchange_rate, number_of_dollars))
|
fabaecbb957750253b213459bf9b71b8e3f6c6ad | ynrng/leetcode | /done/350_Intersection_of_Two_Arrays_II.py | 465 | 3.640625 | 4 | class Solution(object):
@staticmethod
def intersect(nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
s = set(nums1).intersection(set(nums2))
inter = []
for i in s:
inter.extend([i]*min(list(nums1).count(i), list(nums2).count(i)))
return inter
if __name__ == '__main__':
print(Solution().intersect([1, 2, 2, 1], [2, 2])) # [2, 2]
|
90c9e52acb09a2796509a98bb75970aec271e61c | mbuon/Leetcode | /763. Partition Labels.py | 980 | 3.5625 | 4 | # Input: S = "ababcbacadefegdehijhklij"
# Output: [9,7,8]
# Explanation:
# The partition is "ababcbaca", "defegde", "hijhklij".
# This is a partition so that each letter appears in at most one part.
# A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
# https://leetcode.com/problems/partition-labels/description/
S = "qiejxqfnqceocmy"
def minimizer(S):
node = []
for index, value in enumerate(S):
if (value == S[0]):
node.append(index)
min_length = max(node) + 1
i = 0
while (i < min_length):
current = S[i]
node = []
for index, value in enumerate(S):
if (value == current):
node.append(index)
if (max(node) >= min_length):
min_length = max(node) + 1
i += 1
return min_length
node = []
while (len(S) != 0):
length = minimizer(S)
node.append(length)
S = S[length:]
print node |
fe5473ea4d5e0fcf9d64f412d1ea92e845370636 | kszymankiewicz/Python3-basic-to-master | /list/operacjeifunkcjenalistach.py | 438 | 4 | 4 | #len() - długość - length
#.append - dodać
#.extend - rozszerzyć
#.insert(index, co) - wstawić
#.index - indeks danego el.
#sort(reverse=False) - sortuj rosnąco
#max()
#min()
#.count - ile razy coś wystąpi
#.pop - usuń ostatni el.
#.remove - usuń pierwsze wystąpienie
#.clear - wyczyść liste
#.reverse - zamień kolejność
lista1 = [54, 1, -2, 20, 1]
lista2 = ["Arkadiusz", "Wioletta"]
lista1.reverse()
print(lista1)
|
865318bee8f7809f0ac1deec5ea6bd13aaf2694e | SirMullich/pp2-spring-2020 | /pygame-lectures/tanks-draft.py | 4,317 | 3.765625 | 4 | import pygame
class Tank:
# speed instead of dx, dy
def __init__(self, x, y, width, height, speed):
self.x = x
self.y = y
self.width = width
self.height = height
self.speed = speed
self.direction = 1 # 1 - up, 2 - down, 3 - left, 4 - right
def update_location(self, seconds):
if self.direction == 1:
self.y -= self.speed * seconds
elif self.direction == 2:
self.y += self.speed * seconds
elif self.direction == 3:
self.x -= self.speed * seconds
elif self.direction == 4:
self.x += self.speed * seconds
def change_direction(self, direction):
self.direction = direction
def get_rect(self):
return (self.x, self.y, self.width, self.height)
class SceneBase:
def __init__(self):
self.next = self
def process_input(self, events):
print("uh-oh, you didn't override this in the child class")
def update(self, seconds):
print("uh-oh, you didn't override this in the child class")
def render(self, screen):
print("uh-oh, you didn't override this in the child class")
def switch_to_scene(self, next_scene):
self.next = next_scene
# TitleScene is a subclass of SceneBase
# SceneBase is a parent of TitleScene
# TitleScene inherits from SceneBase
class TitleScene(SceneBase):
def __init__(self):
SceneBase.__init__(self)
def process_input(self, events, pressed_keys):
for event in events:
if event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN:
# Move to the next scene when the user pressed Enter
self.switch_to_scene(GameScene()) # create a new object GameScene
def update(self, seconds):
pass
def render(self, screen):
# For the sake of brevity, the title scene is a blank red screen
screen.fill((255, 0, 0))
class GameScene(SceneBase):
def __init__(self):
SceneBase.__init__(self)
self.tank = Tank(100, 100, 50, 50, 80)
def process_input(self, events, pressed_keys):
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.tank.change_direction(1)
elif event.key == pygame.K_DOWN:
self.tank.change_direction(2)
elif event.key == pygame.K_LEFT:
self.tank.change_direction(3)
elif event.key == pygame.K_RIGHT:
self.tank.change_direction(4)
def update(self, seconds):
self.tank.update_location(seconds)
def render(self, screen):
# The game scene is just a blank blue screen
screen.fill((0, 0, 255))
#draw tank (rect)
pygame.draw.rect(screen, (0, 255, 0), self.tank.get_rect())
def run_game(width, height, fps, starting_scene):
pygame.init()
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
active_scene = starting_scene
while active_scene != None:
milliseconds = clock.tick(fps)
seconds = milliseconds / 1000.0
pressed_keys = pygame.key.get_pressed()
# Event filtering
filtered_events = []
for event in pygame.event.get():
quit_attempt = False
if event.type == pygame.QUIT:
quit_attempt = True
elif event.type == pygame.KEYDOWN:
alt_pressed = pressed_keys[pygame.K_LALT] or \
pressed_keys[pygame.K_RALT]
if event.key == pygame.K_ESCAPE:
quit_attempt = True
elif event.key == pygame.K_F4 and alt_pressed:
quit_attempt = True
if quit_attempt:
active_scene.Terminate()
else:
filtered_events.append(event)
active_scene.process_input(filtered_events, pressed_keys) # handle input
active_scene.update(seconds) # move tank
active_scene.render(screen) # (re)draw the tank
active_scene = active_scene.next # when RETURN is pressed in TitleScene, active_scene: TitleScene -> GameScene
pygame.display.flip()
run_game(800, 600, 30, TitleScene()) |
53954916303cf02394d5c6cf09d0a83036a6b278 | dhruvparekh008/ES102project | /zombieland1.py | 11,185 | 4.15625 | 4 | #Creating An Introduction
print("\nWELCOME to the Text Based Adventure Game-->Zombie Land")
print("\nYou are a brave fighter and protector of the magical lands of the Black Village")
print("\nI am Jojo the talking dog and I will guide you through the whole game ")
print("\nThis game will test your imagination. Keep noting down coordinates of traps, zombies, treasure chests or more.")
name=input("\nChoose a name that you want to be known by: ")
print("\nAll hail the brave knight",name)
#Explaining the Rules
movingon1=input("\nPress enter key to go on: ")
print("\nYou are at the centre of the village. The villagers have abandoned this village as it has been taken over by zombies.")
print("\nThe village spans 5 km in all directions. Imagine a 10 by 10 grid.")
print("\nYou are free to move 1 km at a time in one of the four directions: North, South, East, West.")
print("\nYou can move by typing: (w) to go North, (s) to go South, (d) to go East, (a) to go West.")
movingon2=input("\nPress enter key to go on: ")
print("\nYour aim is to light all the 5 torches in the village, as zombies burn when exposed to light.")
print("\nI would suggest you keep a notepad and pen and map out the village as we go...")
movingon3=input("\nPress enter key to go on: ")
print("\n\n\nLets start!!!!")
print("\n\n\nThe village elder has left you the following hints to locate the torches.")
print("\nFind torch1 at a position such that the x coordinate is 999 divided by infinty and the y coordinate is 999 divided by 333.")
print("\nFind torch2 at a position such that the x coordinate is same as the y coordinate of torch1 +1 and the y coordinate is unity.")
print("\nFind torch3 at a position such that x coordinate is 12345**0 and y corrdinate is the negative of the second prime number.")
print("\nFind torch4 at a position such that the x and y coordinate are the same and are the negative of the least odd prime number.")
print("\nFind torch5 at a position such that the x coordinate is the negative of square root of 16 and y coordinate is x coordinate -3 ")
t=0 #Torch counter
x=0 #X-coordinate counter
y=0 #Y-coordinate counter
s1=0 #Torch1 switch checker
s2=0 #Torch2 switch checker
s3=0 #Torch3 switch checker
s4=0 #Torch4 switch checker
s5=0 #Torch5 switch checker
def pos():
print("You are at","(",x,",",y,")")
pos()
while t!=6:
if t==5: #Condition for victory
print("YOU HAVE WON, BRAVE KNIGHT",name,"!!!!!!")
print("THE VILLAGERS THANK YOU ")
exit()
else:
direction=str(input("Give direction: ")) #Giving direction inputs
if(direction=="w"):
y=y+1
elif(direction=="s"):
y=y-1
elif(direction=="d"):
x=x+1
elif(direction=="a"):
x=x-1
else:
print("INVALID DIRECTION INPUT")
print("GAME OVER")
exit()
pos()
if(x<-5 or x>5 or y<-5 or y>5): #Creating Boundry of map
print("You Abandoned The Village ")
print("GAME OVER")
exit()
elif(x==0 and y==1): #Quicksand
print("You fell into quicksand and died")
print("GAME OVER")
exit()
elif x==-1 and y>-1: #Farm side one
print("There is a farm ahead. You canot cross it because the cattle is running haywire")
print("This is beacuse they are afraid of the zombie located at (-2,3)")
print("Use your bow and arrow to kill the zombies.")
arrowx=int(input("Which x coordinate do you want to shoot the arrow?: "))
arrowy=int(input("Which y coordinate do you want to shoot the arrow?: "))
if(arrowx==-2 and arrowy==3):
print("You have crossed the farm and are at a gate located at (-4,0)")
x=-4
y=0
pos()
else:
print("Your aim was bad and you were run over by the cattle.")
print("GAME OVER")
exit()
elif(x==-3 and y>-1): #Farm side two
print("There is a farm ahead. You canot cross it because the cattle is running haywire")
print("This is beacuse they are afraid of the zombie located at (-2,1)")
print("Use your bow and arrow to kill the zombies.")
arrowx=int(input("Which x coordinate do you want to shoot the arrow?: "))
arrowy=int(input("Which y coordinate do you want to shoot the arrow?: "))
if(arrowx==-2 and arrowy==1):
print("You have crossed the farm and are at a gate located at (0,4)")
x=0
y=4
pos()
else:
print("Your aim was bad and you were run over by the cattle.")
print("GAME OVER")
exit()
elif((x<=2 and y==-1) or (x<=2 and y==-2) or (x==2 and y>=-2) or (x==3 and y>=-2)): #Magical lake
print("You have reched the bank of the magical lake ")
print("Jump in to teleport to any location other than to the torches. ")
lakex=int(input("x coordinate: "))
lakey=int(input("y coordinate: "))
if lakex==0 and lakey==3:
print("You broke the rules!!!!!")
print("GAME OVER")
exit()
elif lakex==4 and lakey==1:
print("You broke the rules!!!!!")
print("GAME OVER")
exit()
elif lakex==1 and lakey==-3:
print("You broke the rules!!!!!")
print("GAME OVER")
exit()
elif lakex==-3 and lakey==-3:
print("You broke the rules!!!!!")
print("GAME OVER")
exit()
elif lakex==-4 and lakey==1:
print("You broke the rules!!!!!")
print("GAME OVER")
exit()
else:
x=lakex
y=lakey
pos()
elif(x==1 and y==0): #Zombie
print("There is a zombie in your way. Use your sword to kill it.")
print("You can do so by typing the sum of the coordinates you are at.")
sumofcoord=int(input("What is the sum: "))
if sumofcoord==1:
print("You have killed the zombie.")
else:
print("You have failed to kill the zombie. The zombie killed you")
print("GAME OVER")
exit()
elif(x==0 and y==-3): #Spider
print("You are stuck in a spider web")
print("Answer the giant spider's question correctly to be free.")
answerspider=int(input("Spider: What is the binary representation of 100?: "))
if answerspider==1100100:
print("Spider: Yes that is correct. You are free to go.")
else:
print("Spider: That is incorrect. I will now eat you.")
print("GAME OVER")
exit()
elif(y==-4): #Valley
print("You have fallen into a valley.")
print("GAME OVER")
exit()
elif(x==0 and y==-5): #Goldenchest
print("You have come across a golden chest.")
print("If you wish to open it type open.")
print("Otherwise type ignore.")
goldchest=str(input("What would you like to do?: "))
if goldchest=="open":
print("Well done. You have found one switch to light all torches.")
print("I have switched it on.")
t=5
else:
print("You may go on.")
elif(x==1 and y==4): #Blackbox1
print("You see a black box.If you wish to open it type open.")
print("Otherwise type ignore.")
blackbox=str(input("What would you like to do?: "))
if blackbox=="open":
print("You have released all the demons of hell into the village.")
print("GAME OVER")
exit()
else:
print("You may go on.")
elif(x==1 and y==2): #Blackbox2
print("You see a black box.If you wish to open it type open.")
print("Otherwise type ignore.")
blackbox=str(input("What would you like to do?: "))
if blackbox=="open":
print("You have released all the demons of hell into the village.")
print("GAME OVER")
exit()
else:
print("You may go on.")
elif(x==4 and y==3): #Zombie
print("There is a zombie in your way. Use your sword to kill it.")
print("You can do so by typing the sum of the coordinates you are at.")
sumofcoord=int(input("What is the sum: "))
if sumofcoord==7:
print("You have killed the zombie.")
else:
print("You have failed to kill the zombie. The zombie killed you")
print("GAME OVER")
exit()
elif(x==-4 and y==2): #Zombie
print("There is a zombie in your way. Use your sword to kill it.")
print("You can do so by typing the sum of the coordinates you are at.")
sumofcoord=int(input("What is the sum: "))
if sumofcoord==-2:
print("You have killed the zombie.")
else:
print("You have failed to kill the zombie. The zombie killed you")
print("GAME OVER")
exit()
elif(x==4 and y==-2): #Spider
print("You are stuck in a spider web")
print("Answer the giant spider's question correctly to be free.")
answerspider=int(input("Spider: how many legs do I have?: "))
if answerspider==8:
print("Spider: Yes that is correct. You are free to go.")
else:
print("Spider: That is incorrect. I will now eat you.")
print("GAME OVER")
exit()
elif(x==0 and y==3): #Torches
if s1==0:
print("You have found torch1")
t=t+1
s1=1
elif s1==1:
print("You have already lighted torch1")
elif(x==4 and y==1):
if s2==0:
print("You have found torch2")
t=t+1
s2=1
elif s2==1:
print("You have already lighted torch2")
elif(x==1 and y==-3):
if s3==0:
print("You have found torch3")
t=t+1
s3=1
elif s3==1:
print("You have already lighted torch3")
elif(x==-3 and y==-3):
if s4==0:
print("You have found torch4")
t=t+1
s4=1
elif s4==1:
print("You have already lighted torch4")
elif(x==-4 and y==1):
if s5==0:
print("You have found torch5")
t=t+1
s5=1
elif s5==1:
print("You have already lighted torch5")
|
47f9bff6762f7a38e01e438be8751f9644e8d623 | misrashashank/Competitive-Problems | /buy_and_sell_stocks.py | 1,741 | 3.90625 | 4 | '''
Say you have an array for which the ith element is the price
of a given stock on day i.
If you were only permitted to complete at most one transaction
(i.e., buy one and sell one share of the stock), design an algorithm
to find the maximum profit.
Note that you cannot sell a stock before you buy one.
Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and
sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
'''
import sys
class Solution:
def maxProfit(self, prices):
'''
# Time: O(n^2)
num_days = len(prices)
max_profit = 0
for day in range(num_days):
for next_day in range(day+1, num_days):
profit = prices[next_day] - prices[day]
if profit > max_profit:
max_profit = profit
return max_profit
'''
'''
# Time: O(n)
num_days = len(prices)
min_cost = sys.maxsize
max_profit = 0
for day in range(num_days):
if prices[day] < min_cost:
min_cost = prices[day]
elif (prices[day] - min_cost) > max_profit:
max_profit = prices[day] - min_cost
return max_profit
'''
if not prices:
return 0
min_cost = float('inf')
max_profit = 0
for num in prices:
if num < min_cost:
min_cost = num
min_cost = min(num, min_cost)
max_profit = max((num - min_cost), max_profit)
return max_profit
|
d788e6fefdc13e884e1c4ec31fa9e50369ab5fe6 | jerrytnutt/Automate-the-Boring-Stuff-Project-Solutions | /CH13-Working-With-Excel-Spreadsheets/multiplicationTable/multiplicationTable.py | 1,194 | 4.09375 | 4 | # Create a program that takes a number N from the command line
# Creates an N×N multiplication table in an Excel spreadsheet.
from openpyxl import Workbook
from openpyxl.styles import Font
import sys
def create_table(n):
workbook = Workbook()
sheet = workbook.active
n = int(n)
# Add 2 to n on account of first labeled cell
for i in range(1,n + 2):
for j in range(1,n + 2):
# loop through each cell and add the appropriate label or product
if i == 1 and j != 1:
sheet.cell(row=i, column=j).value = j - 1
sheet.cell(row=i, column=j).font = Font(bold=True)
elif i != 1 and j == 1:
sheet.cell(row=i, column=j).value = i - 1
sheet.cell(row=i, column=j).font = Font(bold=True)
else:
sheet.cell(row=i, column=j).value = (i-1) * (j-1)
sheet.cell(row=1, column=1).value = ''
workbook.save(filename="multiplicationTable.xlsx")
if __name__ == "__main__":
if len(sys.argv) > 1:
try:
if type(int(sys.argv[1])) == int:
number = sys.argv[1]
create_table(number)
except ValueError:
print("Please enter a number")
else:
print('Please enter a number') |
c656e54bb589668b3b9ddb4cadd2735195e9329f | feliperobledo/manatee_escape | /src/utils/colors.py | 725 | 3.71875 | 4 | class Color:
def __init__(self, r=0, g=0, b=0, a=0):
self.r = r
self.g = g
self.b = b
self.a = a
@property
def rgb(self):
return (self.r, self.g, self.b)
@property
def rgba(self):
return (self.r, self.g, self.b, self.a)
def __str__(self):
return "(r={r}, g={g}, b={b}, a={a})".format(r=self.r, g=self.g, b=self.b, a=self.a)
white = Color(r=255, g=255, b=255, a=255)
red = Color(r=255, g=0, b=0, a=255)
green = Color(r=0, g=255, b=0, a=255)
blue = Color(r=0, g=0, b=255, a=255)
yellow = Color(r=255, g=255, b=0, a=255)
black = Color(r=0, g=0, b=0, a=255)
light_green = Color(r=102, g=255, b=51, a=255)
brown = Color(r=135, g=84, b=8, a=255)
|
bd7afb02e7659dc92b45a3d2615e7bade6942667 | hinbody/python_examples | /namespaces/name_scopes.py | 958 | 4.09375 | 4 | # define global variable
my_var = 10
def make_vars():
my_stuff = 20
# print local variable
print(my_stuff)
# print global variable
print(my_var)
class Our_vars:
def __init__(self, var1, var2):
# assign class variable from new obj arg
self.var1 = var1
# assign class variable from new obj arg
self.var2 = var2
# assign class variable from global variable
self.var3 = my_var
class_var = "class var"
# assign new object with values for var1 and var2
the_vars = Our_vars(42, 24)
# next 3 lines print obj variable
print(the_vars.var1)
print(the_vars.var2)
print(the_vars.var3)
# prints global(also local in this case) variable
print(my_var)
# call function that prints global and local variables
make_vars()
# prints locally assigned variable from class
print(the_vars.class_var)
# this variable is not defined in this scope, only in the function scope - Error
# print(my_stuff)
|
dfc3c5da2dfb4394833b73ae4a46e8565003b8f1 | SOURADEEP-DONNY/PYTHON-3-PROGRAMMING | /PYTHON FUNCTIONS FILES AND DICTIONARIES/week 4/BREAK & CONTINUE STATEMENTS.py | 319 | 4.09375 | 4 | #BREAK STATEMENT
i=0
while i<=10:
if i==5:
break
print(i)
i=i+1
#WHEN THE CONDITION MATCHES THE BREAK STATEMENT THE PROGRAM COMES OUT FROM THE LOOP CONDITION.
print('\n\n')
#CONTINUE STATEMENT
i=0
while i<=10:
if i==5:
continue
print(i)
i=i+1
|
ef426a4e507abe2c79d2fbfb1254338170d78417 | A8IK/PYthon-3 | /class in class.py | 520 | 3.84375 | 4 | #outer class
class Student:
def __init__(self,name,roll_number):
self.name=name
self.roll_number=roll_number
self.lap=self.Laptop
def show(self):
print(self.name,self.roll_number)
#inner class
class Laptop:
def __init__(self):
self.brand='Dell'
self.cpu='i5'
self.ram='8gb'
s1=Student('Atik',2)
s2=Student('Emma',3)
s1.show()
s2.show()
lap1=s1.lap
lap2=s2.lap
print(id(lap1))
print(id(lap2))
|
f8e63e22a82c9a05672dbefb096f3c4498925183 | WhiteRobe/ShuaTi | /leetcode/linklist/两数相加2.py | 1,413 | 3.734375 | 4 | """
题目来源:
LeetCode
@See https://leetcode-cn.com/problems/add-two-numbers/
题目序号 2
题目描述:
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
思路:
注意代码的鲁棒性即可,要防止 5 + 5 这种只算到 5 而忘了进位的情况
样例输入:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
样例输出:
输出:7 -> 0 -> 8
原因:342 + 465 = 807
"""
from structure.list_node import ListNode
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
head, carry = ListNode(None), 0 # 哑节点和进位指示器
current = head
while l1 or l2 or carry:
l1_val = l1.val if l1 else 0
l2_val = l2.val if l2 else 0
sums = l1_val + l2_val + carry
carry = int(sums >= 10)
new_node = ListNode(sums % 10)
current.next = new_node
current, l1, l2 = current.next, self.safe_next(l1), self.safe_next(l2)
return head.next
def safe_next(self, l):
return l.next if l else l
|
0339a143eeeaf10360675edce1153213c83979b8 | dasherinuk/classwork | /pairs_claaswork_6.4.py | 223 | 3.578125 | 4 | n = int(input())
arr=[]
for i in range(n):
arr.append(int(input()))
arr_pairs = []
for i in range(0, n-n%2, 2):
arr_pairs.append([arr[i],arr[i+1]])
if n%2==1:
arr_pairs.append([arr[-1],0])
print(arr_pairs)
|
3e1eadc54e18dc815da5c5eb8bbf9a5986ddacaf | JPWS2013/SoftwareDesign | /chap16/double_day.py | 3,229 | 3.59375 | 4 | import datetime as dt
def dayofweek():
days=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
dateToday=dt.date.today()
dayofWeek=dateToday.weekday()
return days[dayofWeek]
def birthday(birthdate):
t=birthdate.split('/')
bday=dt.date(int(t[2]), int(t[1]), int(t[0]))
dateToday=dt.date.today()
age=dateToday-bday
ageDays=age.days
year_rest=divmod(ageDays, 365)
years=year_rest[0]
months_rest=divmod(year_rest[1], 30)
months=months_rest[0]
days=months_rest[1]
age=(years, months, days)
bdaytuple=(bday.month, bday.day)
dateTodayTuple=(dateToday.month, dateToday.day)
if bdaytuple<dateTodayTuple:
nextbday=bday.replace(year=dateToday.year+1)
else:
nextbday=bday.replace(year=dateToday.year)
timeLeft=nextbday-dateToday
return [age, timeLeft]
def doubleday(bd1, bd2):
t1a=bd1.split('/')
t2a=bd2.split('/')
BDay1=dt.date(int(t1a[2]), int(t1a[1]), int(t1a[0]))
BDay2=dt.date(int(t2a[2]), int(t2a[1]), int(t2a[0]))
if BDay1>BDay2:
t1=BDay1
t2=BDay2
else:
t2=BDay1
t1=BDay2
age2_start=t1-t2
age2Days=age2_start.days
age1Days=0
i=0
while age2Days!=2*age1Days:
i+=1
age1Days+=1
age2Days+=1
occurs=t1+dt.timedelta(i)
return occurs
def general_day(bd1, bd2, n=2):
t1a=bd1.split('/')
t2a=bd2.split('/')
BDay1=dt.date(int(t1a[2]), int(t1a[1]), int(t1a[0]))
BDay2=dt.date(int(t2a[2]), int(t2a[1]), int(t2a[0]))
if BDay1>BDay2:
t1=BDay1
t2=BDay2
else:
t2=BDay1
t1=BDay2
age2_start=t1-t2
age2Days=age2_start.days
age1Days=0
i=0
while age2Days!=n*age1Days:
i+=1
age1Days+=1
age2Days+=1
occurs=t1+dt.timedelta(i)
return occurs
if __name__ == '__main__':
#------------------
#Part 1 Test Code
#------------------
# print dayofweek()
#---------------------
#Part 2 Test Code
#---------------------
bday=raw_input("Please Enter Your Date of Birth (DD/MM/YYY): ")
timeleft=birthday(bday)
print "Your age is ", timeleft[0][0], "years, ", timeleft[0][1], "months and ", timeleft[0][2], "days. There are ", timeleft[1], "until your next birthday"
#--------------------
#Part 3 Test Code
#--------------------
# bday1=raw_input("Please Enter the First Person's Date of Birth (DD/MM/YYY): ")
# bday2=raw_input("Please Enter the Second Person's Date of Birth (DD/MM/YYY): ")
# res=doubleday(bday1, bday2)
# print "The date of your DoubleDay is/was: ", res
#--------------------
#Part 4 Test Code
#--------------------
# bday1=raw_input("Please Enter the First Person's Date of Birth (DD/MM/YYY): ")
# bday2=raw_input("Please Enter the Second Person's Date of Birth (DD/MM/YYY): ")
# n=raw_input("What age gap would you like to calculate (e.g. one is twice as old or three times as old etc.)? ")
# #print int(n)
# res=general_day(bday1, bday2, int(n))
# print "The date at which your chosen age gap will occur/has occired: ", res |
b0522cf36195f6e573d7da25965bda85c38beadf | aannddrree/projaulapython170321 | /ex7.py | 150 | 3.640625 | 4 | frutas = ["pera", "morango", "banana","maca", "uva", "amora"]
frutas[0] = "Sei la"
frutas.sort()
for f in frutas:
print(f)
print("Terminei") |
ec7a3ae8111108a6307258d90965f017f1370be7 | himanshu98-git/python_notes | /DataStructuure/task.py | 363 | 4.125 | 4 | words=["orange","banana","apple","orange","papaya","apple","banana","orange","papaya","orange","banana","orange","apple","papaya"]
str="Hi my name is Himanshu"
str1=" "
from collections import Counter
word_counts =Counter(words)
top_three=word_counts.most_common(3)
print(top_three)
spaces=str.isspace()
space=str1.isspace()
print(spaces)
print(space)
|
01a3db43411eb16679fc0b4b83f0370ff323b9e1 | RaghvendraPateriya/algo | /tree/tree_traversal.py | 2,292 | 4.03125 | 4 | """
Print Tree Level Wise:
Given Tree:
1 <= level 0
/ \
2 3 <= level 1
/ \ / \
4 5 6 7 <= level 2
Output: 1 2 3 4 5 6 7
"""
class Tree:
def __init__(self, data, left=None, right=None) -> None:
self.data = data
self.left = left
self.right = right
# In Order Traversal
# In Given Input Tree
# Output: 4 -> 2 -> 5 -> 1 -> 6 -> 3 -> 7
# Steps:
# 1. Traverse Left sub tree
# 2. Traverse Root node
# 3. Traversr Right sub tree
# Left -> root -> right
def in_order_traversal(root_node):
node = root_node
if (node):
in_order_traversal(node.left)
print(node.data)
in_order_traversal(node.right)
# In Pre Order Traversal [ up to bottom]
# In Given Input Tree
# Output: 1 -> 2 -> 4 -> 5 -> 3 -> 6 -> 7
# Steps:
# 1. Traverse Root node
# 2. Traverse Left subtree
# 3. Traverse Right subtree
# Root -> Left -> Right
def pre_order_traversal(root_node):
node = root_node
if (node):
print(node.data)
pre_order_traversal(node.left)
pre_order_traversal(node.right)
# In Post Order Traversal [bottom to up]
# In Given Input Tree
# Output: 4 -> 5 -> 2 -> 6 -> 7 -> 3 -> 1
# Steps:
# 1. Traverse Left Sub Tree
# 2. Traverse Right Sub Tree
# 3. Traverse root node
# Left -> Right -> Root
def post_order_traversal(root_node):
node = root_node
if (node):
post_order_traversal(node.left)
post_order_traversal(node.right)
print(node.data)
# Print Tree Level Wise
def traverse_tree_level_wise(root_node):
node = root_node
node_list = [node]
while node_list:
temp_list = []
for nl in node_list:
print(nl.data)
if nl.left:
temp_list.append(nl.left)
if nl.right:
temp_list.append(nl.right)
node_list = temp_list
if __name__ == '__main__':
# Create Tree
root_node = Tree(1, Tree(2, Tree(4), Tree(5)), Tree(3, Tree(6), Tree(7)))
# Print tree left node first
#print_tree(root_node)
# Print Tree Level Wise
# traverse_tree_level_wise(root_node)
# in_order_traversal(root_node)
# pre_order_traversal(root_node)
post_order_traversal(root_node)
|
80f353fac23277e1e967c04a8a16853dc5ffe5f3 | argriffing/xgcode | /DiscreteEndpoint.py | 15,598 | 3.734375 | 4 | """
Condition a Markov chain on its endpoints.
The Markov chain is discrete and first order.
Find the expected number of transitions.
"""
import unittest
import itertools
import math
import numpy as np
import Util
import StatsUtil
import TransitionMatrix
import HMM
import iterutils
def get_expected_transitions_brute(prandom, nstates, nsteps):
"""
This function is for transition matrices defined by their size and a single parameter.
Use brute force to compute transition expectations.
This function returns two values.
The first value is the expected number of transitions
when the endpoints are the same.
The second value is the expected number of transitions
when the endpoints are different.
@param prandom: the probability of randomization at each step
@param nstates: the number of states in the chain
@param nsteps: one fewer than the length of the sequence
@return: (expected_t_same, expected_t_different)
"""
# handle corner cases
if not nsteps:
return 0.0, float('nan')
if nsteps == 1:
return 0.0, 1.0
if not prandom:
return 0.0, float('nan')
# precalculate stuff
p_notrans = prandom / nstates + (1 - prandom)
p_particular_trans = prandom / nstates
p_any_trans = p_particular_trans * (nstates - 1)
# initialize probabilities
total_p_different = 0
total_p_same = 0
# initialize expectations
e_same = 0
e_different = 0
# define expectations
for sequence in itertools.product(range(nstates), repeat=nsteps+1):
# Calculate the probability of the sequence
# and the number of transitions.
ntransitions = 0
p = 1.0 / nstates
for a, b in iterutils.pairwise(sequence):
if a == b:
p *= p_notrans
else:
p *= p_particular_trans
ntransitions += 1
# add to the expectation
if sequence[0] == sequence[-1]:
total_p_same += p
e_same += p * ntransitions
else:
total_p_different += p
e_different += p * ntransitions
e_same /= total_p_same
e_different /= total_p_different
return e_same, e_different
def get_expected_transitions_binomial(prandom, nstates, nsteps):
"""
This function is for transition matrices defined by their size and a single parameter.
Use binomial coefficients to compute transition expectations.
@param prandom: the probability of randomization at each step
@param nstates: the number of states in the chain
@param nsteps: one fewer than the length of the sequence
@return: (expected_t_same, expected_t_different)
"""
# handle corner cases
if not nsteps:
return 0.0, float('nan')
if nsteps == 1:
return 0.0, 1.0
if not prandom:
return 0.0, float('nan')
# precalculate stuff
p_notrans = prandom / nstates + (1 - prandom)
p_any_trans = 1.0 - p_notrans
# precalculate expected probability of each endpoint pair state
prandom_total = 1 - (1 - prandom)**nsteps
p_notrans_total = prandom_total / nstates + (1 - prandom_total)
# initialize expectations
e_same = 0
e_different = 0
# define expectations
for ntrans in range(nsteps+1):
log_p_ntrans = StatsUtil.binomial_log_pmf(ntrans, nsteps, p_any_trans)
p_ntrans = math.exp(log_p_ntrans)
p_same = (1 - (1 - nstates)**(1 - ntrans))/nstates
e_same += p_same * p_ntrans * ntrans
e_different += (1 - p_same) * p_ntrans * ntrans
e_same /= p_notrans_total
e_different /= (1 - p_notrans_total)
return e_same, e_different
class Chain:
"""
This is an endpoint constrained Markov chain.
The conditional transition expectation matrix can be computed
using the forward and backward algorithms with scaling.
"""
def __init__(self, transition_object):
"""
@param transition_object: returns a transition probability given two states and a distance
"""
self.nstates = transition_object.get_nstates()
self.transition_object = transition_object
self.initial_distribution = [transition_object.get_stationary_probability(i) for i in range(self.nstates)]
def forward(self, initial_state, final_state, nsteps):
"""
@param initial_state: the first state in the sequence
@param final_state: the last state in the sequence
@param nsteps: the number of transitions in the sequence
@return: the list of lists of scaled f variables, and the scaling variables
"""
T = self.transition_object.get_transition_probability
# initialize
f = [[0]*self.nstates for i in range(nsteps+1)]
s = [0]*(nsteps+1)
# define the initial f variable and scaling factor
for state in range(self.nstates):
f[0][state] = 1.0 if state == initial_state else 0.0
s[0] = 1.0
# define the subsequent f variables and scaling factors
for i in range(1, nsteps+1):
# define an unscaled f variable at this position
for sink_index in range(self.nstates):
if i < nsteps or sink_index == final_state:
f[i][sink_index] = 1.0
else:
f[i][sink_index] = 0.0
p = 0
for source_index in range(self.nstates):
p += f[i-1][source_index] * T(source_index, sink_index)
f[i][sink_index] *= p
# define the positive scaling factor at this position
s[i] = sum(f[i])
if not s[i]:
raise ValueError('scaling factor is zero at position %d' % i)
# define the scaled f variable at this position
for sink_index in range(self.nstates):
f[i][sink_index] /= s[i]
return f, s
def backward(self, final_state, nsteps, scaling_factors):
"""
The scaling factors must have been calculated using the scaled forward algorithm.
@param final_state: the last state in the sequence
@param nsteps: the number of transitions in the sequence
@param scaling_factors: the scaling factor for each position
@return: the list of lists of scaled b variables
"""
T = self.transition_object.get_transition_probability
b = [[0]*self.nstates for i in range(nsteps+1)]
b[nsteps] = [1/scaling_factors[nsteps]]*self.nstates
for i in reversed(range(nsteps)):
for source_index in range(self.nstates):
accum = 0
for sink_index in range(self.nstates):
if i + 1 < nsteps or sink_index == final_state:
p = 1.0
p *= T(source_index, sink_index)
p *= b[i+1][sink_index]
accum += p
b[i][source_index] = accum / scaling_factors[i]
return b
def get_dp_info(self, initial_state, final_state, nsteps):
"""
Do the dynamic programming and return the results.
These results can be used for computing posterior expectations of
emissions, of hidden states, and of transition counts.
@param initial_state: the first state in the sequence
@param final_state: the last state in the sequence
@param nsteps: the number of transitions in the sequence
@return: initial_state, final_state, nsteps, f, s, b
"""
f, s = self.forward(initial_state, final_state, nsteps)
b = self.backward(final_state, nsteps, s)
return (initial_state, final_state, nsteps, f, s, b)
def get_transition_expectations(self, dp_info):
"""
@param dp_info: this is from get_dp_info
@return: a matrix of expected transition counts
"""
initial_state, final_state, nsteps, f, s, b = dp_info
T = self.transition_object.get_transition_probability
# initialize the matrix of expected counts
A = np.zeros((self.nstates, self.nstates))
# get the expected counts for each transition
for sink_index in range(self.nstates):
for source_index in range(self.nstates):
for i in range(1, nsteps+1):
if i < nsteps or sink_index == final_state:
p = 1.0
p *= f[i-1][source_index]
p *= T(source_index, sink_index)
p *= b[i][sink_index]
A[source_index, sink_index] += p
return A
def get_transition_expectations_brute(self, initial_state, final_state, nsteps):
"""
@return: a matrix of expected transition counts
"""
T = self.transition_object.get_transition_probability
# initialize the matrix of expected counts
A = np.zeros((self.nstates, self.nstates))
# compute the probability of observing the final state conditional on the first state
p_total = T(initial_state, final_state, nsteps)
# iterate over all possible sequences of missing states
for missing_sequence in itertools.product(range(self.nstates), repeat=nsteps-1):
sequence = [initial_state] + list(missing_sequence) + [final_state]
# get the probability of observing this continuation of the initial state
p = 1.0
for a, b in iterutils.pairwise(sequence):
p *= T(a, b)
# add the weighted transitions of each type
for a, b in iterutils.pairwise(sequence):
A[a, b] += p
# divide by the total probability so that the conditioning is correct
A /= p_total
return A
def get_expectations(self, dp_info):
"""
@param dp_info: this is from get_dp_info
@return: an expectation for each state
"""
initial_state, final_state, nsteps, f, s, b = dp_info
v = np.zeros(self.nstates)
for fs, bs, si in zip(f, b, s)[1:-1]:
for state, (x, y) in enumerate(zip(fs, bs)):
v[state] += x*y*si
return v
def get_expectations_brute(self, initial_state, final_state, nsteps):
"""
Get the number of times each state was expected to occur between the initial and final positions.
@return: an expectation for each state
"""
T = self.transition_object.get_transition_probability
# initialize the vector of expected counts
v = np.zeros(self.nstates)
# compute the probability of observing the final state conditional on the first state
p_total = T(initial_state, final_state, nsteps)
# iterate over all possible sequences of missing states
for missing_sequence in itertools.product(range(self.nstates), repeat=nsteps-1):
sequence = [initial_state] + list(missing_sequence) + [final_state]
# get the probability of observing this continuation of the initial state
p = 1.0
for a, b in iterutils.pairwise(sequence):
p *= T(a, b)
# add the weighted transitions of each type
for state in missing_sequence:
v[state] += p
# divide by the total probability so that the conditioning is correct
v /= p_total
return v
class TestDiscreteEndpoint(unittest.TestCase):
def test_brute(self):
prandom = 0.001
nstates = 4
nsteps = 6
e_same, e_different = get_expected_transitions_brute(prandom, nstates, nsteps)
def test_binomial(self):
for prandom in (0.01, 0.99, 1.0):
for nstates in range(2, 6):
for nsteps in range(1, 4):
expected = get_expected_transitions_brute(prandom, nstates, nsteps)
observed = get_expected_transitions_binomial(prandom, nstates, nsteps)
self.assertTrue(np.allclose(expected, observed))
def test_chain_expected_transitions_brute_compatibility(self):
"""
Test a reduced-parameter transition matrix for which a method already exists.
"""
# the following parameters define the sequence distribution
prandom = 0.1
nstates = 3
nsteps = 6
# create the chain object
transition_object = TransitionMatrix.UniformTransitionObject(prandom, nstates)
chain = Chain(transition_object)
# compare the expected number of changes
A = chain.get_transition_expectations_brute(0, 0, nsteps)
e_same_a = np.sum(A) - np.sum(np.diag(A))
A = chain.get_transition_expectations_brute(0, 1, nsteps)
e_different_a = np.sum(A) - np.sum(np.diag(A))
e_same_b, e_different_b = get_expected_transitions_brute(prandom, nstates, nsteps)
# the methods should give identical results
self.assertAlmostEqual(e_same_a, e_same_b)
self.assertAlmostEqual(e_different_a, e_different_b)
def test_chain_expected_transitions(self):
"""
Compare brute force results to dynamic programming results.
"""
# define the sequence distribution
T = np.array([
[.1, .6, .3],
[.1, .1, .8],
[.8, .1, .1]])
nstates = len(T)
nsteps = 5
# create the chain object
transition_object = TransitionMatrix.MatrixTransitionObject(T)
chain = Chain(transition_object)
# compare the matrices defining the transition expectations
for i_state, e_state in itertools.product(range(nstates), repeat=2):
# compute the brute force result and the dynamic programming result
A_brute = chain.get_transition_expectations_brute(i_state, e_state, nsteps)
A_dynamic = chain.get_transition_expectations(chain.get_dp_info(i_state, e_state, nsteps))
# assert that for each method the sum of the expectations is equal to the number of steps
self.assertAlmostEqual(np.sum(A_brute), nsteps)
self.assertAlmostEqual(np.sum(A_dynamic), nsteps)
# assert that the methods give the same result
self.assertTrue(np.allclose(A_brute, A_dynamic))
def test_chain_expectations(self):
"""
Compare brute force results to dynamic programming results.
"""
# define the sequence distribution
T = np.array([
[.1, .6, .3],
[.1, .1, .8],
[.8, .1, .1]])
nstates = len(T)
nsteps = 5
# create the chain object
transition_object = TransitionMatrix.MatrixTransitionObject(T)
chain = Chain(transition_object)
# compare the matrices defining the transition expectations
for i_state, e_state in itertools.product(range(nstates), repeat=2):
# compute the brute force result and the dynamic programming result
v_brute = chain.get_expectations_brute(i_state, e_state, nsteps)
v_dynamic = chain.get_expectations(chain.get_dp_info(i_state, e_state, nsteps))
# assert that for each method the sum of the expectations is equal to the number of steps minus one
self.assertAlmostEqual(np.sum(v_brute), nsteps-1)
self.assertAlmostEqual(np.sum(v_dynamic), nsteps-1)
# assert that the methods give the same result
self.assertTrue(np.allclose(v_brute, v_dynamic))
if __name__ == '__main__':
unittest.main()
|
c90678d55ee5b9f93592088ff86e0d1f742306b8 | jakeTran42/CS-2-Tweet-Generator | /rearrange.py | 613 | 3.640625 | 4 | import random
import sys
# words = ['time', 'space', 'antimatter', 'universe', 'neutron']
words = sys.argv[1:]
def create_random_quote():
word = []
num_already_used = []
counter = 0
while counter < len(words):
rand_index = random.randint(0, len(words) - 1)
if rand_index not in num_already_used:
word.append(words[rand_index])
num_already_used.append(rand_index)
counter += 1
return word
quote = ' '.join(create_random_quote())
if __name__ == '__main__':
# quote = create_random_quote()
quotes = ' '.join(quote)
print(quote)
|
17a1a2373d96a9af3ba25106819eea54ad4e4b41 | andreamena/Girls_Who_Code2 | /turtle4.py | 608 | 4.1875 | 4 |
from turtle import *
import math
alex=Turtle()
alex.pensize(10)
alex.turtlesize(4,4)
pendown()
def drawShapes(turtle,sides,color):
turtle.pencolor(color)
drawnSides = 0
sides = sides+1
angle = 360/sides
turtle.speed("slow")
while drawnSides < sides:
turtle.forward(50)
turtle.right(angle)
drawnSides+=1
print("How many sides do you want your shape to have?")
numsides = int(input())
print ("What color do you want your shape to be?")
colorchosen=input()
drawShapes(alex,numsides,colorchosen)
exitonclick()
|
ca53c4e005e8c0b699944da5b46d2512f6216cde | ElizaLo/Practice-Python | /Python 3 Programming/course 2/c_2_ex_4.py | 1,437 | 4.21875 | 4 | '''
Write a function called int_return that takes an integer as input and returns the same integer.
'''
def int_return(x):
return x
'''
Write a function called add that takes any number as its input and returns that sum with 2 added.
'''
def add(num):
return num + 2
'''
Write a function called change that takes any string, adds “Nice to meet you!” to the end of the argument given,
and returns that new string.
'''
def change(s):
return '{}Nice to meet you!'.format(s)
'''
Write a function, accum, that takes a list of integers as input and returns the sum of those integers.
'''
def accum(lst):
total = 0
for i in lst:
total += i
return total
'''
Write a function, length, that takes in a list as the input. If the length of the list is greater than or equal to 5,
return “Longer than 5”. If the length is less than 5, return “Less than 5”.
'''
def length(lst):
if len(lst) >= 5:
return 'Longer than 5'
return 'Less than 5'
'''
You will need to write two functions for this problem. The first function, divide that takes in any number and
returns that same number divided by 2.
The second function called sum should take any number, divide it by 2, and add 6. It should return this new number.
You should call the divide function within the sum function. Do not worry about decimals.
'''
def divide(num):
return num / 2
def sum(x):
return divide(x) + 6
|
225492ddd62ba73a80a7b3a45b72e0efcc069a85 | MelihCelik00/GEO106E | /geo106e_lab projeler/LabWork4/010180519_labwork4.3.py | 284 | 3.625 | 4 | months1_519 = ("January","February","March","April","May","June")
months2_519 = ("July","August","September","October","November","December")
all_months_519 = months1_519 + months2_519
print(all_months_519)
print(all_months_519.index("June"))
print(all_months_519.index("August")) |
98166987ddd2c9c7ea30f39450960eecd0c7b52e | Xiankai-Wan/Python-Quiz-Summarize | /Python-语法/Part2/2-15_创建程序段2.py | 622 | 4.15625 | 4 | # 练习:创建帮助函数 sum_of_middle_three
# 现在是时候完成 sum_of_middle_three 这个函数了。确保使用打印语句测试该函数。可以根据之前编写的框架开始。你可以使用 max() 和 min() 查找最大值和最小值。max() 返回一组数字中的最大值,min() 返回最小值。例如:
# max(1,2,3,4) #returns 4
# min(1,2,3,4) #returns 1
def sum_of_middle_three(score1,score2,score3,score4,score5):
return (score1 + score2 + score3 + score4 + score5)-min(score1,score2,score3,score4,score5)-max(score1,score2,score3,score4,score5)
print(sum_of_middle_three(1,2,3,4,5))
|
4b94b2efcada09f4ba4bb55fa089b97dc1fcdb5c | lucastrindadesilva/aulasProgramacao | /Aula 2/selecao_repeticao.py | 202 | 3.609375 | 4 | bruno = 29
sosnierz = 36
lucas = 30
booleano = True
if bruno > sosnierz:
if bruno > lucas:
print("O mais velho é Bruno")
else:
print("O mais velho é Lucas")
#construam o else |
d34c980651fb83e0dc8a959191ff72da8dfd21bf | silverdoe23/python-lessons | /binaryNumbers/binaryIteration.py | 910 | 4.125 | 4 | #!/usr/bin/python
def isBinary(x): #this function will determine if the number inputed is a binary number
for a in x:
if a != 0 and a != 1:
print('please input a valid binary number. Try again.')
return False
return True
def valueBinary(x):#this function will determine the value of the binary number
thisValue = 1 #a, in this function, is what the value of the place is
total = 0 #c is the value of the number
for y in range(len(x)-1,-1, -1):
if x[y] == 1:
total = total + thisValue
thisValue = thisValue * 2
return total
def getInput():
tf = False
while tf == False:
i = input("Please input a valid binary number.\n")
tf = isBinary(i)
if tf == True:
return i
def calcMyBinary():
inp = getInput()
print(valueBinary(inp))
if __name__ == '__main__':
calcMyBinary()
|
39d587042b81f1800dee7f42a0a1c7c94bd9841a | Fbocciii/Python-Training | /AdvancedPython-2-Assignment1.py | 3,759 | 4.15625 | 4 | # 1. Create a Python Generators to generate the vowels. This should be a cyclic generators and will generate infinte list of vowels.
# -------------
# 2. Let's imagine a scenario where we have a Server instance running different services such as http and ssh on different ports. Some of these services have an active state while others are inactive.
#
# class Server:
#
# services = [
# {'active': False, 'protocol': 'ftp', 'port': 21},
# {'active': True, 'protocol': 'ssh', 'port': 22},
# {'active': True, 'protocol': 'http', 'port': 80},
# ]
#
# - Create an iterators for the Server class which would loop over only the active ports
# - Create a generator class that does the same thing
#
# -------------
# 3.Write a password generator in Python. Be creative with how you generate passwords - strong
# passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols. The
# passwords should be random, generating a new password every time the user asks for a new
# password. Include your run-time code in a main method.
# Extra:
# Ask the user how strong they want their password to be. For weak passwords, pick a word
# or two from a list.
#
# -------------
#4. Use the BeautifulSoup and requests Python packages to print out a list of all the article titles on the New York Times homepage.(https://www.nytimes.com/)
#Part 1
from itertools import cycle
print("Vowels generated in cyclic fashion:")
vowels = cycle(['a', 'e', 'i', 'o', 'u', 'y'])
for i in range(10):
print(next(vowels))
#Part 2
class Server:
services = [
{'active': False, 'protocol': 'ftp', 'port': 21},
{'active': True, 'protocol': 'ssh', 'port': 22},
{'active': True, 'protocol': 'http', 'port': 80},
]
def __init__(self):
self.__counter = 0
def __iter__(self):
return self
def __next__(self):
while self.__counter < len(self.services):
self.__counter += 1
if self.services[self.__counter - 1]['active']:
return self.services[self.__counter - 1]
raise StopIteration
def service_generator(server : Server = Server()):
counter = 0
while counter < len(server.services):
if server.services[counter]["active"]:
yield server.services[counter]
counter += 1
raise StopIteration
ser = Server()
ser_it = iter(ser)
print("\nMade with iterator:")
while True:
try:
print(next(ser_it))
except StopIteration:
break
print("\nMade with generator:")
ser_gen = service_generator()
while True:
try:
print(next(ser_gen))
except RuntimeError or StopIteration:
break
#Part 3
import random as r
import re
def main():
password_generator()
def password_generator():
pass_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHYJKLMNOPQRSTYUVWXYZ1234567890!@#$%^&*+="
char_count = r.randrange(8, 12)
password = ""
for i in range(char_count):
password += pass_chars[r.randrange(0, len(pass_chars))]
while re.match(r'[A-Za-z0-9!@#$%^&*+=]{8,}', password) == False:
password += pass_chars[r.randrange(0, len(pass_chars))]
print("\nGenerated password:")
print(password,"\n")
if __name__ == "__main__":
main()
#Part 4
from bs4 import BeautifulSoup
import requests
url = "https://www.nytimes.com/"
html = requests.get(url, timeout=10).content
soup = BeautifulSoup(html, "html.parser")
divs = soup.find_all(name="h2") #all article titles stored in h2 tags
print("\nNY Times home page articles right now:")
for article in divs[:-2]: #Leave out last 2 because they are headers for site index and navigation
if article.get_text().strip() != "":
print(article.get_text())
#print(divs) |
f9169420d4e112349487da508a8c9b3f138c1552 | darrencheng0817/AlgorithmLearning | /Python/sorting/exercise/countInversions.py | 755 | 3.515625 | 4 | '''
Created on 2015年12月10日
@author: Darren
'''
global count
count=0
def mergeSort(nums):
if len(nums)<=1:
return nums
m=len(nums)//2
return merge(mergeSort(nums[:m]),mergeSort(nums[m:]))
def merge(nums1,nums2):
index1,index2=0,0
res=[]
global count
while index1<len(nums1) and index2<len(nums2):
if nums1[index1]>nums2[index2]:
count+=len(nums1)-index1
res.append(nums2[index2])
index2+=1
else:
res.append(nums1[index1])
index1+=1
for i in range(index1,len(nums1)):
res.append(nums1[i])
for i in range(index2,len(nums2)):
res.append(nums2[i])
return res
nums=[2,1]
print(mergeSort(nums))
print(count)
|
2cb59a8eeb377d2e06641d1792292e63d0ab92bd | lishuang1994/-1807 | /01day/09-文件备份系统.py | 383 | 3.9375 | 4 | #1.获取用户要复制的文件名
old_file_name = input("请输入要复制的文件名")
#2.打开要复制的文件
old_file = open(old_file_name,"r")
#3.新建一个文件
new_file = open("新建.txt","w")
#4.从旧文件中读取数据,并且写入新的文件中
content = old_file.read()
new_file.write(content)
#5.关闭两个文件
old_file.close()
new_file.close()
|
7f18652d181d1cd6e325185746b17ced0885ece3 | Rad-wane/FreeCodeCamp-certification-projects | /'Data science with Python' certification/Sea-level-predictor/sea_level_predictor.py | 1,018 | 3.78125 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
def draw_plot():
# Read data from file
df=pd.read_csv('epa-sea-level.csv')
# Create scatter plot
plt.plot(df['Year'],df['CSIRO Adjusted Sea Level'])
# Create first line of best fit
slope, y_intercept, r_value, p_value, std_err = stats.linregress(df['Year'],df['CSIRO Adjusted Sea Level'])
x=np.linspace(1880,2050,171)
y=slope*x+y_intercept
plt.plot(x,y)
# Create second line of best fit
df_n=df[df['Year']>=2000]
slope, y_intercept, r_value, p_value, std_err = stats.linregress(df_n['Year'],df_n['CSIRO Adjusted Sea Level'])
x=np.linspace(2000,2050,51)
y=slope*x+y_intercept
plt.plot(x,y)
# Add labels and title
plt.title('Rise in Sea Level')
plt.xlabel("Year")
plt.ylabel("Sea Level (inches)")
# Save plot and return data for testing (DO NOT MODIFY)
plt.savefig('sea_level_plot.png')
return plt.gca() |
9848dbbca48711584e75370b4fc4f99ce1893362 | RitaWxy/PythonBase | /codeExercise/syntaxTree.py | 379 | 3.609375 | 4 | Num = lambda env,n : n
Val = lambda env,x : env[x]
Add = lambda env,a,b : _eval(env,a)+_eval(env,b)
Mul = lambda env,a,b : _eval(env,a)*_eval(env,b)
_eval = lambda env,expr : expr[0](env,*expr[1:])
env = {'a':3,'b':6}
tree = (Add,(Val,'a'),
(Mul,(Num,5),(Val,'b'))
)
print(_eval(env,(Val,'a')))
print(_eval(env,(Num,5)))
print(Num(env,5))
print(_eval(env,tree)) |
5daa73b09c99893a77cc347b27fa1247f28cf3f9 | ashermanwmf/test | /ex6.py | 989 | 4.3125 | 4 | # writing a string with a number in it
x = 'There are %d types of people.' % 10
# creating a string variable
binary = 'binary'
# creating a string variable
do_not = "don't"
# created a string and added two other variable strings
y = 'Those who know %s and those who %s.' % (binary, do_not)
# printed both x and y variable
print x
print y
# printed a sting and added the string with an integer by converting it with repr()#
print "I said: %r." % x
# printing a string and adding a variable with other variables added
print "I also said: '%s'." % y
# created two variables one can accept an integer or string by passing through repr()#
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
# print the string variable and add the boolean experssion variable to the end#
print joke_evaluation % hilarious
# created two variables with strings
w = 'This is the left side of...'
e = 'a string with a right side.'
# added variables with strings together like math
print w + e |
9b22594ed01eacfad1bd1b9d1bbc5818e1d1481e | pocceschi/aprendendo_git | /operadores/exretangulo.py | 268 | 3.78125 | 4 | b = float(input("Base do retangulo: "))
a = float(input("Altura do retangulo: "))
area = float(a*b)
perimetro = float(a+a+b+b)
diagonal = float((a**2 + b**2) ** 0.5)
print(f"Area: {area:.4f}")
print(f"Perimetro: {perimetro:.4f}")
print(f"Diagonal: {diagonal:.4f}")
|
8de78b297005e2bdc058c29503fb0f2f88c65807 | asariakevin/timetable-comparison-app | /main.py | 2,758 | 3.8125 | 4 | from timetable import TimeTable
timetable1 = TimeTable()
timetable2 = TimeTable()
timetable1.monday = ["7 to 12" , "13 to 15", "16 to 18"]
timetable2.monday = ["8 to 10" , "14 to 16" , "17 to 18"]
NUMBER_OF_HOURS = 11
hour_taken_array = []
# initialize hour_taken_array to zeros
for one_hour_period in range(NUMBER_OF_HOURS):
hour_taken_array.append(0)
hours_string_prompt = ""
for hour in range(7,19):
hours_string_prompt = hours_string_prompt + str(hour) + "\t"
# split the scheduled periods to one hour periods
def split_into_one_hour_components( day_schedule ):
# arrays to store the one hour periods
schedule_time_pairs = []
for schedule in day_schedule:
# first split into given hours
timeScheduleList = schedule.split()
startHour = int( timeScheduleList[0])
finishHour = int( timeScheduleList[-1])
if finishHour - startHour > 1:
# need to create new strings
lesson_length = finishHour - startHour
this_hour = startHour
for hour in range(lesson_length):
next_hour = this_hour + 1
new_schedule_time = str(this_hour) + " to " + str(next_hour) #create a new hour string
schedule_time_pairs.append(new_schedule_time)
this_hour = next_hour
else:
schedule_time_pairs.append(schedule)
for time_pair in schedule_time_pairs:
print(time_pair)
return schedule_time_pairs
def map_one_hour_slots_to_hour_taken_array( scheduled_one_hour_time):
mappings = {
"7 to 8" : 0,
"8 to 9" : 1,
"9 to 10" : 2,
"10 to 11" : 3,
"11 to 12" : 4,
"12 to 13" : 5,
"13 to 14" : 6,
"14 to 15" : 7,
"15 to 16" : 8,
"16 to 17" : 9,
"17 to 18" : 10,
}
for one_hour_period in scheduled_one_hour_time:
index_in_hours_taken_array = mappings.get( one_hour_period , "Invalid hour")
hour_taken_array[ index_in_hours_taken_array ] = 1
print(hour_taken_array)
def print_a_timetable_to_the_terminal():
print( hours_string_prompt)
shade = ""
for hour_taken in hour_taken_array:
if hour_taken == 1:
shade+=("|" * 8)
else:
shade+="\t"
print( shade)
print( shade)
print( shade)
print( shade)
list_of_one_hour_slots_2 = split_into_one_hour_components(timetable2.monday)
list_of_one_hour_slots_1 = split_into_one_hour_components(timetable1.monday)
map_one_hour_slots_to_hour_taken_array( list_of_one_hour_slots_1)
map_one_hour_slots_to_hour_taken_array( list_of_one_hour_slots_2)
print_a_timetable_to_the_terminal()
|
bfff47c86361065344d66e90c20cbc1262ea0831 | brettlod/flicklist-python | /crypto/initials.py | 447 | 4.09375 | 4 | def get_initials(fullname):
initial = fullname[0]
found = False
for letter in fullname:
if found is True:
initial = initial + letter
found = False
elif letter == " ":
found = True
else:
initial = initial
return initial.upper()
def main():
fullname=input("What is your full name?")
print(get_initials(fullname))
if __name__ == '__main__':
main()
|
9e405be15c83aa24524158a6fe3fa8d1f3413974 | OverCastCN/Python_Learn | /XiaoZzi/Practice100/17StringClassify.py | 472 | 3.921875 | 4 | # -*- coding:utf-8 -*-
import string
"""
题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
"""
aplha = 0
space = 0
num = 0
other = 0
a = raw_input()
for i in a:
if i.isalpha():
aplha += 1
elif i.isspace():
space += 1
elif i.isdigit():
num += 1
else:
other += 1
print '中英文字母:',aplha
print '空格:',space
print '数字:',num
print '其它:',other
|
5d9d6fc814a78ec2ed128c42543c39d991683d38 | DakotaDecker/cis1415 | /Chapter 7: Additional Exercise 5.py | 3,869 | 3.734375 | 4 | user = input('Enter a phone number in the format XXX-XXX-XXXX:\n')
print('You entered:', user)
user = user.upper()
user = user.replace('A', '2')
user = user.replace('B', '2')
user = user.replace('C', '2')
user = user.replace('D', '3')
user = user.replace('E', '3')
user = user.replace('F', '3')
user = user.replace('G', '4')
user = user.replace('H', '4')
user = user.replace('I', '4')
user = user.replace('J', '5')
user = user.replace('K', '5')
user = user.replace('L', '5')
user = user.replace('M', '6')
user = user.replace('N', '6')
user = user.replace('O', '6')
user = user.replace('P', '7')
user = user.replace('Q', '7')
user = user.replace('R', '7')
user = user.replace('S', '7')
user = user.replace('T', '8')
user = user.replace('U', '8')
user = user.replace('V', '8')
user = user.replace('W', '9')
user = user.replace('X', '9')
user = user.replace('Y', '9')
user = user.replace('Z', '9')
print('Just digits:', user)
'''
# Excessive amount of code, but it works
for x in user:
if x == 'A' or 'B' or 'C':
user = user.replace('A', '2')
user = user.replace('B', '2')
user = user.replace('C', '2')
if x == 'D' or 'E' or 'F':
user = user.replace('D', '3')
user = user.replace('E', '3')
user = user.replace('F', '3')
if x == 'G' or 'H' or 'I':
user = user.replace('G', '4')
user = user.replace('H', '4')
user = user.replace('I', '4')
if x == 'J' or 'K' or 'L':
user = user.replace('J', '5')
user = user.replace('K', '5')
user = user.replace('L', '5')
if x == 'M' or 'N' or 'O':
user = user.replace('M', '6')
user = user.replace('N', '6')
user = user.replace('O', '6')
if x == 'P' or 'Q' or 'R' or 'S':
user = user.replace('P', '7')
user = user.replace('Q', '7')
user = user.replace('R', '7')
user = user.replace('S', '7')
if x == 'T' or 'U' or 'V':
user = user.replace('T', '8')
user = user.replace('U', '8')
user = user.replace('V', '8')
if x == 'W' or 'X' or 'Y' or 'Z':
user = user.replace('W', '9')
user = user.replace('X', '9')
user = user.replace('Y', '9')
user = user.replace('Z', '9')
'''
'''
# Function that replaces every character in the string
# with a 2 for some reason.
# I'm not sure why it isn't working, but theoretically
# this would be the shortest way to solve the problem.
# Make sure to call the function in the print statement!
def replace(num):
for x in num:
if x == 'A' or 'B' or 'C':
num = num.replace(x, '2')
if x == 'D' or 'E' or 'F':
num = num.replace(x, '3')
if x == 'G' or 'H' or 'I':
num = num.replace(x, '4')
if x == 'J' or 'K' or 'L':
num = num.replace(x, '5')
if x == 'M' or 'N' or 'O':
num = num.replace(x, '6')
if x == 'P' or 'Q' or 'R' or 'S':
num = num.replace(x, '7')
if x == 'T' or 'U' or 'V':
num = num.replace(x, '8')
if x == 'W' or 'X' or 'Y' or 'Z':
num = num.replace(x, '9')
return num
# Similarly, this function returns a string of all 9s
def replace(num):
digits = ''
for x in num:
if x == 'A' or 'B' or 'C':
x = '2'
if x == 'D' or 'E' or 'F':
x = '2'
if x == 'G' or 'H' or 'I':
x = '2'
if x == 'J' or 'K' or 'L':
x = '5'
if x == 'M' or 'N' or 'O':
x = '6'
if x == 'P' or 'Q' or 'R' or 'S':
x = '7'
if x == 'T' or 'U' or 'V':
x = '8'
if x == 'W' or 'X' or 'Y' or 'Z':
x = '9'
digits += x
return num
'''
|
902a32bf028b4ee195a1f4ad32d4232aac643c6e | chenxy3791/leetcode | /No0876-middle-of-the-linked-list.py | 2,889 | 3.875 | 4 | """
876. 链表的中间结点
给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
示例 1:
输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5])
返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。
注意,我们返回了一个 ListNode 类型的对象 ans,这样:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.
示例 2:
输入:[1,2,3,4,5,6]
输出:此列表中的结点 4 (序列化形式:[4,5,6])
由于该列表有两个中间结点,值分别为 3 和 4,我们返回第二个结点。
提示:
给定链表的结点数介于 1 和 100 之间。
解题思路:
快慢指针。
块指针前进两步,慢指针前进一步
"""
import math
import time
import numpy as np
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
if head == None:
return None
fast = head
slow = head
while fast.next != None and fast.next.next != None:
fast = fast.next.next
slow = slow.next
if fast.next == None:
return slow
else:
return slow.next
if __name__ == '__main__':
sln = Solution()
print('\ntestcase1 ...')
[1,2,3,4,5]
head = ListNode(1)
second = ListNode(2)
third = ListNode(3)
fourth = ListNode(4)
fifth = ListNode(5)
head.next = second
second.next = third
third.next = fourth
fourth.next = fifth
tStart= time.time()
middle = sln.middleNode(head)
h = middle
while h != None:
print(h.val)
h = h.next
tStop = time.time()
print('tStart={0}, tStop={1}, tElapsed={2}(sec)'.format(tStart, tStop, tStop-tStart))
print('\ntestcase2 ...')
[1,2,3,4,5,6]
head = ListNode(1)
second = ListNode(2)
third = ListNode(3)
fourth = ListNode(4)
fifth = ListNode(5)
sixth = ListNode(6)
head.next = second
second.next = third
third.next = fourth
fourth.next = fifth
fifth.next = sixth
tStart= time.time()
middle = sln.middleNode(head)
h = middle
while h != None:
print(h.val)
h = h.next
tStop = time.time()
print('tStart={0}, tStop={1}, tElapsed={2}(sec)'.format(tStart, tStop, tStop-tStart))
print('\ntestcase3 ...')
[1]
head = ListNode(1)
middle = sln.middleNode(head)
h = middle
while h != None:
print(h.val)
h = h.next
tStop = time.time()
print('tStart={0}, tStop={1}, tElapsed={2}(sec)'.format(tStart, tStop, tStop-tStart))
|
2c709afde8adea6987bb824e3657e3b5e393b8a3 | sagar104511/spe | /Calculator.py | 223 | 3.765625 | 4 | def sum(a,b):
return a+b
def diff(a,b):
return a-b
def multiply(a,b):
return a*b
def divide(a,b):
return a//b
if __name__ == "__main__":
print(sum(4,2))
print(diff(4,2))
print(multiply(4,2)) |
9e47bc6c049a19db25b8faf2999ab10d29beb158 | saiakhil0034/cse253 | /assignments/hw2/PA2/test.py | 385 | 3.515625 | 4 | class B(object):
"""docstring for B"""
def __init__(self, arg):
super(B, self).__init__()
self.arg = arg
self.c = [1, 2]
class A(object):
"""docstring for A"""
def __init__(self, arg):
super(A, self).__init__()
self.arg = arg
self.b = [B(arg), B(arg + 1)]
a1 = A(1)
c1 = a1.b[0].c.copy()
a1.b[0].c[0] = 3
print(c1)
|
d9ce7a58f4f41c39ab0e1bbefb092b71c222ea4b | kangwonlee/15ecab | /wk02/use_sequential.py | 181 | 3.734375 | 4 | # -*- coding: cp949 -*-
import root_finding
def f2(x):
return float(x*x) - 3.0
print root_finding.sequential(f2, 0.01)
print root_finding.sequential(root_finding.func, 0.01)
|
4a7b5d782dbe376fccee9fe230df8aaf2b8fb0de | Priyansh2906/cryptographic-algorithms | /Playfair.py | 3,491 | 3.78125 | 4 | import numpy as np
key = input("Enter a key : ")
rectified_key_letters = "".join(dict.fromkeys(key)) #removes all duplicate letters
alpha=[chr(i) for i in range(97,123)] #Generates a list of all alphabtes
key_letters = [] #List of letters included in key so that we can know remaining letters to add into 5x5 matrix
for i in rectified_key_letters:
key_letters.append(i)
for i in key_letters:
if i=='j':
key_letters.remove(i)
for i in alpha:
if i not in key_letters:
if i =='j':
pass
else:
key_letters.append(i)
print(key_letters)
matrix = np.array(key_letters).reshape(5,5)
print(matrix)
plain_text = input("\n\nEnter plain text : ")
plain_text = plain_text.replace(" ","") #removing blank spaces from plain_text
pairs = [(plain_text[i:i+2]) for i in range(0, len(plain_text), 2)]
#Padding x if there is only one letter in pair
for i in range(0,len(pairs)):
if len(pairs[i])==1:
pairs[i] = pairs[i]+'x'
#Padding x if two letters are same in a pair
for i in range(0,len(pairs)):
temp_letter = ""
for letters in pairs[i]:
if letters==temp_letter:
temp_letter = temp_letter+'x'
else:
temp_letter = temp_letter+letters
pairs[i] = temp_letter
print("The pairs are : ",pairs)
position_list = []
for two_letters in pairs:
position_list_temp = []
for letter in two_letters:
row_col = []
#Iterating the array
for i in range(0,5):
for j in range(0,5):
temp = matrix[i][j]
if temp == letter:
row_col.append(i)
row_col.append(j)
position_list_temp.append(row_col)
position_list.append(position_list_temp)
print("positions of each letter are : \n",position_list,"\n\n")
#Main conditions
cipher_text = ""
#0 will be rows
#1 will be coloums
for i in position_list:
letter1=""
letter2=""
#checking if rows are equal
if i[0][0] == i[1][0]:
if i[0][1]==4: #if col of only letter 1 is 4 (ending col)
letter1 = matrix[i[0][0]][i[0][1]-4] #wrapping around
letter2 = matrix[i[1][0]][i[1][1]+1] #letter2 will be as it is
elif i[1][1]==4: #if only col of letter2 is 4 (ending col)
letter1 = matrix[i[0][0]][i[0][1]+1] #letter1 will be as it is
letter2 = matrix[i[1][0]][i[1][1]-4] #wrapping around
else:
letter1 = matrix[i[0][0]][i[0][1]+1]
letter2 = matrix[i[1][0]][i[1][1]+1]
#checking if cols are equal
elif i[0][1] == i[1][1]:
if i[0][0]==4: #if row of letter1 is 4 (ending row)
letter1 = matrix[i[0][0]-4][i[0][1]] #wrapping around
letter2 = matrix[i[1][0]+1][i[1][1]] #as it is
elif i[1][0]==4: #if row of letter2 i 4 (ending row)
letter1 = matrix[i[0][0]+1][i[0][1]] #as it is
letter2 = matrix[i[1][0]-4][i[1][1]] #wrapping around
else:
letter1 = matrix[i[0][0]+1][i[0][1]]
letter2 = matrix[i[1][0]+1][i[1][1]]
#if neither rows and cols are equal
else:
letter1 = matrix[i[0][0]][i[1][1]] #takes same row , different col for letter 1
letter2 = matrix[i[1][0]][i[0][1]] #takes same row , different col for letter 2
cipher_text=cipher_text+letter1+letter2
print("The encrypted text is : "+cipher_text)
|
c284d3231f39051b27c7db6e856ea8c8fa9de65a | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/b946e078bb904b47bf67863586198872.py | 661 | 3.984375 | 4 | # -*- coding: utf-8 -*-
import re
"""
Bob answers 'Sure.' if you ask him a question.
He answers 'Woah, chill out!' if you yell at him.
He says 'Fine. Be that way!' if you address him without actually saying
anything.
He answers 'Whatever.' to anything else.
"""
def hey(text):
# Remove whitespace and check if string is empty
text = text.strip()
if not text:
return 'Fine. Be that way!'
# Check if string contains letters and is all uppercase
elif text.isupper():
return 'Woah, chill out!'
# Check if the string is a question
elif text.endswith("?"):
return 'Sure.'
else:
return 'Whatever.'
|
2dafa8ea5598a172064f3b41178c0b40838f259f | mbebiano/exercicios-python | /exerciciocoursera/MaiorPrimo.py | 578 | 3.671875 | 4 | def maior_primo(num):
count = 1
acum = 0
a = 0
b = False
while b==False:
while count <= num:
if num % count == 0:
acum += 1
else:
a += 1
count += 1
if acum == 2:
b = True
else:
num = num - 1
acum = 0
count= 1
return num
num_primo = int(input('Digite nº primo maior ou igual a 2: '))
while num_primo < 2 :
num_primo = int(input('Digite nº primo maior ou igual a 2: '))
print(maior_primo(num_primo))
|
ac3f65a3b83083f5938a612e64ad528a12eaa497 | rohitb2310/python_Programming | /Assingment1.py | 500 | 3.515625 | 4 | f=open("File.txt","r") ## opening the file
content = f.read() ## reading the data in a variable
print(content) ##printing all the content
##s="I am Rohit I am Rohit"
l=content.split() ##Splitting the content
dictonary={ } ##creatin the blank dictonary
for word in l:
if word in dictonary: ## if word is present increse the value of the word otherwise leave it
dictonary[word]=dictonary[word] + 1
else:
dictonary[word]=1 ## if not present increament it by 1
print(dictonary)
|
6731e03f888de7f5fd43578663fae935f513215c | daniel-reich/ubiquitous-fiesta | /5h5uAmaAWY3jSHA7k_7.py | 355 | 3.8125 | 4 |
def landscape_type(lst):
while lst[0]==lst[1]:lst=lst[1:]
while lst[-1]==lst[-2]:lst=lst[:-1]
l=[i[1]-i[0] for i in zip(lst,lst[1:])]
if 0 in l: return "neither"
l=[i>0 for i in l]
if all(l) or not any(l): return 'neither'
for i in range(1,len(l)-1):
if l[i-1]==l[i+1]!=l[i]: return "neither"
return "mountain" if l[0] else "valley"
|
0093bd5b9d8312844956f4e6ef5967f2ce989a94 | Mohamed209/Python_OOP_tutorial | /LogicGate.py | 2,536 | 3.609375 | 4 | class LogicGate: # super class Logic Gate
def __init__(self,label):# init function to set label and output
self.label=label
self.output=None
# function to check if input is valid boolean value
'''ef check_valid_input(self):
assert int(input()) is bool, "0 and 1 are only valid inputs"
return True'''
def get_label(self):
return self.label
def get_output(self):
self.output=self.perform_logic()
return self.output
class BinaryGate(LogicGate):# binary gate class inherits logic gate class
# overriding parent class init method
def __init__(self,label):
LogicGate.__init__(self,label) # init binary gate is the same as logic gate , but with two new lines of code ,that init input
self.pin1=None # input 1
self.pin2=None # input 2
# get input for the gate
def getPin1(self):
return int(input("Enter Pin 1 input for gate " + self.get_label() + "-->"))
def getPin2(self):
return int(input("Enter Pin 2 input for gate " + self.get_label()+ "-->"))
def setNextPin(self,dest):
if self.pinA == None:
self.pinA = dest
else:
if self.pinB == None:
self.pinB = dest
else:
print("Cannot Connect: NO EMPTY PINS on this gate")
class UnaryGate(LogicGate):
def __init__(self,n):
LogicGate.__init__(self,n)
self.pin = None
def getPin(self):
return int(input("Enter Pin input for gate "+ self.get_label()+"-->"))
class AndGate(BinaryGate):
def __int__(self,label):
BinaryGate.__init__(self,label)
def perform_logic(self):
a,b=[self.getPin1(),self.getPin2()]
return (a and b)
class OrGate(BinaryGate):
def __int__(self,label):
BinaryGate.__init__(self,label)
def perform_logic(self):
a,b=[self.getPin1(),self.getPin2()]
return (a or b)
# connector class implements HAS-A relationship
class Connector:
def __init__(self,gatefrom,gateto): # init with two gates
self.gatefrom=gatefrom
self.gateto=gateto
gateto.setNextPin(self)
def get_gatefrom(self):
return self.gatefrom
def get_gateto(self):
return self.gateto
g1=AndGate("and1")
print("gate name",g1.get_label())
print("gate inputs ",g1.pin1,g1.pin2,"gate output",g1.output)
print(g1.get_output())
g2=OrGate("or1")
print("gate name",g2.get_label())
print("gate inputs ",g2.pin1,g2.pin2,"gate output",g2.output)
print(g2.get_output()) |
2f12d891c6f56bb927463407996cd327a0b85ae7 | lsgos/MPhysPulsars | /src/SemiSupervisedClassifier.py | 1,400 | 3.65625 | 4 | """
A class factory to abstract the creation of a semi-supervised classifier
from a novelty detection method
"""
from sklearn.tree import DecisionTreeClassifier
class SemiSupervisedClassifier(object):
def __init__(self, novelty_detector, noise_label = 0):
self.novelty_clf = novelty_detector
self.stump = DecisionTreeClassifier(max_depth=1, criterion='entropy')
self.noise_label = noise_label
def fit(self, X, Y):
"""
Fit the isolation forest only on negative data, then train a threshold
stump on the isolation score
"""
train_noise = X [Y == self.noise_label]
#fit the isolation forest
self.novelty_clf.fit(train_noise)
#transform the dataset using the outlier detector and train the
#stump to pick the threshold
anomaly_train = self.novelty_clf.decision_function(X).reshape(-1,1)
self.stump.fit(anomaly_train, Y)
def predict(self, X):
anomaly_scores = self.novelty_clf.decision_function(X).reshape(-1,1)
return self.stump.predict(anomaly_scores)
def decision_function(self, X):
return (-1) * self.novelty_clf.decision_function(X)
def score(self, X, Y):
"""Accuracy score for the classifier """
anomaly_scores = self.novelty_clf.decision_function(X).reshape(-1,1)
return self.stump.score(anomaly_scores, Y)
|
a79dd2293cdf8578a35653afbed338f640cd2e61 | SiddharthBhawsar/Python-Bootcamp-with-OOPS | /14_FileIO_Basics.py | 1,872 | 4.25 | 4 | # #File IO Basics
#
# """
# "r" - Open File in Read Mode
# "w" - Open File in Write Mode
# "x" - Creates File if not exist
# "a" - Add more content of file/append
# "t" - Text mode
# "b" - Binary Mode
# "+" - Read and Write both
# """
#
#
# #Here open function returns a file pointer and
# # in our case it gets stores in f
# f=open("piemr")
# content=f.read()
# print(content)
# #
# f.close()
#
# #r is default mode and t(text file) is default type
# f=open("piemr", "rt")
# content=f.read()
# print(content)
# #
# f.close()
# #
# f=open("piemr", "rt")
# content=f.read(3)
# print(content)
#
# #
# content=f.read(3)
# print(content)
# #
# f.close()
#
#
#
# #If you want to read line line by line than you may itrerate the lines
# f=open("piemr", "rt")
# content=f.read()
# # #
# for char in content:
# print(char, end=" ")
# #
# f.close()
#
#
# # f=open("piemr", "rt")
# # # content=f.read()
# #
# # for line in content:
# # print(line, end="")
# #
# # f.close
#
#
# #Read line function
# f=open("piemr", "rt")
# # for i in range(3):
# print(f.readline())
# print(f.readline())
# print(f.readline())
# #
# # # #readlines for print in form of list
# f=open("piemr", "rt")
# print(f.readlines())
# f.close()
#
# #Writing and Appending to file
# f=open("piemr", "w")
# f.write("Python Scripting")
# f.close()
# #
# f=open("piemr", "w")
# # f.write("Hello World")
# (f.write("I hope you are Enjoying"))
#
# f.close()
# # #
# f=open("piemr", "a")
# f.write("I hope you are Enjoying")
# f.close()
#
#
# # #Handle read and write both
# f=open("piemr","r+")
# # print(f.read())
# f.write("Thank You")
#
#
# f=open("piemr1")
# #Access file by with Block
with open("piemr1") as f:#it replaces both functions like open and close
a=f.read()
print(a)
#
#
|
f91acf4428c7cf2467a16846ff5f463e122a90be | aishukanagaraj/exe1 | /exe3/firstlast.py | 281 | 3.78125 | 4 | def firstdigit(n):
while(n>=10):
n=n//10
return (int(n))
def lastdigit(n):
return (n%10)
def lastfirst(n):
flag=True
if not(firstdigit(n)==lastdigit(n)):
flag=False
return flag
n=input("Enter the number")
print(lastfirst(n))
|
38e77d814161a799cfe6f61a52a009a45116cd07 | AlexBardDev/Project_Euler | /euler_7.py | 642 | 3.96875 | 4 | """
problem:
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
import math
K = 10001
LIST_PRIME_NUMBERS = [2, 3, 5]
M = 2
while len(LIST_PRIME_NUMBERS) < K:
is_prime = True
MAYBE_PRIME = LIST_PRIME_NUMBERS[-1] + M
for nb in range(3, math.ceil(MAYBE_PRIME/2)):
if MAYBE_PRIME%nb == 0:
is_prime = False
break #Not a prime number
if is_prime == True:
LIST_PRIME_NUMBERS.append(MAYBE_PRIME)
M = 2
else:
M += 2
print(LIST_PRIME_NUMBERS[-1])
|
3d126a7a28ff5bd642b48b6d2a200c63c6e5e6db | lktolon/Ejercicios-Estructura-Secuencial-Phyton | /ejercicio16.py | 284 | 3.703125 | 4 | v1 = float(input("Velocidad del primer vehículo:"))
v2 = float(input("Velocidad del segundo vehículo):"))
dist = float(input("Distancia entre ambos vehículos:"))
t = dist / abs(v1 - v2)
t = t * 60
print("El primer vehículo alcanzará al segundo en ", tiempo,"minutos.")
|
17815767dd719c5422f258b237363e857ee3723d | jothamsl/Learning_Python | /1.0/Non-Primitives/Lists/Lists.py | 628 | 4.1875 | 4 | # A list contains items separated by commas and enclosed within square brackets
# []. Lists are almost similar to arrays in C. One difference is that all the
# items belonging to a list can be of different data type.
list = [21, 'Hello world!', 23.1, 'f']
list1 = ['What up', 'world']
print(list) # [21, 'Hello world!', 23.1, 'f']
print(list[0:2]) # Output's first two elements, [21, 'Hello world!']
print(list1 * 2) # Output's list1 two times, ['What up', 'world', 'What up', 'world']
print(list + list1) # Output's concatenatioon of both the lists
# [21, 'Hello world!', 23.1, 'f', 'What up', 'world']
|
22cf85f4339057fbbded653f7a95749bf9f9e7a4 | Marauderer97/LSI-Internship | /Rahul-code/point_at_dist.py | 1,883 | 3.609375 | 4 | # to find point B on line at distance D from point A on same line
import sys
from sympy import *
from fractions import Fraction
def point_at_dist(pt1, pt2, distance):
if pt1 == pt2:
print 'invalid line'
sys.exit()
# Check for slop 0 and infinite
if pt1[0] == pt2[0]:
p1, p2, p3, p4 = (pt1[0], pt1[1]+distance), (pt1[0], pt1[1]-distance), (pt2[0], pt2[1]+distance),\
(pt2[0], pt2[1]-distance)
return [p1, p2, p3, p4]
elif pt1[1] == pt2[1]:
p1, p2, p3, p4 = (pt1[0]+distance, pt1[1]), (pt1[0]-distance, pt1[1]), (pt2[0]+distance, pt2[1]),\
(pt2[0]-distance, pt2[1])
return [p1, p2, p3, p4]
m = (pt1[1]-pt2[1])/(pt1[0]-pt2[0])
p1 = (pt1[0] + dx(distance, m), pt1[1] + dy(distance, m))
p2 = (pt1[0] - dx(distance, m), pt1[1] - dy(distance, m))
p3 = (pt2[0] + dx(distance, m), pt2[1] + dy(distance, m))
p4 = (pt2[0] - dx(distance, m), pt2[1] - dy(distance, m))
return [p1, p2, p3, p4]
def dy(distance, m):
return m*dx(distance, m)
def dx(distance, m):
return distance/sqrt((m**2+1))
def perpendicular_point(stp, ep, p):
d1, d2 = tuple(x-y for x, y in zip(stp, ep))
if d2 == 0: # If a horizontal line
if p[1] == stp[1]: # if p is on this linear entity
# print p
# print tuple(x+y for x, y in zip(p, (0.0, 100.0)))
return tuple(x+y for x, y in zip(p, (0.0, 100.0)))
else:
p2 = (p[0], stp[1])
return p2
else:
p2 = (p[0] - d2, p[1] + d1)
return p2
if __name__ == '__main__':
points = point_at_dist((1.0, 1.0), (2.0, 4.0), 10.0/9.0)
print points
# points = point_at_dist((1.0, 1.0), (1.0, 4.0), 5.0)
# print points
# points = point_at_dist((1.0, 1.0), (2.0, 1.0), 5.0)
# print points
print sqrt(5) |
bef32217407cad77849c4c82eb2221db538bc75a | zenuie/leetcode | /reverse-integer.py | 411 | 3.515625 | 4 | class Solution:
def reverse(self, x: int) -> int:
y = str(abs(x))[::-1]
if int(x) < 0:
x = abs(x)
x = str(x)[::-1]
if 2 ** 31 - 1 > int(x) > -2 ** 31:
x = int(x) - 2 * int(x)
return x
return 0
elif 2 ** 31 - 1 > int(y) > -2 ** 31:
x = str(x)[::-1]
return int(x)
return 0
|
99c1ab004943351df0250aca750d53b70cd9c796 | NikiDimov/SoftUni-Python-Advanced | /modules/snake_game.py | 3,451 | 3.609375 | 4 | import pygame
import time
import random
pygame.init()
clock = pygame.time.Clock()
orangecolor = (255, 123, 7)
blackcolor = (0, 0, 0)
redcolor = (213, 50, 80)
greencolor = (0, 255, 0)
bluecolor = (50, 153, 213)
display_width = 600
display_height = 400
dis = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("Snake Game")
snake_block = 10
snake_speed = 15
snake_list = []
def snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(dis, orangecolor, [x[0], x[1], snake_block, snake_block])
def snakegame():
game_over = False
game_end = False
x1 = display_width / 2
y1 = display_height / 2
x1_change = 0
y1_change = 0
snake_list = []
Length_of_snake = 1
foodx = round(random.randrange(0, display_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, display_height - snake_block) / 10.0) * 10.0
while not game_over:
while game_end == True:
dis.fill(blackcolor)
font_style = pygame.font.SysFont("comicsansms", 25)
mesg = font_style.render("You Lost! Wanna play again? Press P", True, redcolor)
dis.blit(mesg, [display_width / 6, display_height / 3])
score = Length_of_snake - 1
score_font = pygame.font.SysFont("comicsansm", 35)
value = score_font.render("Your Score: " + str(score), True, greencolor)
dis.blit(value, [display_width / 3, display_height / 5])
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
snakegame()
if event.type == pygame.QUIT:
game_over = True
game_end = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
if x1 >= display_width or x1 < 0 or y1 >= display_height or y1 < 0:
game_end = True
x1 += x1_change
y1 += y1_change
dis.fill(blackcolor)
pygame.draw.rect(dis, greencolor, [foodx, foody, snake_block, snake_block])
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_list.append(snake_Head)
if len(snake_list) > Length_of_snake:
del snake_list[0]
for x in snake_list[:-1]:
if x == snake_Head:
game_end = True
snake(snake_block, snake_list)
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, display_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, display_height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
clock.tick(snake_speed)
pygame.quit()
quit()
snakegame()
|
73b86d002bb4bc66513775aa788be41b09a33733 | zuobing1995/tiantianguoyuan | /第一阶段/day15/exercise/myfactorial.py | 449 | 3.890625 | 4 | # 练习:
# 写一个生成器函数myfactorial(n)此函数用来生成n个从1开始的阶乘
# def myfactorial(n):
# ...
# L = list(myfactorial(5)) # L = [1, 2, 6, 24, 120]
# # 1! 2! 3! 4! 5!
def myfactorial(n):
s = 1 # 用来保存阶乘
for x in range(1, n + 1):
s *= x
yield s
L = list(myfactorial(5)) # L = [1, 2, 6, 24, 120]
print(L)
print(sum(myfactorial(5)))
|
4ba78b4aeaa075137cce343ee60fcb65230be6e7 | PMKeene/SoftwareDesign | /SoftwareDesignExplore/GUI_Experimentation/GUI_Hello1.py | 245 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Mar 2 01:43:45 2014
@author: maire
"""
#Doesn't Display Text--
#To Fix: Make text
#WWWHHHHHHYYYYYY!!!
from Tkinter import *
root= Tk()
w=Label(root, text="Hello, world!")
w.pack
root.mainloop()
|
e8f737cbc342616e3f805115c898a560ac6ae949 | KocUniversity/comp100-2021f-ps0-nevzatozh1 | /main.py | 177 | 3.65625 | 4 | print("Enter number x: 10")
print("Enter number y: 4")
x=10
y=4
print("x . y=",x**y)
import math
print("logarithm base 2 of 10 is: ", end="")
print(math.log2(10))
print("78987") |
94e1cf8d1dbc5a40fce920025424bd33890ec4d3 | bitwoman/curso-em-video-python | /Curso de Python 3 - Mundo 1 - Fundamentos/#029.py | 396 | 3.953125 | 4 | # Exercício Python 029: Escreva um programa que leia a velocidade de um carro.
# Se ele ultrapassar 80Km/h, mostre uma mensagem dizendo que ele foi multado.
# A multa vai custar R$7,00 por cada Km acima do limite.
velocity = float(input('Enter a velocity of the car: '))
if velocity > 80:
traffic_ticket = (velocity - 80) * 7
print(f'Fined! The traffic ticket is R$%.2f' %traffic_ticket)
|
519cd45393e228d0f502a7dadee824ba7321a1e2 | dudu9999/Exerc-cio_de_casa_01 | /Exercicio 01.py | 250 | 3.796875 | 4 | #Ler dois numeros N1 e N2 nesta ordem e
#imprimir as variaveis N1 e N2 nesta ordem ordem
#de digitação
N1, N2 = 0, 0
N1 = int(input("digite um numero: "))
N2 = int(input("digite outro numero: "))
print("Primeiro numero",N1,"segundo numero",N2)
|
51ebbaf9f347edb7b5405258f60870651f45a312 | yutoo89/python_programing | /basic_grammar/indention.py | 253 | 4.0625 | 4 | # 80文字以上になる場合は改行するのがルール
s = 'aaaaaaaaa' \
+ 'bbbbbbbb'
print(s)
x = 1 + 1 + 1 + 1 + 1 + 1 + 1 \
+ 1 + 1 + 1 + 1 + 1 + 1 + 1
print(x)
x = (1 + 1 + 1 + 1 + 1 + 1 + 1
+ 1 + 1 + 1 + 1 + 1 + 1 + 1)
print(x) |
3eded02154416ee8ee73f226fd308056bbf86c07 | TheSauceWizard/Team-A1 | /arran.py | 2,376 | 4.09375 | 4 | import time as t
print ("""
I approach the man.
"Hey, what brings you to this part of town?"
"Please sit Detective Frankestein, we have much to discuss."
My curosity compelled me to sit down.
"Who are you and how did you know my name?"
"My name is Chris Requiredfield.
I am working with Special Tactics and Resource Server or S.T.A.R.S to trackdown Hackula."
he procalims, taking a sip from his bottle "I knew your name because I worked with your father."
""")
t.sleep(2)
print(""""Why are you telling me this, what has it got to do with me?" I asked with frustration.
"This has everything to do with you.
Only you have enough data to resist his powers. You've done it before and must do it again."
"What do you mean? I have never even met 'Hackula,' I doubt he even exists." my voice raising in frustration.
"I understand that things may be confusing at the moment but all we explained over the next couple of days.
Meet me tomorrow at the church in town around 7 o'clock."
He hands me a map of Transfervania and took a final drink from his bottle, stands up and then leaves.
""")
t.sleep(2)
print("""The night will soon become dawn. I grow weary. I book a room in the pub and I fall asleep quickly.
""")
t.sleep(2)
print("""I wake up from the sound of a gentle breeze with no fatigue whatsoever. I rise from the double bed I slept in and check the clock mounted on the wall opposite me. It reads 14:01, I overslept. However, I still have 5 hours before I planned to meet with Chris.
I can only do one thing before I meet with him.
""")
variable1 = input("What do I do in that time? Investigate the town(1), Investigate around the pub(2) or Sleep until the time(3)")
if variable1 == "1":
statement1 = False
elif variable1 == "2":
statement1 = False
elif variable1 == "3":
statement1 = False
else:
statement1 = True
print("""I leave my room going down the old wooden staircase, I find the pub to be empty.
""")
variable2 = input("Do i? Investigate the bar(1) Investigate the back alley(2) Go back and rest(3)")
if variable2 == "1":
statement1 = False
elif variable2 == "2":
statement1 = False
elif variable2 == "3":
statement1 = False
else:
statement1 = True
print("""I look around the bar. There is nothing out of the ordinary and the bartender is no where to be seen.
""")
|
39a95bcf84c8d28c96f772442811d98e443f03bf | mishu45/lang2sign | /lang2sign/utils/secrets.py | 2,009 | 3.78125 | 4 | """
Utility to access secrets stored in files
or to input them on prompt
"""
# pylint: disable=unexpected-keyword-arg
import os
from getpass import getpass
class Secret(object):
"""
Secret class to store and retrieve secret
"""
def __init__(self, name, filepath):
self.name = name
self.filepath = filepath
self.full_path = self.filepath
def set_base_directory(self, directory):
self.filepath = os.path.join(
directory,
self.filepath
)
def get(self):
with open(self.full_path, "r") as file_obj:
return file_obj.read()
def set(self, value):
os.makedirs(
os.path.dirname(self.full_path),
exist_ok=True
)
with open(self.full_path, "w") as file_obj:
file_obj.write(value)
def get_or_prompt(self):
try:
value = self.get()
except IOError:
value = getpass(
("{name} not found at {filepath}. Please type in.\n" + \
"**Note this will write your input to {filepath}:\n").format(
name=self.name,
filepath=self.full_path
)
)
self.set(value)
return value
class SecretManager(object):
"""
Stores and retrieves secrets from files
"""
def __init__(self, secrets):
self.secrets = {
secret.name: secret for secret in secrets
}
def set_base_directory(self, directory):
for secret in self.secrets.values():
secret.set_base_directory(directory)
def get(self, name):
try:
return self.secrets[name]
except KeyError:
raise KeyError(
"No secret registered with name {}".format(name)
)
manager = SecretManager([
Secret("aws_access_key_id", "secrets/aws_access_key_id"),
Secret("aws_secret_access_key", "secrets/aws_secret_access_key")
])
|
82643189cda450671431f428882c635cbe5395d0 | shuhailshuvo/Learning-Python | /16.Error.py | 780 | 3.5625 | 4 |
import sys
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
randomList = ['a', 0, [1, 2], True]
for entry in randomList:
# Comon exceptions
r = None
try:
print("The entry is", entry)
r = 1/int(entry)
break
except ValueError:
print("Oops!", sys.exc_info()[0], "occured.,")
print("ValueErrors are handled exclussively ")
print()
raise MemoryError("This is an argument")
raise ValueTooSmallError("This is an argument")
except:
print("Oops!", sys.exc_info()[0], "occured.")
print("Next entry.")
print()
print("The reciprocal of", entry, "is", r)
|
53af1074bba2776e8cb349efcfac02febd681eab | greenlucid/oeis | /b02.py | 1,587 | 3.65625 | 4 | # Tomas 'Green' Roca Sanchez
# b02.1 : F(n) has same number of prime factors than F(n+1), with F(a) being the Fibonacci sequence
# b02.2 : The specific Fibonacci numbers
# b02.3 : Number of prime factors of F(n)
# Instead of having to factor these numbers, I fetched a file with the first 1000 Fibonacci factorizations
# Credit to http://mersennus.net/fibonacci/ [email protected]
# So this script only has to load in the information and compare it with itself
f = open("f1000.txt", "r")
data = f.readlines()
#Stores the list of factors for each element. F(0), F(1) and F(2) are non applicable
fibf = [[],[],[]]
#process and store the input data
for i in range(3,1001):
cur = []
j = 0
while data[i][j]!='=':
j+=1
j+=1
lastj = j
while j < len(data[i]):
if data[i][j] == '*':
cur.append(data[i][lastj+1:j-1])
lastj=j+1
j+=1
cur.append(data[i][lastj+1:j-1])
fact = []
for st in cur:
if '^' in st:
# search for ^ as breakpoint
j = len(st)-2
while st[j] != '^':
j-=1
a = int(st[:j])
b = int(st[j+1:])
for ii in range(b):
fact.append(a)
else:
fact.append(int(st))
fibf.append(fact)
s_1 = [0,1]
s_2 = [0,1]
s_3 = [0,0,0]
for i in range(3,len(fibf)-1):
if len(fibf[i]) == len(fibf[i+1]):
s_1.append(i)
mul = 1
for j in fibf[i]:
mul*=j
s_2.append(mul)
s_3.append(len(fibf[i]))
print("s_1: ", s_1)
print("s_2: ", s_2)
print("s_3: ", s_3) |
835aa1645294360680a9630cb9e04dd15a55a06b | eunseo5355/python_school | /lab3_4.py | 703 | 3.9375 | 4 | """
사용자로부터 연도를 입력받아서, 해당 연도가 몇일로 구성되어 있는지 출력하라.
4로 나누어 떨어지면 윤년이다. 단, 100으로 나누어 떨어지면 윤년이 아니며,
400으로 나누어 떨어지면 윤년이다.
입력예)
연도: 2000
출력예)
366일입니다.
"""
y = int(input("연도:")) # 입력받기
if y % 4 == 0 and y % 100 != 0:
print("366일입니다.")
elif y % 400 == 0:
print("366일입니다.")
else:
print("365일입니다.")
"""
if y%4==0:
print("366일입니다.")
if y%100==0:
print("365일입니다.")
if y%400==0:
print("366일입니다.")
else:
print("365일입니다.")
""" |
5926ecdd76558ba15b643a9b10aeb6b3a2239f4d | Henry-the-junior/tictactoe_teaching_resource | /tictactoe_ep5-3.py | 2,532 | 3.921875 | 4 | def drawBoard(board):
# This function prints out the board that it was passed.
# "board" is a list of 10 strings representing the board (ignore index 0)
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
def isSpaceFree(board, move):
# Return true if the passed move is free on the passed board.
return board[move] == ' '
def getXMove(board):
move = ' '
while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board, int(move)):
print('What is your next move? (1-9)')
move = input()
move = int(move)
board[move] = 'X'
def getOMove(board):
move = ' '
while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board, int(move)):
print('What is your next move? (1-9)')
move = input()
move = int(move)
board[move] = 'O'
def whoGoesFirst():
who = ''
while not (who == 'O' or who == 'X'):
who = input('Who goes first?')
return who
def isWinner(board, turn):
# Given a board and a player's letter, this function returns True if that player has won.
return ((board[7] == turn and board[8] == turn and board[9] == turn) or # across the top
(board[4] == turn and board[5] == turn and board[6] == turn) or # across the middle
(board[1] == turn and board[2] == turn and board[3] == turn) or # across the bottom
(board[7] == turn and board[4] == turn and board[1] == turn) or # down the left side
(board[8] == turn and board[5] == turn and board[2] == turn) or # down the middle
(board[9] == turn and board[6] == turn and board[3] == turn) or # down the right side
(board[7] == turn and board[5] == turn and board[3] == turn) or # diagonal
(board[9] == turn and board[5] == turn and board[1] == turn)) # diagonal
print('Welcome to Tic Tac Toe!')
# Reset the board
theBoard = [' '] * 10
turn = whoGoesFirst()
print('The ' + turn + ' will go first.')
gameIsPlaying = True
while gameIsPlaying:
if turn == 'X':
# X's turn.
drawBoard(theBoard)
getXMove(theBoard)
turn = 'O'
else:
# O's turn.
drawBoard(theBoard)
getOMove(theBoard)
turn = 'X'
# isWinner寫好了,要怎麼融入這個流程? |
3f0fb2c7721708bb915650ed18d81d991bb70894 | muskanmahajan37/programming-language-paradigms | /python_examples/heranca_multipla.py | 640 | 3.5 | 4 | class Figura(object):
def __init__(self):
print ( 'criou Figura' )
def nome( self ):
print ( 'Nome da Figura' )
def __str__(self):
return "< classe Figura >"
class Poligono(object):
def __init__(self):
print ( 'criou Poligono' )
def nome( self ):
print ( 'Nome do Poligono' )
def __str__(self):
return "< classe Poligono >"
class Quadrado(Figura, Poligono):
def __init__(self):
Figura.__init__(self)
Poligono.__init__(self)
print( 'quadrado' )
def __str__(self):
return "< classe Quadrado >"
c = Quadrado()
c.nome() |
d8f084d29799052664b4ee0c02508ade0561a95e | apple2062/algorithm | /programmers/[L2]문자열압축.py | 993 | 3.703125 | 4 | # abcabcdede와 같은 경우, 문자를 2개 단위로 잘라서 압축하면 abcabc2de가 되지만,
# #3개 단위로 자른다면 2abcdede가 되어 3개 단위가 가장 짧은 압축 방법
# "ababcdcdababcdcd" -> 9
# "abcabcdede" -> 8
# "abcabcabcabcdededededede"-> 14
def solution(s): # 1부터 length/2 까지가 단위(step) 이 됨
wording = ""
size = len(s) // 2
ans = []
for i in range(6, size + 1): # 스텝
part = s[0:i] # 기준이 될 놈
cnt = 1
for j in range(i, len(s), i): # 스텝만큼 비교하기
if part == s[j:j + i]:
cnt += 1
else:
wording += part
if cnt > 1:
wording += str(cnt)
part = s[j:j + i]
cnt = 1
wording += part
if cnt > 1:
wording += str(cnt)
ans.append(len(wording))
print(i, len(wording), wording)
wording = ""
return min(ans)
|
a871cea8c59b7468d5f543bf7d285af4eca8fd21 | veratsurkis/infa_2020_postnikov | /lab2_1/ex12.py | 429 | 3.5625 | 4 | import turtle as tr
import numpy as np
tr.shape("turtle")
def arc(x,y,r,angle_1,angle_2):
tr.penup()
tr.goto(x+r*np.cos(angle_1*np.pi/180),y+r*np.sin(angle_1*np.pi/180))
tr.pendown()
for i in range(angle_1,angle_2+1,1):
tr.goto(x+r*np.cos(i*np.pi/180),y+r*np.sin(i*np.pi/180))
r = 100
x_1 = -3*r
for j in range(4):
x_1 = x_1 + 6*r/4
arc(x_1, 0, r, 0, 180)
arc(x_1 + 3*r/4, 0, r/4, 180, 360)
tr.done() |
f2fd66e59c2d9481684b04a84f31b5ab4290a564 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/jason_jenkins/lesson03/list_lab.py | 3,230 | 4.375 | 4 | #!/usr/bin/env python3
"""
Lesson 3: List Lab
Course: UW PY210
Author: Jason Jenkins
"""
def series_1(list=[]):
"""
Practicing using lists
"""
# Make a copy of list
list = list[:]
print()
print("Starting series_1:")
print()
display_list(list)
# Add to list
list.append(input("Input another fruit to the list: "))
display_list(list)
# Find and output an item
loc = input("Input fruit number to print (Starting at 1): ")
loc = int(loc) - 1
if (0 <= loc < len(list)):
print(list[loc])
# Add to beginning of the list using "+" creating a local object
response = input("Input another fruit to the list: ")
list = [response] + list
display_list(list)
# Add to beginning of the list using "insert"
response = input("Input another fruit to the list: ")
list.insert(0, response)
display_list(list)
# Display all the fruits that begin with “P”, using a for loop
for item in list:
if(item[0] == "P"):
print(item)
return list
def series_2(list=[]):
"""
Practicing using lists
"""
# Make a copy of list
list = list[:]
print()
print("Starting series_2:")
print()
display_list(list)
# Remove last item on list
print("Removing last items")
list.pop()
display_list(list)
# Remove requested item from list
loc = input("Input fruit number to remove (Starting at 1): ")
loc = int(loc) - 1
if (0 <= loc < len(list)):
list.pop(loc)
display_list(list)
return list
def series_3(list=[]):
"""
Practicing using lists
"""
# Make a copy of list
list = list[:]
print()
print("Starting series_3:")
print()
display_list(list)
# Make all items in list lowercase
for i in range(len(list)):
list[i] = list[i].lower()
# Create a tmplist
new_list = []
# Ask used if they like item and remove if no
print("For the following questions input yes or no.")
for item in list:
while(True):
response = input(f"Do you like {item}? ")
if(response.lower() == "yes"):
new_list.append(item)
break
elif(response.lower() == "no"):
break
display_list(new_list)
return new_list
def series_4(list=[]):
"""
Practicing using lists
"""
print()
print("Starting series_4:")
print()
display_list(list)
# Make a copy of list
list = list[:]
# Make a new list
new_list = []
# reverse all item leters
for i, item in enumerate(list):
new_list.append(str(item)[::-1])
print(f"New List: {new_list}")
# Remove Last Item
list.pop()
print(f"Orignial list after removing last item: {list}")
return new_list
def display_list(list=[]):
"""
Print the list as a list
"""
print(f"Current List: {list}")
if __name__ == "__main__":
# Create a list
tmp_list = ["Apples", "Pears", "Oranges", "Peaches"]
series_1_list = series_1(tmp_list)
series_2_list = series_2(series_1_list)
series_3_list = series_3(series_1_list)
series_4_list = series_4(series_1_list)
|
c050a38ed6ef14bb1b1a0b1285319fe6261fba7a | kyaing/KDYSample | /kYPython/FluentPython/BasicLearn/MultiProcess/CopyFile.py | 1,170 | 3.578125 | 4 | from multiprocessing import Pool, Manager
import os
""" 多线程拷贝文件 """
def copyFileTask(name, old_folder_name, new_folder_name):
""" 拷贝一个文件 """
fr = open(old_folder_name + '/' + name)
fw = open(new_folder_name + '/' + name, 'w')
content = fr.read()
fw.write(content)
fr.close()
fw.close()
def main():
old_folder_name = input("请输入文件夹的名字:")
# 创建新的文件夹
new_folder_name = old_folder_name + '-复件'
os.mkdir(new_folder_name)
file_names = os.listdir(old_folder_name)
# 使用多进程拷贝原文件的内容
pool = Pool(5)
queue = Manager().Queue()
for name in file_names:
pool.apply_async(copyFileTask,
args=(name, old_folder_name, new_folder_name, queue))
# pool.close()
# pool.join()
# 记录拷贝文件的进度
num = 0
allNum = len(file_names)
while num < allNum:
queue.get()
num += 1
copyRate = num / allNum
print('\rcopy的进度是:%0.2f%%' % (copyRate * 100), end="")
print('---已经完成拷贝---')
if __name__ == '__main__':
main()
|
56d4618c988e5b78bbabe6bb2bfa85ccde9e7335 | simon7lousky/Stock-Analyzer | /tick_compare.py | 3,226 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 9 00:52:03 2018
@author: simonlousky
"""
"""
Program that receives a start date, a end date,a list of shares and a variable the user wants
to compare and analyze. The program will create a graph in the given period,
which compares the selected variable for the shares on the list.
In addition, the program will display a table with summaries data for each share in the list.
Paremeters
----------
from_date: string
The start date, need to be in format yyyy-mm-dd.
to_date: string
The end date, need to be in format yyyy-mm-dd.
tickers: string
The input of selected tickers(ID), need to be separate by commas.
var_test: string
The variable the user wants to compare(can get:'close','high','low','daily_profit','cumulative_profit').
lst_tickers: list
The list of selected tickers(ID).
ticker_data: pandas.core.frame.DataFrame
The data which includes the variable to compare of the share.
An auxiliary variable that changes along the loop
"""
import TickersData as td
from ctir import function_ctir
import matplotlib.pyplot as plt
from_date= input("Enter the start date in the format yyyy-mm-dd:")
to_date= input("Enter the end date in the format yyyy-mm-dd:")
tickers= input("Enter the ID of the shares you want to analyze(please separate the names with commas):")
var_test= input("Enter the variable you want to compare:")
lst_tickers= tickers.split(',')
while var_test not in ['close','high','low','daily_profit','cumulative_profit']:
print("You did not give an appropriate variable for comparison. Try again.")
var_test= input("Enter the variable you want to compare:")
for ticker_name in lst_tickers:
try:
if var_test== 'close':
ticker_data= td.get_data_for_ticker_in_range(ticker_name,from_date,to_date, ['close'])
plt.plot(ticker_data.index, ticker_data.close, label= ticker_name)
if var_test== 'high':
ticker_data= td.get_data_for_ticker_in_range(ticker_name,from_date,to_date, ['high'])
plt.plot(ticker_data.index, ticker_data.high, label= ticker_name)
if var_test== 'low':
ticker_data= td.get_data_for_ticker_in_range(ticker_name,from_date,to_date, ['low'])
plt.plot(ticker_data.index, ticker_data.low, label= ticker_name)
if var_test== 'daily_profit':
ticker_data= td.get_profit_for_ticker_in_range(ticker_name,from_date,to_date)
plt.plot(ticker_data.index, ticker_data.daily_profit, label=ticker_name)
if var_test== 'cumulative_profit':
ticker_data= td.get_profit_for_ticker_in_range(ticker_name,from_date,to_date,accumulated="true")
plt.plot(ticker_data.index, ticker_data.cumulative_profit, label= ticker_name)
except ValueError:
print("The share {} is not found in the database or on the range date you choose.".format(ticker_name))
continue
plt.title(str.upper(var_test))
plt.legend()
plt.show()
print(function_ctir(from_date,to_date, tickers))
|
10196dd033199f1f0dd5f20bf5bd181d772ec0a9 | loggar/py | /py-dev/best-practice/dont-use-recursion/ex.1.py-closure.py | 196 | 3.984375 | 4 | def outer():
x = 1
def inner():
print(f'x in outer function (before modifying): {x}')
x += 1
print(f'x in outer function (after modifying): {x}')
return inner
|
08ef0c68c01bc4b2f113108110ccba0b0b8d0b86 | dorabelme/Python-Programming-An-Introduction-to-Computer-Science | /chapter8_programming8.py | 270 | 3.875 | 4 | def main():
print("Euclid's algorithm")
m = eval(input("Enter the first integer: "))
n = eval(input("Enter the second integer: "))
m_orig = m
n_orig = n
while m != 0:
n , m = m, n % m
print("The GCD of", m_orig, "and", n_orig, "is", str(n) + ".")
main()
|
d9caadcc90f900caf939191acf5a1e028a2bb0e5 | isruthi/HighSchoolCamp | /loops_applying_your_knowledge.py | 1,512 | 4.09375 | 4 | """
title: loops_applying_your_knowledge
author: isruthi
date: 2019-06-13 13:40
"""
# part 1 - ex. 1
loop1 = [89, 41, 73, 90]
for i in loop1:
print(i)
# part 1 - ex. 2
for i in range(5, 15):
print(i, end=" ")
print()
# part 1 - ex. 3
for i in range(100, 201, 10):
print(i, end=" ")
print()
# part 1 - ex. 4
for i in range(80, 31, -8):
print(i, end=" ")
print()
# part 1 - ex. 5
for i in range(3):
print("Alright", end=" ")
print()
# part 2 - ex. 1
number = 10
while number > 0:
print(number, end=" ")
number = number - 1
print()
# part 2 - ex. 2
response = int(input("Enter an integer greater than 0: "))
while response <= 0:
print("Invalid")
response = input("Enter an integer greater than 0: ")
print("This number is valid!")
# part 2 - ex. 3
response1 = int(input("Enter an integer: "))
response2 = int(input("Enter an integer larger than the last integer you entered: "))
while response1 > response2:
print("Invalid. Second integer entered must be larger than the first integer entered.")
response1 = int(input("Enter an integer: "))
response2 = int(input("Enter an integer larger than the last integer you entered: "))
while response2 >= response1:
print(response1, end=" ")
response1 = response1 + 1
print()
# part 2 - ex. 4
response4 = input("Enter response: ")
while response4 not in ['Y', 'y', 'yes', 'YES', 'N', 'n', 'no', 'NO']:
print("Invalid response")
response4 = input("Enter response: ")
print("Valid response") |
6ad9f15e9546644d0f223fced6495f7441453d92 | BryCant/IntroToCryptography | /wk6/Project3.py | 2,208 | 3.8125 | 4 | import time
# 1) implement the modular exponentiation algorithm to compute a^b mod n for any integer inputs a, b and n. Use your
# code to compute a^b mod n for the sets of numbers below. Record the computer run time and iteration count for each.
def getBinExpList(num):
# function that returns list for all numbers that make binary exponent
binExpList = []
binForm = bin(num)[2:]
for n in range(len(binForm)):
newExp = int(binForm[len(binForm) - n - 1]) * (2 ** n)
binExpList.append(newExp)
return binExpList
def mea(a, b, n):
start_time = time.time()
finalNum = 1
steps = 0
print(len(getBinExpList(b)))
for exp in getBinExpList(b):
finalNum *= (a ** exp) % n
finalNum = finalNum % n
if steps % 10 == 0:
print('hello')
steps += 1
duration = time.time() - start_time
return [finalNum % n, duration, steps] # [finalNum % n, duration]
def rec_mea(a, b, n):
def innards(k):
if k >= len(bin(b)[2:]):
return 1
else:
# print(int(bin(b)[::-1][k]))
if int(bin(b)[::-1][k]) == 1:
fin = a
for i in range(k):
fin = (fin ** 2) % n
print(f"K = {k}; {int(bin(b)[::-1][k])} * {fin} * innards({k + 1})")
return fin * innards(k + 1)
else:
print(f"K = {k}; {int(bin(b)[::-1][k])} * {((a ** k) % n)} * innards({k + 1})")
return innards(k + 1) % n
return innards(0) % n
def list_mea(a, b, n):
finalNum = 1
for exp in getBinExpList(b):
finalNum *= rec_mea(a, b, n)
finalNum = finalNum % n
return finalNum
# print(getBinExpList(13530185234470674604))
print(getBinExpList(105))
# print(rec_mea(9, 105, 137))
# a) a = 2, b = 135301852344706746049, n = 947112966412947222343
print(rec_mea(2, 13530185234470674604, 947112966412947222343))
# b) a = 13, b = 354224848179261915075, n = 573147844013817084101
# print(mea(13, 354224848179261915075, 573147844013817084101))
# c) a = 3, b = 927372692143078999175, n = 927372692143078999176
# print(mea(3, 927372692143078999175, 927372692143078999176))
|
6a950e840fbeeebae536b85d9465626bd04b61bd | amcguier/pysc2-protossbot | /zerg/MultiThreadingTest1.py | 602 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 29 21:49:11 2018
@author: User
"""
import threading
import queue
my_queue = queue.Queue()
#function to run in thread
def testFunction(imput1, out_queue):
#function stuff
output = imput1 + 1
#return
out_queue.put(output)
#create thread
thread1 = threading.Thread(testFunction(1, my_queue))
#start thread
thread1.start()
#stuff to happen in main thread while other thread is doing shinanigans
#stop until thread done
thread1.join()
#print function return
print(my_queue.get()) |
0b04451faeae0c2fff14b7c22458db365f78c04d | hmcurt01/Ivy-Plus | /college.py | 1,210 | 3.609375 | 4 | # college class
class College:
def __init__(self, name, ed, aid, intvw, cadone, casent, fafsa, css, par, ty, choose, accept):
self.name = name
self.ed = ed
self.aid = aid
self.intvw = intvw
self.cadone = cadone
self.casent = casent
self.fafsa = fafsa
self.css = css
self.par = par
self.ty = ty
self.choose = choose
self.accept = accept
# change attributes of object
def change_attr(self, value, new):
if value == "name":
self.name = new
elif value == "ed":
self.ed = new
elif value == "aid":
self.aid = new
elif value == "intvw":
self.intvw = new
elif value == "cadone":
self.cadone = new
elif value == "casent":
self.casent = new
elif value == "fafsa":
self.fafsa = new
elif value == "css":
self.css = new
elif value == "par":
self.par = new
elif value == "ty":
self.ty = new
elif value == "choose":
self.choose = new
elif value == "accept":
self.accept = new
|
19dc9f8d539bbd7f7c6b266aee1e9aecd8eeb0f5 | KaranKendre11/cloudcounselage_intern | /CloudConselage/SOLN/problem5.py | 75 | 3.640625 | 4 | s = input()
m = ""
for x in s:
if x not in m:
m += x
print(m)
|
6124935344a4816ae2bf5790f60b2faa27b09066 | JanviChitroda24/pythonprogramming | /Hackerrank Practice/left_rotation.py | 1,173 | 4.3125 | 4 | '''
A left rotation operation on an array of size shifts each of the array's elements unit to the left. For example, if left rotations are performed on array , then the array would become .
Given an array of integers and a number, , perform left rotations on the array. Then print the updated array as a single line of space-separated integers.
Input Format
The first line contains two space-separated integers denoting the respective values of (the number of integers) and (the number of left rotations you must perform).
The second line contains space-separated integers describing the respective elements of the array's initial state.
Constraints
Output Format
Print a single line of space-separated integers denoting the final state of the array after performing left rotations.
Sample Input
5 4
1 2 3 4 5
Sample Output
5 1 2 3 4
Explanation
When we perform left rotations, the array undergoes the following sequence of changes:
Thus, we print the array's final state as a single line of space-separated values, which is 5 1 2 3 4.
'''
n, d = map(int, input().split())
arr = [int(i) for i in input().split()]
arr = arr[d:] + arr[:d]
print(*arr)
|
5e2db6fc610175252b66022876add0de2705c062 | dlefcoe/daily-questions | /directionsValidate.py | 4,530 | 3.9375 | 4 | '''
This problem was asked by Uber.
A rule looks like this:
A NE B
This means this means point A is located northeast of point B.
A SW C
means that point A is southwest of C.
Given a list of rules, check if the sum of the rules validate. For example:
A N B
B NE C
C N A
does not validate, since A cannot be both north and south of C.
A NW B
A N B
is considered valid.
'''
'''
initial thoughts
possible directions:
'''
import math
# these are the possible directions split horizontally and vertically
possibleDirections = {'N':(1,0), 'S':(-1,0), 'E':(0,1), 'W':(0,-1),}
'''
here is the rule for decoding:
A NW B
=> a = b + n + w
=> a = b + (1,0) + (0,-1)
=> a = b + (1,-1)
B NE C
=> b = c + n + e
=> b = c + (1,0) + (0,1)
=> b = c + (1,1)
'''
def decodeDirection(point1, direction, point2):
''' get point1 = point2 + [i,j]
inputs:
point1: a letter (type string)
point2: a letter (type string)
direction: a string (of one char or 2 chars)
output:
point1: a letter (type string)
point2: a letter (type string)
direction: an array [i,j]
'''
v = [0,0]
for i in direction:
# get value from dict
move = possibleDirections.get(i)
v[0] = v[0] + move[0]
v[1] = v[1] + move[1]
# something like A(i,j) = B(i,j) + Move(i,j)
return point1, v, point2
def breakIntoThreeParts(rule):
point1 = rule[0]
point2 = rule[-1]
if len(rule) == 5:
move = rule[2]
elif len(rule) == 6:
move = rule[2:4]
return point1, move, point2
'''
...good code here, but dont need....
r = 'A NW B' #len 6 rule
tp = breakIntoThreeParts(r)
# parse rule into decoder
out = decodeDirection(*tp)
print(out)
r = 'A W C' # len 5 rule
tp = breakIntoThreeParts(r)
# parse rule into decoder
out = decodeDirection(*tp)
print(out)
'''
# code to test decodeDirection()
# yay = decodeDirection('A', 'ne', 'B')
# print(yay)
def workOnRuleList(ruleList):
''' Takes the list of rules (as a list of strings) '''
out = [] #output list
for i in ruleList:
tp = breakIntoThreeParts(i)
out.append(decodeDirection(*tp))
#print(out)
# test verticals
print('verticals:')
eqV = []
for i in out:
#print('point1:', i[0], ', point2:',i[2], ', Vertical move vector:', i[1][0])
if i[1][0] >= 1:
print(i[0], ">", i[2] )
eqV.append(i[0] + " > " + i[2])
elif i[1][0] == 0:
print(i[0],"=",i[2])
eqV.append(i[0] + " = " + i[2])
elif i[1][0] <= -1:
print(i[0],"<",i[2])
eqV.append(i[0] + " < " + i[2])
else:
print(i[0], i[1][0], i[2] )
# test horizontals
print('horizontals:')
eqH = []
for i in out:
#print('point1:', i[0], ', point2:',i[2], ', Horizontal move vector:', i[1][1])
if i[1][1] >= 1:
print(i[0], ">", i[2] )
eqH.append(i[0] + " > " + i[2])
elif i[1][1] == 0:
print(i[0],"=",i[2])
eqH.append(i[0] + " = " + i[2])
elif i[1][1] <= -1:
print(i[0],"<",i[2])
eqH.append(i[0] + " < " + i[2])
else:
print(i[0], i[1][1], i[2] )
return eqV, eqH
def compareInequality(equality1, equality2, equality3):
'''
takes 3 inequalities and compares
input:
equality 1, 2, 3: strings of format ("A > B")
output:
string = "this is good" or "this is bad"
'''
# compare A to B
if "A > B":
a, b = 1, 0
elif "A = B":
a, b = 0, 0
elif "A < B":
a, b = -1, 0
else:
print('inequality error')
# compare B to C
if "B > C":
b, c = 0, -1
elif "B = C":
b, c = 0, 0
elif "B < C":
b, c = 0, 1
else:
print('inequality error')
# check if A to C is valid
if a > c and equality3 == 'A > C':
decission = 'this is good'
elif a == c and equality3 == 'A = C':
decission = 'this is good'
elif a < c and equality3 == 'A < C':
decission = 'this is good'
else:
decission = 'this is bad'
return decission
print('--- work on the rule list ---')
ruleList = ['A N B', 'B NE C', 'C N A']
ruleList = ['A N B', 'B E C', 'A N C']
a = workOnRuleList(ruleList)
print('--- compare inequality for verticals---')
d = compareInequality(*a[0])
print(d)
print('--- compare inequality for horizontals---')
d = compareInequality(*a[1])
print(d)
|
c67c6b50af88e4110b96c15576b1aceff4bac8f6 | hrz123/algorithm010 | /Week10/每日一题/面试题 08.06. 汉诺塔问题.py | 1,077 | 3.890625 | 4 | # 面试题 08.06. 汉诺塔问题.py
from typing import List
class Solution:
def hanota(self, A: List[int], B: List[int], C: List[int]) -> None:
"""
Do not return anything, modify C in-place instead.
"""
n = len(A)
self.move(n, A, B, C)
def move(self, n, A, B, C):
if n == 1:
C.append(A.pop())
return
self.move(n - 1, A, C, B)
C.append(A.pop())
self.move(n - 1, B, A, C)
class Solution:
def hanota(self, A: List[int], B: List[int], C: List[int]) -> None:
"""
Do not return anything, modify C in-place instead.
"""
n = len(A)
return self.helper(n, A, B, C)
def helper(self, n, A, B, C):
if n == 1:
C.append(A.pop())
return
self.helper(n - 1, A, C, B)
C.append(A.pop())
self.helper(n - 1, B, A, C)
def main():
sol = Solution()
A = list(range(10, -1, -1))
B = []
C = []
sol.hanota(A, B, C)
print(C)
if __name__ == '__main__':
main()
|
89e9a72df08f9d0558796b3e74b9a3cb42830f91 | ygberg/labbar | /function 1-6/function1.py | 138 | 3.546875 | 4 |
a=22
b=11
c=6
def incomp(num1,num2,num3):
lista = [num1,num2,num3]
lista.sort()
return print(lista[-1])
incomp(a,b,c) |
c54c21ae0a7706eec992d3ec1d59065a9960812e | JbrooksGit/python-joins | /data_frame.py | 1,328 | 3.84375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 14 16:41:35 2019
@author: jonathanbrooks
"""
import csv
import pandas as pd
import numpy as np
def drop_y(df):
# list comprehension of the cols that end with '_y'
to_drop = [x for x in df if x.endswith('_y')]
df.drop(to_drop, axis=1, inplace=True)
data = pd.read_csv("subjects.csv")
#data[['last_name','first_name','dob']] #pandas two dimensional series
data2 = pd.read_csv("test.csv",delimiter = ',',na_values = ['no info', '.'])
#print(data2.head()) #prints out number of rows based on argument of head
#print(data2['last_name'][:]) #prints out all last names
#row2 = data2.iloc[0] #prints out specific row. this one prints out abate
merged = data.merge(data2, on = 'last_name' and 'first_name' and 'dob' , suffixes=('', '_y'))
#for i,j in data2.head().iterrows(): #the i is the index while the j is the row
# print(j)
drop_y(merged)
merged.drop_duplicates(inplace = True) #With the XML Replace this with all column values
merged.to_csv("output.csv", index=False)
#remove_duplicates.drop_duplicates()
#print(row2)
#data2.last_name == 'brooks'
#data2[data2.last_name == 'abate']
#liste = [row for row in data2]
'''
df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
columns=['a', 'b', 'c'])
print(df2)
''' |
29a79ff8a7b18fad475ed5b961d2df21b2030304 | Maryville-SWDV-610-3W18SP2/week-4-stacks-queues-and-lists-GFRAYJO | /DequeUsingLinkedList.py | 1,128 | 3.53125 | 4 | class _Node:
__slots__ = '_object', '_prev', '_next'
def __init__(self,object,prev,next):
self._object = object
self._prev = prev
self._next = next
class Deque:
def __init__(self):
self._header = self._Node(None,None,None)
self._trailer = self._Node(None,None,None)
self._header._next = self._trailer
self._trailer._prev = self._header
self.size = 0
def len(self):
return self.size
def is_empty(self):
return self.size == 0
def insert_between(self,obj,predecessor,successor):
newObj = self._Node(obj,predecessor, successor)
predecessor._next = newObj
successor._prev = newObj
self.size +=1
return newObj
def delete_node(self,node):
predecessor = node._prev
successor = node._next
predecessor._next = successor
successor._prev = predecessor
self.size -= 1
object = node.object
node._prev = node._next = node.object = None
return object
|
c2bb72aeb043e9342c8f7248e50048f1a63ed95f | tjsaotome65/sec430-python | /module-06/threadexample1.py | 443 | 4 | 4 | """
File: threadexample1.py
First demo of a thread.
"""
from threading import Thread
class MyThread(Thread):
"""A thread that prints its name."""
def __init__(self, name):
Thread.__init__(self, name = name)
def run(self):
print("Hello, my name is %s" % self.getName())
def main():
"""Create the thread and start it."""
thread = MyThread("Ken")
thread.start()
if __name__ == "__main__":
main()
|
60bc1822965c2a34cbc5934f0d08904f5726d4da | AdamZhouSE/pythonHomework | /Code/CodeRecords/2636/60618/321148.py | 61 | 3.90625 | 4 | str=input()
if str=="4 3":
print(4)
else:
print(str)
|
3e91152381245f43b0b85568fdeb24e242d366cb | soumyadip1188/python | /python programe/KrishnamurtyNumber.py | 449 | 4.15625 | 4 | def factorial(n):
fact = 1
while(n!=0):
fact=fact*n
n=n-1
return fact
def Krishnamurty(n):
s = 0
temp = n
while(temp!=0):
rem=temp%10
s=s+factorial(rem)
temp=temp//10
return(s==n)
n=int(input("enter a numberto check if it's a Krishnamurty number or not:"))
if(Krishnamurty(n)):
print("Krishnamurty Number.")
else:
print("Not a Krishnamurty Number.") |
752f284808f5b65b796707c699e9cf38bab5c705 | blankxz/LCOF | /排序、二分等基础算法/桶排序.py | 535 | 3.71875 | 4 | def bucketSort(arr):
maximum, minimum = max(arr), min(arr)
bucketArr = [[] for i in range(maximum // 10 - minimum // 10 + 1)] # set the map rule and apply for space
for i in arr: # map every element in array to the corresponding bucket
index = i // 10 - minimum // 10
bucketArr[index].append(i)
arr.clear()
for i in bucketArr:
i.sort() # sort the elements in every bucket
arr.extend(i) # move the sorted elements in bucket to array
a = [2,8,9,10,4,5,6,7]
bucketSort(a)
print(a) |
f52e1d612a1b14314c39a08b0b6eb5020ef199c6 | mrichko2705/lab_python | /py_75.py | 318 | 3.84375 | 4 | #!/usr/bin/env python3
# --*-- coding:utf-8 --*--
string = str(input("Введіть слово англійською мовою: "))
alph = ['a', 'o', 'u', 'i', 'e', 'y']
b = []
for i in string:
if i.lower() in alph :
b.append(1)
print("Кількість голосних в слові = {}".format(len(b)))
|
e8095bbf2b7af3435b272453dd9c986ba3a6b22b | yns01/leetcode | /149-word-search.py | 1,930 | 3.859375 | 4 | from typing import List
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == word[0]:
if self.dfs(board, (i, j), word, 0, set()):
return True
return False
def dfs(self, board, starting_point, word, word_index, seen):
r, c = starting_point
if board[r][c] != word[word_index]:
return False
seen.add(starting_point)
word_index += 1
# In the following example,
# [["a","b"],
# ["c","d"]]
# "acdb"
# When we visit the last node, 'b', we don't have anything else to visit as
# either we already saw the nodes, or they are out of range.
# If we already found the string, we just stop.
# An alternative would be to check for valid boundaries at the beginning of the function,
# right after the word_index check.
if word_index >= len(word):
return True
for dx, dy in (1, 0), (-1, 0), (0, 1), (0, -1):
nr = r + dy
nc = c + dx
if (0 <= nr < len(board) and 0 <= nc < len(board[0])) and (nr, nc) not in seen:
if self.dfs(board, (nr, nc), word, word_index, seen):
return True
# Backtrack: we are trying all possible path. After trying all four directions,
# we remove the point from seen to make it available for future explorations.
seen.remove(starting_point)
return False
print(Solution().exist([["A", "B", "C", "E"], [
"S", "F", "C", "S"], ["A", "D", "E", "E"]], "ABCCED"))
print(Solution().exist([["a"]], "a"))
print(Solution().exist([["a", "b"], ["c", "d"]], "acdb"))
print(Solution().exist([["A", "B", "C", "E"], [
"S", "F", "C", "S"], ["A", "D", "E", "E"]], "ABCB"))
|
89434c283d04ea08b3472c73c0941280da125b64 | ashcolecarr/Exercism-Python | /prime-factors/prime_factors.py | 716 | 3.96875 | 4 | from math import sqrt
def prime_factors(natural_number):
prime_factors = []
# Get a list of factors.
factors = [2] if natural_number % 2 == 0 else []
factors += [x for x in range(3, int(sqrt(natural_number)) + 1, 2)
if natural_number % x == 0]
# Using straightforward trial division.
trialed_number = natural_number
idx = 0
while idx < len(factors):
if trialed_number % factors[idx] == 0:
prime_factors.append(factors[idx])
trialed_number //= factors[idx]
else:
idx += 1
# A prime factor could still be left.
if trialed_number > 1:
prime_factors.append(trialed_number)
return prime_factors
|
1d4242e51797d470826b27d4be32ccedbc52a4ef | MJVL/Python-Projects | /Basic Stuff/list_comprehension.py | 164 | 3.640625 | 4 | evens_to_20 = [i for i in range(21) if i % 2 == 0]
print(evens_to_20)
cubes_by_four = [x ** 3 for x in range(1,11) if (x ** 3 % 4 == 0)]
print(cubes_by_four)
|
38b88ff73071bde58f0d5e337d8ca5ed4ff12d51 | aj-1000/project-euler | /first-50/problem_7.py | 852 | 4.1875 | 4 | # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10 001st prime number?
# import required libraries
from itertools import count
# Using the prime test from a previous problem
def test_if_prime(x):
if x == 2:
return True
elif x%2 == 0: # check that x is not even
return False
else:
# loop through the odd integers between 3 and x/2
for i in [j for j in range(3,(x//2)+1,2)]:
if x%i == 0:
return False
return True
# set initial variables
candidate = 2
primes = []
target = 10001
arr = count(3,2)
# loop through primes
while len(primes) != target:
found_prime = test_if_prime(candidate)
if found_prime:
primes.append(candidate)
candidate = next(arr)
# print result
print(primes[-1])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.