blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
6b96e98d60e5296a041e9934295f93735c2c088d | paras-bhavnani/Python | /Python/DataTypeAndCoversions/Q1.py | 255 | 3.703125 | 4 | word1 = 'w3resource'
word2 = 'w3'
word3 = 'w'
def task1(word):
answer = word[0:2] + word[len(word) - 2:len(word)]
if len(answer) < 4:
print('Empty String')
else:
print(answer)
task1(word1)
task1(word2)
task1(word3) |
6687375e1a810388c09f8bc297a61afd404f92d5 | zhanghognbo/aaaa | /three_chuan.py | 181 | 3.671875 | 4 | import random
list=[]
for i in range(20):
list.append(random.choice(range(100)))
print(list)
for i in range(len(list)):
list[::2]=sorted(list[::2],reverse=True)
print(list)
|
9fed6970d496128ce9141b462bed06d178d16fa0 | aikozijlemans/intellij-plugin | /test-data/python/documentation/detailedRenderer/hover/type/counter/code.py | 323 | 3.828125 | 4 | class Counter(object):
"""This is a counter"""
def __init__(self, n=0, name="counter"):
self.n = n
self.name = name
def increment(self, n):
return self.n
def foo(bar) -> int | str | bool:
return bar;
# Caret between . and increment
Counter.increment
x = True
x = 1
x = 2
print(x) |
774363fdf61b4660b2d04e1fcb1dff3dfeafa8bd | cmanny/expert-octo-garbanzo | /project_euler/2.py | 301 | 4.0625 | 4 | import sys
def even_fib(N):
a, b = 0, 1
even_sum = 0
if N < 2:
return N
else:
while b < N:
if b % 2 == 0:
even_sum += b
a, b = b, a + b
return even_sum
t = int(input())
for _ in range(t):
print(even_fib(int(input())))
|
6fdd9941403730504345b6de516ae9eda03601c4 | etangreal/compiler | /test/tests/05class/test_class-polymorphism_001.py | 292 | 3.734375 | 4 | class A( object ):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def func( self ):
return a.x + a.y + a.z
if True:
a = A(7, 70, 700)
else:
a = "abc"
print a.func()
if False:
a = A(7, 70, 700)
else:
a = "abc"
print a
|
073da41d71e62466af8f0943c66d3c830e89416d | zhb1207/Practice | /EulerProj/P7.py | 230 | 3.859375 | 4 | from math import sqrt
i = 2
step = 0
def isprime(n):
for i in range(2, int(sqrt(n)) + 1):
if n % i == 0:
return False
return True
while step != 10001:
if isprime(i):
step += 1
i += 1
print(i - 1)
|
571f8473c8269609738cd829a5a0108d94df9975 | gsketefian/regional_workflow | /ush/python_utils/misc.py | 1,764 | 4.34375 | 4 | #!/usr/bin/env python3
import re
def uppercase(str):
""" Function to convert a given string to uppercase
Args:
str: the string
Return:
Uppercased str
"""
return str.upper()
def lowercase(str):
""" Function to convert a given string to lowercase
Args:
str: the string
Return:
Lowercase str
"""
return str.lower()
def find_pattern_in_str(pattern, source):
""" Find regex pattern in a string
Args:
pattern: regex expression
source: string
Return:
A tuple of matched groups or None
"""
pattern = re.compile(pattern)
for match in re.finditer(pattern,source):
return match.groups()
return None
def find_pattern_in_file(pattern, file_name):
""" Find regex pattern in a file
Args:
pattern: regex expression
file_name: name of text file
Return:
A tuple of matched groups or None
"""
pattern = re.compile(pattern)
with open(file_name) as f:
for line in f:
for match in re.finditer(pattern,line):
return match.groups()
return None
def flatten_dict(dictionary,keys=None):
""" Faltten a recursive dictionary (e.g.yaml/json) to be one level deep
Args:
dictionary: the source dictionary
keys: list of keys on top level whose contents to flatten, if None all of them
Returns:
A one-level deep dictionary for the selected set of keys
"""
flat_dict = {}
for k,v in dictionary.items():
if not keys or k in keys:
if isinstance(v,dict):
r = flatten_dict(v)
flat_dict.update(r)
else:
flat_dict[k] = v
return flat_dict
|
5054646d2d41d1464a53eca9f11b342970b48f5a | SSD-2021/backend-study | /Problem Solving/DONGHAK/[boj]/[boj]10947.py | 173 | 3.703125 | 4 | import random
arr = []
while len(arr) < 6:
temp = random.randrange(1,46)
if temp in arr:
continue
else:
arr.append(temp)
arr.sort()
print(arr) |
5b955eddec266f3e066901938749480cbe4c6ea9 | mehulthakral/logic_detector | /backend/dataset/inorderTraversal/inorder_22.py | 746 | 3.5625 | 4 | class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
## RC ##
## APPROACH : STACK ##
## (question demands iterative solution)
## TIME COMPLEXITY : O(N) ##
## SPACE COMPLEXITY : O(N) ##
res = []
stack = []
currNode = root
while(currNode or stack): # attention to condition.
while(currNode):
stack.append(currNode)
currNode = currNode.left # traverse all to the left
currNode = stack.pop()
res.append(currNode.val) # print
currNode = currNode.right # traverse right
return res
|
bc727f0d6c28aa0050711f4d5eeed36e9cfdbe0a | dpalatynski/colony_of_flies | /colony_of_flies.py | 5,448 | 3.875 | 4 | import pygame
import random
import math
import numpy as np
import sys
import matplotlib.pyplot as plt
WHITE = (255,255,255)
GREEN = (0,255,0)
DARK_GREEN = (50,205,50)
RED = (255,0,0)
BLACK =(0,0,0)
class fly():
def __init__(self, x, y):
"""
(x,y) - coordinates of fly
"""
self.x = x
self.y = y
self.rect = pygame.Rect(self.x, self.y, 2, 2) #obiekt pygame'u
self.color = RED
def movement(self):
"""
Fly's movement is a bit modified Brown Motion, because for large t, variance of
normal distribution is so high and fly's movement is similar to random jumping on the screen,
so finally variance is equal to 4
"""
u1 = random.normalvariate(0,4)
u2 = random.normalvariate(0,4)
self.x = self.x + u1
self.y = self.y + u2
if self.x < 0:
self.x = 0
elif self.x > 1000:
self.x = 1000
if self.y < 0:
self.y = 0
elif self.y > 600:
self.y = 600
self.rect.center = (self.x, self.y)
def breeding(self):
"""
Breeding - program generate number from defined interval, if generated number
is equal to time t, defined fly set one egg in (x,y)"""
if t == random.randint(int(t-1/p), int(t+1/p)):
eggs.append(egg(self.x, self.y, t + 50)) # t + 50 ---> time, when egg will be hatched
def draw(self):
pygame.draw.rect(screen, self.color, self.rect)
class egg():
"""
(x,y) - coordinates of egg
hatchtime - time, in which eggs will change in flies"""
def __init__(self, x, y, hatchtime):
self.x = x
self.y = y
self.hatchtime = hatchtime
self.rect = pygame.Rect(self.x, self.y, 5, 5)
def hatch(self):
"""
eggs are changing for defined number of flies"""
if t == self.hatchtime:
for i in range(size_of_breeding):
flies.append(fly(self.x, self.y))
eggs.remove(self)
def draw(self):
pygame.draw.rect(screen, (255,255,0), self.rect)
class car():
"""
Car - rectangular shape on the screen, always starts on the left side
"""
def __init__(self, y):
self.x = 0
self.y = y
self.speed = 10
self.rect = pygame.Rect(self.x, self.y, 50, 25)
self.color = (random.uniform(10,250),random.uniform(10,250), random.uniform(10,250))
def movement(self):
self.rect.center = (self.x, self.y)
self.x = self.x + self.speed
if self.x > 1000:
pass
def draw(self):
pygame.draw.rect(screen, self.color, self.rect)
def text_objects(text, font, color):
textSurface = font.render(text, True, color)
return textSurface, textSurface.get_rect()
def lyrics(message, size, x,y, color=WHITE):
largeText = pygame.font.Font('freesansbold.ttf', size)
TextSurf, TextRect = text_objects(message, largeText,color)
TextRect.center = (x,y)
screen.blit(TextSurf,TextRect)
def draw_a_background(t):
"""
Function to draw all scenery
"""
d = min(int(t/10),100)
screen.fill(BLACK)
pygame.draw.rect(screen, BLACK, (0,200,1000,400),0)
pygame.draw.rect(screen,DARK_GREEN,(0,0,1000, 200-d),0)
pygame.draw.rect(screen,DARK_GREEN,(0,400+d,1000, 200+d),0)
for i in range(0,10,2):
pygame.draw.line(screen,WHITE,(100*i + 25,300),(100*(i+1) + 25,300))
size_of_breeding = 20 #number of flies hacthed from egg
p = 0.0005 #probability od setting an egg by one fly in time t
initial_number_of_flies = 100 #initial number of flies
N_t = 1/2 #intensity of appearing cars on the screen
pygame.display.init()
screen = pygame.display.set_mode((1000,600))
pygame.display.flip()
pygame.font.init()
clock = pygame.time.Clock()
intro = True
eggs = []
cars = []
flies = []
for i in range(initial_number_of_flies):
flies.append(fly(random.uniform(20,980), random.uniform(20,580)))
t = 0
t1 = 0
deaths = 0
while intro:
if t1 <= t:
U = random.random()
t1 = t1 - 1/N_t * math.log(U)
t1 = int(t1) + 7
d = min(int(t/10),100)
cars.append(car(random.uniform(220-d,380+d)))
t+=1
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.display.quit()
sys.exit()
draw_a_background(t)
for item in cars:
item.draw()
item.movement()
for item in eggs:
for item1 in cars:
if item1.rect.colliderect(item.rect):
eggs.remove(item)
item.hatch()
item.draw()
for item in flies:
for item1 in cars:
if item1.rect.colliderect(item.rect):
flies.remove(item)
deaths +=1
item.draw()
item.movement()
item.breeding()
if len(flies) > 4000:
print("Too much flies")
pygame.display.quit()
sys.exit()
if len(flies) == 0:
pygame.display.quit()
sys.exit()
lyrics("Week: " + str(int(t/10)),20, 60, 510)
lyrics("Flies: " + str(len(flies)),20, 70, 540)
lyrics("Deaths: " + str(deaths),20, 60, 570)
pygame.display.update()
clock.tick(20) |
1815c61ba168c96b9407093fdd29e7e32ba88d03 | sufi-yan/URI-Beginner-Solution | /URI-1011.py | 153 | 3.671875 | 4 | #URI-1011
pi = 3.14159
R = float(input(""))
res = (4/3.0)*pi*(R*R*R)
print("VOLUME = {:.3f}".format(res))
#Solved by https://github.com/sufiyanism |
845496c350c442a9e7649a8dc016e3c9df4f14c3 | emmacamille/Hackbright | /billCalculator.py~ | 1,334 | 4.21875 | 4 | # This is a comment and it not read by the interpreter
# These are useful for describing difficult code or adding reminders.
# TODO - fix this code :D
# (Part 1): Instead of using the hard coded ".18",
# Ask the user to input the percentage of tip they want to give.
# Save the input to a variable.
# Use the variable to calculate the tip.
# (Part 2): Fix any bugs and make it work!
def bill_total():
bill = float(raw_input("How much was your bill?"))
tip_percent = float(raw_input("What percentage of the bill would you like to tip?"))
tip_total = bill * (tip_percent/100)
total_bill = bill + tip_total
print "The tip is %.2f and the total bill is %.2f." % (tip_total, total_bill)
def bill_split():
bill = float(raw_input("How much was your bill?"))
tip_percent = float(raw_input("What percentage of the bill would you like to tip?"))
tip_total = bill * (tip_percent/100)
total_bill = bill + tip_total
number_paying = int(raw_input("How many people are in your party?"))
total_bill_split = total_bill / number_paying
print "Each peron will pay %.2f." %(total_bill_split)
print "Menu"
print "1- Bill Total"
print "2 - Bill Split"
choice = raw_input("Type '1' or '2' to select menu item.")
if choice == "1":
bill_total()
else:
bill_split()
<<<<<<< HEAD
=======
>>>>>>> 3b40934f08a4008045af94495f96c8d6a5f8e5cc
|
b4295448f751c3a3c729dbc577135cebd09a7a0d | vecin2/em_automation | /sqltask/sqltask_jinja/globals.py | 154 | 3.734375 | 4 |
def camelcase(st):
if not st:
return ""
output = "".join(x for x in st.title() if x.isalnum())
return output[0].lower() + output[1:]
|
316ae5ad340667448e4f64bbf4201d7ebe44bb2a | lhd0320/AID2003 | /official courses/month01/day12/exercise04.py | 388 | 3.859375 | 4 | class Car:
def __init__(self,brand,speed):
self.brand=brand
self.speed=speed
class Electrocar(Car):
def __init__(self,brand,speed,battery_capacity,charging_power):
super().__init__(brand,speed)
self.battery_capacity=battery_capacity
self.charging_power=charging_power
e01=Electrocar("艾玛",60,70000,1)
print(e01.brand)
print(e01.speed)
|
29980e64908dfc61a7cef920f4f2a4f1c8a1dda4 | unnat5/Data-Structures-and-Algorithms-Specialization | /Coursera Algorithm/Algorithmic Toolbox/week4_divide_and_conquer/1_binary_search/binary_search.py | 1,288 | 4.03125 | 4 | # Uses python3
import sys
def binary_search(a, x,high,low):
#left, right = 0, len(a)-1
# write your code here
if high<low:
return -1
mid = low + (high-low)//2
if a[mid]==x:
return mid
elif a[mid] < x:
return binary_search(a,x,high,mid+1)
else :
return binary_search(a,x,mid-1,low)
def linear_search(a, x):
for i in range(len(a)):
if a[i] == x:
return i
return -1
def binary_search_iterative(array,item,high,low):
while True:
if low>high:
return -1
mid = low + (high-low)//2
if array[mid]==item:
return mid
elif array[mid] < item:
low = mid+1
else:
high = mid-1
if __name__ == '__main__':
sequence = list(map(int,sys.stdin.readline().split()))[1:]
items = list(map(int,sys.stdin.readline().split()))[1:]
for item in items:
print(binary_search_iterative(sequence,item,len(sequence)-1,0), end = ' ')
# input = sys.stdin.read()
# data = list(map(int, input.split()))
# n = data[0]
# m = data[n + 1]
# a = data[1 : n + 1]
# for x in data[n + 2:]:
# # replace with the call to binary_search when implemented
# print(linear_search(a, x), end = ' ')
|
404855d29b2c7b00e488fd11b0cece282c6f22c0 | Nyapy/TIL | /04_algorithm/05day/3.py | 112 | 3.78125 | 4 | print(repr('123'))
print(str('123'))
print(eval(str("12*3")))
print(eval(repr("12*3")))
a = repr(123)
print(a) |
2157bf8917509d098df2bac3e16be104915d2781 | dipeshdd/PYTHON | /replacecharacter.py | 680 | 4.28125 | 4 | def ReplaceChar(string,replaceby):
output=""
replace=string[:1]
string=string[1:]
index=string.find(replace)
output+=replace
while(index!=-1):
output+=string[:index]
string=string[index+len(replace):]
index=string.find(replace)
output+=replaceby
output+=string[index+len(replace):]
return output
if __name__=="__main__":
string=input("Enter a string:")
replaceby=input("Enter the character to replace by :")
output=ReplaceChar(string,replaceby)
print("OUTPUT String : %s"%(output))
'''
OUTPUT:
dipeshdd@dipesh-dd:~/python/string$ python replacecharacter.py
Enter a string:"bubble"
Enter the character to replace by :"*"
OUTPUT String : bu**le
'''
|
6402595387f5044279dcb6343336b8fdbd45cbaa | kspommer/FHCC_Python_II_CS21B | /susanPommerBank.py | 1,931 | 4.375 | 4 | ###########################################################
# Course: CS21B Python Programming: Lab #3
# Name: Susan Pommer
# Description: This program creates a class
# which models a simple bank account and has features
# spanning deposits, withdrawals, interest and
# penalties.
# Driven by test file susanPommerLab3.py
# File name: susanPommerBank.py
# Date: January 30, 2018
###########################################################
## ------- DEFINE CLASS ------- ##
# Class which models a simple bank account
class BankAccount:
## Constructs a BankAccount object
## Assumes provided an initial deposit amount
## @param balance is initial deposit amount
def __init__(self, initial_balance):
# Default balance
DEF_BALANCE = 0.0
self._balance = initial_balance + DEF_BALANCE
# Add deposit to account
# @param amount customer's deposit amount
def deposit(self, amount):
self._balance = self._balance + amount
# Make withdrawal from account
# If withdrawal < balance, calculate new balance
# If withdrawal > balance, impose penalty
# and do not allow withdrawal
## @param amount is withdrawal amount
## @param PENALTY is penalty amount
def withdraw(self, amount):
# Define overdraw penalty amount
PENALTY = 10.0
# Calculate new balance or apply penalty
if (amount > self._balance):
self._balance = self._balance - PENALTY
else:
self._balance = self._balance - amount
# Apply interest to the account
# Program assumes today's date is end-of-month
## @param rate is monthly interest rate
def add_interest(self, rate):
if (self._balance > 0): ## sanity check not neg balance
self._balance = self._balance * (1 + (rate/100.0))
# Return the current account balance
def get_balance(self):
return(self._balance)
|
3883edc2bbed66be119d9be1993d580e99e00aef | HarshKohli/leetcode_practice | /google/interview_process/licence_key.py | 744 | 3.5 | 4 | # Author: Harsh Kohli
# Date created: 7/24/2020
def licenseKeyFormatting(S, K):
reversed = ""
n = len(S)
for index in range(n - 1, -1, -1):
if S[index] != '-':
reversed = reversed + S[index]
temp, output = "", ""
n = len(reversed)
for index, c in enumerate(reversed):
temp = temp + c
if len(temp) == K and index != n - 1:
output = output + temp + "-"
temp = ""
output = output + temp
final_output = ""
n = len(output)
for index in range(n - 1, -1, -1):
final_output = final_output + output[index]
final_output = final_output.upper()
return final_output
S = "5F3Z-2e-9-w"
K = 4
output = licenseKeyFormatting(S, K)
print(output)
|
fa1eec4689b0dce06ce6db24b81163896388d273 | khaled-hossain-code/python-tutor | /regex.py | 235 | 4.21875 | 4 | import re
pattern = ["term1","term2"]
text = "This is a text with term1, not with is the another term around"
print re.search("Hello",text)
#when no pattern is found None is returned
match = re.findall("is",text)
print match.start() |
5578d43de2d5e51e01725682d4e5fd9bf42315dd | Exacte/CP104 | /coop8200_a4/src/q3.py | 692 | 3.96875 | 4 | """
-------------------------------------------------------
-------------------------------------------------------
Author: Mason Cooper
ID: 140328200
Email: coop8200@mylaurier.ca
Version: 2014-09-19
------------
"""
amountData = float(input("How much data will be transmitted(GB)? "))
fastestSpeed = float(input("What is your fastest download speed(Mbps)? "))
slowestSpeed = float(input("What is your slowest download speed(Mbps)? "))
amountData = (amountData*8000)
fastestTime = (amountData/fastestSpeed)/60
slowestTime = (amountData/slowestSpeed)/60
print("The fastest the movie will download is {0:.2f} minutes. The slowest it will download is {1:.2f} minutes!".format(fastestTime, slowestTime))
|
405d43622e63ec8d1ddc6986872f20ee4dd7739e | nfredrich/Network-Project | /networkinformationfunctions.py | 3,277 | 3.90625 | 4 | import subprocess
import platform
hostname = ""
def getHostName(): # defines the function that gets the hostname from the user
global hostname # declares hostname as a global variable and allows you to change it within the function
hostname = input("\nEnter the target hostname: ") # prints a user request to the screen for a target hostname and assigns the result to the variable hostname
print()
return hostname # returns hostname to the original function call
def checkHostName(targetName): # checks if there is target hostname
if targetName == '':
targetName = getHostName()
print("\nThe target hostname is currently " + str(targetName))
validity = input("Is this the correct hostname/target IP? (Y/N) ").lower()
while validity != 'y':
print("\nChanging the hostname....")
print("The target hostname is currently " + str(targetName))
targetName = getHostName()
print("The target hostname is NOW " + str(targetName))
validity = input("Is this correct? (Y/N) ")
print()
return targetName
def networkInfo(): # prints the network informatino for the host system to the screen (ip address, MAC address, etc.)
systemplatform = platform.system()
if systemplatform == 'Linux':
try:
handle = Popen('ifconfig', stdin=PIPE, stderr=PIPE, stdout=PIPE, shell=True) # Popen executes a child program in a new process (on Windows it calls the CreateProcess() function)
for line in handle.stdout.readlines(): # iterator function that iterates through each line of the process output stored in the handle variable
line = line.decode('utf-8') # decodes the byte information using the utf-8 processes and assigns the result to line
print(line.rstrip())
except:
print("\nList of Network Interfaces:")
subprocess.call('ip address', shell=True)
print("\nSystem's Kernel Routing Table:")
subprocess.call('ip route', shell=True)
print()
elif systemplatform == 'Windows':
print()
subprocess.call('ipconfig', shell=True)
print()
else:
print("The network information could not be determined.")
return
def pingTarget(targetName): # pings a target host
global hostname
hostname = checkHostName(targetName)
systemplatform = platform.system()
if systemplatform == 'Linux':
cmd = "ping -c 4 " + hostname
elif systemplatform == 'Windows':
cmd = "ping " + hostname
else:
print("Could not perform traceroute on current system.")
return hostname
returned_value = subprocess.call(cmd, shell=True)
return hostname
def traceTheRoute(targetName): # shows the route taken by packets across an IP network
global hostname
hostname = checkHostName(targetName)
systemplatform = platform.system()
if systemplatform == 'Linux':
cmd = "traceroute " + hostname
elif systemplatform == 'Windows':
cmd = "tracert " + hostname
else:
print("Could not perform traceroute on current system.")
return hostname
returned_value = subprocess.call(cmd, shell=True)
print("\nProcess Completed!\n")
return hostname
|
11b1aa4b3eb5156f08c947809f12e2508e0796d9 | nikl1425/Snake | /player.py | 1,567 | 3.625 | 4 | import pygame
# Game config
WIDTH = 600
HEIGHT = 600
FPS = 1
SCORE = 0
clock = pygame.time.Clock()
red = (161, 40, 48)
lime = (0, 255, 0)
snake_body = []
x_back = 30
y_back = 30
intro_screen = False
class Player:
def __init__(self, x, y, width, height, direction):
self.x = x
self.y = y
self.width = width
self.height = height
self.direction = direction
self.speed = 30
self.body_parts = [pygame.Rect(self.x, self.y, self.width, self.height)]
def player_movement(self):
# change direction on input
if self.direction == "right":
self.x += self.speed
if self.direction == "down":
self.y += self.speed
if self.direction == "up":
self.y -= self.speed
if self.direction == "left":
self.x -= self.speed
# prevent player from exiting screen
if self.x + self.width/2 < 0:
self.x = WIDTH
if self.x > WIDTH:
self.x = 0
if self.y + self.height/2 < 0:
self.y = HEIGHT
if self.y > HEIGHT:
self.y = 0
def get_rect(self):
box = pygame.Rect(self.x, self.y, self.width, self.height)
return box
def draw(self, window):
for body_part in self.body_parts:
pygame.draw.rect(window, red, body_part)
print(body_part.x)
def update(self):
self.player_movement()
self.body_parts.insert(0, pygame.Rect(self.x, self.y, self.width, self.height))
self.body_parts.pop() |
61e13505bf99a93d2fbb825959a5b79223937e18 | 4daJKong/Leetcode_by_Python | /026_rmDupli.py | 997 | 3.609375 | 4 | def removeDuplicates(nums):
n = len(nums)
i = n - 1
while (i > 0) and (n > 1):
if nums[i] == nums[i - 1]:
del nums[i]
n = n - 1
i = n - 1
else:
i = i - 1
return nums
def removeDuplicates_demo(nums):
n = len(nums)
i = 0
for j in range(1, n):
#print("i:",nums[i], "j:", nums[j])
if nums[i] != nums[j]:
print(nums[i])
i = i + 1
print(nums[i])
print(nums[j])
nums[i] = nums[j]
print('s:',nums)
return i + 1
num1 = [1,1,2]
num2 = [0,0,1,1,1,2,2,3,3,4]
num3 = [1,1]
num4 = [1,2,2,3,4]
# print(removeDuplicates(num1))
# print(removeDuplicates(num2))
# print(removeDuplicates(num3))
# print(removeDuplicates(num4))
# print(removeDuplicates_demo(num1))
# print(removeDuplicates_demo(num2))
# print(removeDuplicates_demo(num3))
print(removeDuplicates_demo(num4))
|
e2e571532a9da8b6be5f8caaa17d1b438d5ba452 | kotano/brain-games | /brain_games/game_engine.py | 1,786 | 3.828125 | 4 | from brain_games.cli import welcome_user
import prompt
DIFFICULTY = {'easy': 3, 'normal': 5, 'hard': 15, 'infinite': 1000}
def engine(game_module, rounds=None):
'''Main algorithm for building games. Takes as a required argument game_module
with function named generate, use second argument to enable difficulty
setting'''
correct_answers_count = 0
print('\nWelcome to the Brain Games! ')
print(game_module.RULE, end='\n\n')
name = welcome_user()
if rounds is None:
diffic = input(
'Please, select difficulty [easy, normal, hard, infinite]: ')
if diffic == 'normal':
max_correct_answers = DIFFICULTY['normal']
elif diffic == 'hard':
max_correct_answers = DIFFICULTY['hard']
elif diffic == 'infinite':
max_correct_answers = DIFFICULTY['infinite']
else:
max_correct_answers = DIFFICULTY['easy']
else:
max_correct_answers = rounds # may be an error if entered a number
while correct_answers_count < max_correct_answers:
question, correct_answer = game_module.generate()
correct_answer = correct_answer
print('\nQuestion: {}'.format(question))
answer = prompt.string('Your answer: ')
if answer == 'q' or answer == 'exit':
print('Goodbye, {} ;('.format(name))
break
elif answer == correct_answer:
print('Correct!')
correct_answers_count += 1
else:
print(
"'{}' is wrong answer ;(."
"Correct answer was '{}' ".format(answer, correct_answer)
)
print('Let\'s try again, {}!'.format(name))
else:
print('Congratulations, {name}!'.format(name=name))
|
4af1787ac3b1899f7f5b12b4aaca84c622b63d5b | Srajan011/capgemini | /Python Programs Capgemini/Python Programs Capgemini/day1/programs/program1.py | 126 | 3.890625 | 4 | #Input your name into a variable called name and then print "Hello,
#<your name here>"
name = 'Hiren'
print("Hello",name)
|
6b379da1094fd28998410b29dbb35a6c4397c01c | juanksRuiz/Utilidades | /Estadistica.py | 609 | 3.5 | 4 | def promedio(valores):
#Retorna el promedio de los valores ingresados
suma = 0
for v in valores:
suma = suma + float(v)
return suma/(len(valores))
def varianza(valores):
#Retorna la varianza de los valores ingresados
mean = promedio(valores)
sumDist = 0
for v in valores:
sumDist = sumDist + (v-mean)**2
return sumDist
def sd(valores):
#Retorna la desviacion estandar de los valores ingresados
mean = promedio(valores)
sumDist = 0
for v in valores:
sumDist = sumDist + (v-mean)**2
sd = sumDist**(1.0/2.0)
return sd
|
22c07ecbd4b70880b38d4b414075b4e9ad0f36a3 | Doomsday46/python_course | /venv/python_course/lab2.py | 929 | 3.703125 | 4 | import math as m
def task1():
print("task 1")
print("---- Float -----")
print(firstExpression(1.25, 1))
print(secondExpression(4, 1))
print(thirdExpression(5, 6))
print("---- Integer -----")
print(int(firstExpression(1.25, 1)))
print(int(secondExpression(4, 1)))
print(int(thirdExpression(5, 6)))
def task2(x, y, z):
print("task 2")
print("Old value: ", x, y, z)
t = x
x = y
y = z
z = t
print("Value: ", x, y, z)
def firstExpression(x, y):
numerator = m.sqrt(x - 1) - m.sqrt(y)
denominator = 1 + (x ** 2) / 2.0 + (y ** 2) / 4.0
return numerator / denominator
def secondExpression(x, z):
return x * (m.tan(z) + m.exp(-(x + 3)))
def thirdExpression(x, y):
numerator = 3 + m.exp(y - 1)
denominator = 1 + x ** 2 - 10
return numerator / denominator
def performLaboratory():
print("Laboratory 2")
task1()
task2(0, 1, 2)
|
1aeb33a70f36746c21fd174b867805f53486425a | WongWai95/LeetCodeSolution | /25. K 个一组翻转链表/Solution.py | 789 | 3.625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
p_head = head
for _ in range(k):
if p_head == None:
return head
else:
p_head = p_head.next
res = ListNode(None)
p_res = res
candidate = [None for _ in range(k)]
for i in range(k-1, -1, -1):
candidate[i] = head
head = head.next
for i in range(k):
p_res.next = candidate[i]
p_res = p_res.next
p_res.next = self.reverseKGroup(p_head, k)
return res.next |
20f35c3afb011f4d3528ba4b4ba7035a5d0beec0 | amitks815/Old_programs | /argv/commandlinearg.py | 231 | 3.5625 | 4 | from sys import argv
print ("value1",argv[0])
print ("value1",argv[1])
print ("value1",argv[2])
print ("value1",argv[3])
print ("value1",argv[4])
list=[argv[1],argv[2],argv[3],argv[4]]
print (list)
for i in list:
print(int(i)) |
e1752f0195e19a5005b5819ac7f1f02bd20db903 | edimaudo/Project-Euler | /ProjectEuler007.py | 381 | 3.65625 | 4 | def is_prime(n):
n = abs(int(n))
if n < 2:
return False
if n==2:
return True
if not n & 1:
return False
for x in range(3,int(n**0.5)+1,2):
if n % x == 0:
return False
return True
count = 0
for i in range (1,20000000):
if is_prime(i) == True:
count+=1
if count == 10001:
print(i)
|
46cc2971b7ec747d22c41deb0d30ae7c639fd82a | KFurudate/Atcoder_SHOJIN | /Atcoder/猪突猛進_貪欲法/辞書式順序/ABC_007_B_辞書式順序.py | 660 | 3.609375 | 4 | #https://atcoder.jp/contests/abc007/tasks/abc007_2
"""
それぞれの文字列の同じ位置同士を先頭から比較していって、初めて不一致になったら、
その文字同士の(アルファベットでの)比較結果が文字列の全体の比較結果である。
例えば、 " a b c d " と " a x " を比較すると、 2 文字目で、 ′ b ′ < ′ x ′ となるので、
" a b c d "<" a x " である。
もし、比較している途中で片方の文字列が尽きてしまったら、文字列の長さが短い方が小さい。
例えば " a b "<" a b c " である。
"""
A = input()
if len(A) > 1:
print(A[0])
|
3a199fe9062eb986896d2178d8b1e34d0a85a3a8 | ivan-sepulveda/algorithms | /sort/selection_sort.py | 1,717 | 3.59375 | 4 | import sys
test_array = [20, 21, 12, 11, 13, 5, 6]
sorted_test_array = sorted(test_array)
def selection_helper(sorted_array, index_min_unsorted_elem, index_next_unsorted_elem):
return index_next_unsorted_elem \
if sorted_array[index_min_unsorted_elem] > sorted_array[index_next_unsorted_elem]\
else index_min_unsorted_elem
def min_index(sorted_array, index_next_unsorted_elem, j):
if index_next_unsorted_elem == j:
return index_next_unsorted_elem
index_min_unsorted_elem = min_index(sorted_array, index_next_unsorted_elem + 1, j)
return selection_helper(sorted_array, index_min_unsorted_elem, index_next_unsorted_elem)
def selection_sort(array, recursive=True, n=sys.maxsize, index_min_unsorted_elem=0):
array_length, sorted_array = len(array), array.copy()
if array_length <= 1 or n == 0 or index_min_unsorted_elem == n:
return array
if recursive:
num_elems = len(sorted_array) if n == sys.maxsize else n
k = min_index(sorted_array, index_min_unsorted_elem, num_elems - 1)
sorted_array[k], sorted_array[index_min_unsorted_elem] = sorted_array[index_min_unsorted_elem], sorted_array[k]
sorted_array = selection_sort(sorted_array, True, num_elems, index_min_unsorted_elem + 1)
else:
for k in range(array_length):
index_min_unsorted_elem = k
for index_next_unsorted_elem in range(k+1, array_length):
index_min_unsorted_elem = selection_helper(sorted_array, index_min_unsorted_elem, index_next_unsorted_elem)
sorted_array[k], sorted_array[index_min_unsorted_elem] = sorted_array[index_min_unsorted_elem], sorted_array[k]
return sorted_array
|
e3fe1f8a9ff986ca4b788b5fdd87719dd13e9417 | curande5786/python-challenge | /PyBank/main.py | 1,904 | 3.578125 | 4 | #PyBank Challenge
#import dependencies
import csv, os
#import file as variable
csv_file = os.path.join("Resources", "budget_data.csv")
#set path for output file
my_report = open("analysis/myreport.txt","w")
#access file and set variable
with open(csv_file) as profLoss:
#read file, set variable for file reader
file = csv.reader(profLoss)
#skip and store the header
header = next(file)
#set variables
total = 0
months = 0
first = 0
prevrow = 0
prev_rev = 0
ch_sum = 0
#set arrays to track date of and values for
#greatest increase and decrease in profit
inc = ['',0]
dec = ['',0]
#begin looping rows
for row in file:
#track total months counted in data
months += 1
#set variable to the value in column 2
rev = int(row[1])
#count total revenue
total += rev
#track changes from row to row
change = rev - prev_rev
#run conditional setting the change to zero on the first row
if prev_rev == 0:
change = 0
#add tracked changes together
ch_sum += change
#set variable to current row before moving on to the next one
prev_rev = rev
#find greatest increase in profit
if change > inc[1]:
inc[0] = row[0]
inc[1] = change
#find greatest decrease in profit
if change < dec[1]:
dec[0] = row[0]
dec[1] = change
#set variable containing the results
output = f'''
Financial Analysis
----------------------------
Total Months: {months}
Total: ${total:,}
Average Change: ${ch_sum/(months-1):,.2f}
Greatest Increase in Profits: {inc[0]} (${inc[1]:,})
Greatest Decrease in Profits: {dec[0]} (${dec[1]:,})
'''
#print results
print(output)
#write to file
my_report.write(output) |
621048af5fb08e24a18b8c536ea2d8f46b3945b2 | athirarajan23/luminarpython | /data collections/common elements in a string.py | 75 | 3.65625 | 4 | s1={1,2,3,4,5}
s2={1,5,4,7,8}
for i in s1:
if i in s2:
print(i) |
6fcef2d7d20013f4d4f851622e7019287bbd6ad1 | ChiSha2019/USACO_Solution_Python | /Bronze/wordProcessor/word_bronze_jan20/word_processor_class_demo.py | 988 | 3.625 | 4 | '''
strategy:
for each line
keep looping
if current_length + length of next word > K, change line,
update current_length to be length of next word
else current_length = current_length+ length of next word
'''
with open("word.in", "r") as input_file:
line1 = input_file.readline().split()
word_num = int(line1[0])
max_char_num_each_line = int(line1[1])
line2 = input_file.readline().split()
with open("word.out", "w") as output_file:
current_length = 0
for i in range(0, word_num):
if current_length + len(line2[i]) > max_char_num_each_line:
output_file.write("\n")
output_file.write(line2[i])
current_length = len(line2[i])
else:
current_length = current_length + len(line2[i])
output_file.write(line2[i])
if i < word_num -1 and current_length + len(line2[i+1]) <= max_char_num_each_line:
output_file.write(" ")
|
2a60bb2c6fea506003224803c00be3feea364f56 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_207/392.py | 1,369 | 3.625 | 4 | # raw_input() reads a string with a line of input, stripping the '\n' (newline) at the end.
# This is all you need for most Google Code Jam problems.
possibles = ['R', 'O', 'Y', 'G', 'B', 'V']
t = int(raw_input()) # read a line with a single integer
for i in xrange(1, t + 1):
params = [int(s) for s in raw_input().split(" ")]
n = params[0]
nums = params[1:]
small = [{"key":"R", "num":nums[0]}, {"key":"Y", "num":nums[2]}, {"key":"B", "num":nums[4]}]
small = sorted(small, key = lambda x: x["num"], reverse = True)
if small[0]["num"] > n/2:
print "Case #{}: IMPOSSIBLE".format(i)
continue
finish = False
ret = ""
while not finish:
if small[0]["num"] > small[1]["num"]:
ret = ret + small[0]["key"] + small[1]["key"] + small[0]["key"] + small[2]["key"]
small[0]["num"] -= 2
small[1]["num"] -= 1
small[2]["num"] -= 1
else:
ret = ret + small[0]["key"] + small[1]["key"]
small[0]["num"] -= 1
small[1]["num"] -= 1
if small[2]["num"] > 0:
ret = ret + small[2]["key"]
small[2]["num"] -= 1
if small[0]["num"] <= 0:
finish = True
print "Case #{}: {}".format(i, ret)
# else:
# check out .format's specification for more formatting options
|
b085620eafa668f1b311db5748926d31f45969dc | shuowenwei/LeetCodePython | /Easy/LC70ClimbingStairs.py | 431 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
@author: Wei, Shuowen
https://leetcode.com/problems/climbing-stairs/
"""
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
results = []
for i in range(n+1):
if i < 3 :
results.append(i)
else:
results.append( results[i-1] + results[i-2] )
return results[n] |
e9f475711fef9e5b9e71e15656932bea76fd47f3 | nacho1415/Toy_Blockchain | /OneDrive/바탕 화면/알고리즘/9000~10000/9226.py | 475 | 3.875 | 4 | while(True):
item = list(input())
if(item[0] == "#"):
break
else:
while(True):
if(item[0] == "A" or item[0] == "E" or item[0] == "I" or item[0] == "O" or item[0] == "U" or item[0] == "a" or item[0] == "e" or item[0] == "i" or item[0] == "o" or item[0] == "u"):
print("".join(item)+"ay")
break
else:
temp = item[0]
del item[0]
item.append(temp) |
7933043bc5906632faa1fee7a8bc662df39b14d7 | jeongwoohong/iot_python2019 | /01_Jump_to_python/3_control/4_exer/diamond.py | 311 | 3.703125 | 4 | start = 1
while True:
diamond = int(input("홀수를 출력하세요(0 <-종료)"))
if diamond==0:
break
elif diamond%2==0:
continue
else:
while diamond > start:
print(" "*((diamond-start)//2-1)+('*'* start)+" "*((diamond-start)//2-1))
start += 2
|
e27460aa16022bdf0c0cdffd82f09719265d4f7e | vsharmanyc/cse337 | /minor-hw1/burger.py | 1,607 | 4.0625 | 4 | # Vasu Sharma
# 110493783
# vvsharma
#
# CSE 337 (Fall 2019)
# Minor Homework 1, Problem 1
def burger(order):
if type(order) == type("") and order != "":
protiens = 0
toppings = 0
condiments = 0
for x in order:
if x in "BTV":
protiens += 1
elif x in "ltopjcbsmf":
toppings += 1
elif x in "kuyaq":
condiments += 1
else:
return "unrecognized order code"
if protiens == 1 and 0 <= toppings <= 5 and 0 <= condiments <=2:
if "B" in order:
return 0.5 * toppings + 2.0
elif "T" in order:
return 0.5 * toppings + 2.5
else:
return 0.5 * toppings + 2.25
else:
return "invalid order"
else:
return "unrecognized order code"
# DO NOT DELETE THE FOLLOWING LINES OF CODE! YOU MAY
# CHANGE THE FUNCTION CALLS TO TEST YOUR WORK WITH
# DIFFERENT INPUT VALUES.
if __name__ == "__main__":
print('burger("Bck"):', burger("Bck")) # simple cheeseburger
print()
print('burger("Tpmlmy"):', burger("Tpmlmy")) # turkey burger w/ stuff
print()
print('burger("altop"):', burger("altop")) # error: no protein
print()
print('burger("VtojsT"):', burger("VtojsT")) # error: too many protein choices
print()
print('burger("lsucjV"):', burger("lsucjV")) # okay; protein at end
print()
print('burger("Bqcbksmfy"):', burger("Bqcbksmfy")) # error: too many condiments
print()
print('burger("Toxpk"):', burger("Toxpk")) # error: invalid character (x)
print()
print('burger("Vqltopjm"):', burger("Vqltopjm")) # error: too many toppings
print()
|
17930a1f3446aa3c6e0e0110d60c32641a3cd3f4 | JairZhu/CODE | /python/tutorial/8_7_7.py | 291 | 3.59375 | 4 | import csv
import sqlite3
db = sqlite3.connect('books.db')
curs = db.cursor()
ins = 'insert into book values(?,?,?)'
with open('article.csv', 'rt') as fin:
books = csv.DictReader(fin)
for row in books:
curs.execute(ins, (row['title'], row['author'], row['year']))
db.commit() |
c8702c326bd11ce0ae6de200840e515f7eefe7cf | mvrramos/python | /curso-em-video/aprovando_emprestimo.py | 449 | 3.890625 | 4 | valorcasa = int(input('Digite o valor da casa '))
salario = int(input('Qual o seu salario '))
anos = int(input('Em quantos anos deseja pagar '))
parcela = anos * 12
valortotal = valorcasa/parcela
porcento = salario * 0.30
print(f'Voce deverá pagar {valortotal} reais todo mês')
if valortotal > porcento or valortotal == porcento:
print('Você não pode comprar a casa, sinto muito')
else:
print(f'Você pode comprar a casa, parabéns')
|
4bc2421c92a5b3b3db99f3f95cbff7c90abadce7 | raffivar/SelfPy | /unit_3_strings/palindrome.py | 159 | 3.96875 | 4 | s = input("is palindrome: ")
s = s.lower()
s = s.replace(' ', '')
print(s + " == " + s[::-1] + " ? ")
if s == s[::-1]:
print('OK')
else:
print('NOT')
|
028b5542bf58f27b0607b86349ecdecb254918bd | davidebarcelli/4A_SIS_2018_19 | /pythonBasics.py | 1,253 | 4.125 | 4 | # Questo e' un commento in python
# In python le variabili non hanno un tipo escliito, quindi non necessitano dichiarazione
a = 1
# per stamapre una variabile bast usare print
print(a)
# e' possbile fare stampe piu' complesse, ma tenedo conto dei tipi
print("a = "+str(a)+" !!")
# in python non eistono {}, la dipendenza si escplicita con l'indetazione
if(a>0):
print("numero")
print("positivo")
else:
print("numero")
print("negativo")
# notate che tutte le sitruzioni indentate fanno parte del blocco dipendente
# in python il for funziona con i range
a=10
for i in range(0,a):
a=a-1
print("i="+str(i)+", a="+str(a))
# notate che anche modificando il valore di a il ciclo esegue 10 volte, perche'?
# perche' il range viene generato all'inizio, in fatti si potrebbe anche scrivere
a=10
r = range(0,a)
for i in r:
a=a-1
print("i="+str(i)+", a="+str(a))
# una cosa importante che si puo' fare con python sono le funzioni
def somma(a,b):
return a+b
#per chiamarle e' facile
b=somma(4,5)
print(b)
# libreria grafica in Python
from Tkinter import *
# creazione di una finestra
root = Tk()
# creo un testo
l = Label(root, text="ciaociao")
# dico di visualizzarlo
l.pack()
# inizio del ciclo infinito di ascolto degli eventi
root.mainloop()
|
9254499cea5fcdaa4a6872741b1b0e38601caa9e | Jugveer-Sandher/PythonProjects | /Dictionaries/main.py | 3,867 | 3.84375 | 4 | import utilities_set
import utilities_dict
def main():
""" Main Program """
# PART A
set1 = {'apple', 'banana', 'orange', 'peach'}
set2 = {'banana', 'pineapple', 'peach', 'watermelon'}
set1_count = utilities_set.get_total_items(set1)
print("The total number of items in set1 is:", set1_count)
print()
print("Displaying the items of the set1:")
utilities_set.display_all_items(set1)
print()
utilities_set.add_item("grape", set1)
print("Added a grape, new set items are: ")
utilities_set.display_all_items(set1)
print()
utilities_set.remove_item("orange", set1)
print("Removed orange, new set items are: ")
utilities_set.display_all_items(set1)
print()
set3 = utilities_set.get_the_union_of(set1, set2)
print("The union of set1 and set2 is: ")
utilities_set.display_all_items(set3)
print()
# # PART B
provinces = {"alberta": "edmonton",
"ontario": "toronto",
"quebec": "quebec city",
"nova scotia": "halifax",
"new brunswick": "fredericton",
"manitoba": "winnipeg",
"prince edward island": "charlottetown",
"saskatchewan": "regina",
"newfoundland and labrador": "st. john's",
"yukon": "whitehorse",
"nunavut": "iqaluit",
"northwest territories": "yellowknife",
"british columbia": "victoria"}
print("The current dictionary contains: ")
utilities_dict.display_all(provinces)
print()
print("The capital for Yukon is:", utilities_dict.get_capital_city("yukon", provinces))
print()
print("removing Manitoba from list: ")
utilities_dict.remove_province("manitoba", provinces)
utilities_dict.display_all(provinces)
print()
print("Adding Manitoba back: ")
utilities_dict.add_province("manitoba", "winnipeg", provinces, )
utilities_dict.display_all(provinces)
print()
# PART C
canada = {
"alberta": {"capital": "edmonton", "largest": "calgary", "population": 3645257},
"ontario": {"capital": "toronto", "largest": "toronto", "population": 12851821},
"quebec": {"capital": "quebec city", "largest": "montreal", "population": 7903001},
"nova scotia": {"capital": "halifax", "largest": "halifax", "population": 921727},
"new brunswick": {"capital": "fredericton", "largest": "saint john", "population": 751171},
"manitoba": {"capital": "winnipeg", "largest": "winnipeg", "population": 1208268},
"prince edward island": {"capital": "charlottetown", "largest": "charlottetown", "population": 140204},
"saskatchewan": {"capital": "regina", "largest": "saskatoon", "population": 1033381},
"newfoundland and labrador": {"capital": "st. john's", "largest": "st. john's", "population": 514536},
"yukon": {"capital": "whitehorse", "largest": "whitehorse", "population": 33897},
"nunavut": {"capital": "iqaluit", "largest": "iqaluit", "population": 31906},
"northwest territories": {"capital": "yellowknife", "largest": "yellowknife", "population": 41462},
"british columbia": {"capital": "victoria", "largest": "vancouver", "population": 4400057}
}
print("The total population of the provinces are:", utilities_dict.get_total_population(canada))
print()
print("The smallest province is:", utilities_dict.get_smallest_province(canada))
print()
print("The largest province is:", utilities_dict.get_largest_province(canada))
print()
print("The capital of Yukon is:", utilities_dict.get_another_capital_city ("yukon", canada))
print()
print("The largest city of Quebec is:", utilities_dict.get_largest_city("quebec", canada))
if __name__ == '__main__':
main()
|
95af104578e282750440cf79f9b4db1a1fbd4d0b | PSohini/python-challenge | /PyBank/Main.py | 2,236 | 3.78125 | 4 | # import the os module
import os
#Module for reading csv files
import csv
#Declare Global Variables
TotalMonths = 0
month_of_change=[]
net_change_list=[]
greatest_increase = ["", 0]
greatest_decrease = ["", 9999999999999999999]
total_net = 0
#Files to load
file_to_load = os.path.join('budget_data.csv')
print(file_to_load)
with open(file_to_load, newline='') as csvfile:
# CSV reader specifies delimiter and variable that holds contents
reader = csv.reader(csvfile, delimiter=',')
# Set a variable to header and set that to next csv reader
header=next(reader)
first_row = next(reader)
print(header)
# Extract row 1 to avoid appending to change values
first_row = next(reader)
TotalMonths = TotalMonths + 1
total_net = total_net + int(first_row[1])
prev_net = int(first_row[1])
for row in reader:
TotalMonths = TotalMonths + 1
total_net = total_net + int(first_row[1])
# Track Changes
net_change = int(row[1]) - prev_net
prev_net = int(first_row[1])
net_change_list = net_change_list + [net_change]
month_of_change = month_of_change + [row[0]]
# Calculate the greatest increase
if net_change < greatest_decrease[1]:
greatest_decrease[0] = row[0]
greatest_decrease[1] = net_change
# Calculate the greatest increase
if net_change > greatest_increase[1]:
greatest_increase[0] = row[0]
greatest_increase[1] = net_change
# Calculate avg net change
net_monthly_avg = sum(net_change_list) / len(net_change_list)
#Generate Output Summary
output = (
f"\n Financial Analysis \n"
f"---------------------------------\n"
f"Total Months: {TotalMonths}\n"
f"Total: ${total_net}\n"
f"Average Change : ${net_monthly_avg:.2f}\n"
f"Greatest Increase in Profits: {greatest_increase[0]} (${greatest_increase[1]})\n"
f"Greatest Decrease in Profits: {greatest_decrease[0]} (${greatest_decrease[1]})\n")
print(output)
#Write output file
# Set variable for output file
output_file = os.path.join("pybank_final.csv")
# Display results on output file
with open(output_file, "w") as txt_file:
txt_file.write(output)
|
7ca684e1d409382010ea582508d1b6f4d4bd1521 | Kechkin/PythonNiitCourse | /8/count_symbol.py | 183 | 3.875 | 4 | def count_symbol(str, symb):
arr = str.split(" ")
count = 0
for i in range(len(arr)):
if symb in arr[i]:
count+=1
return count
print(count_symbol("Hi Elvis, I am here", "i")) |
c519825eab506b4f074201901eb1f3267fc7ef3f | mpettersson/PythonReview | /questions/data_structure/graph/shortest_snakes_and_ladders_path.py | 3,001 | 4.15625 | 4 | """
SHORTEST SNAKES AND LADDERS PATH
Design an algorithm, which when given two list of tuples representing the start and end of the Snakes and Ladders
on the board, will return the shortest path (i.e., least number of rolls) to the end.
You can assume that the board consists of positions 1 to 100, where 1 is the start and 100 is the end. Furthermore,
Snakes and Ladders cannot start on position 1 or 100 (however they may end on any position), and a dice roll
produces a random int in the range [1,6].
"""
import heapq
def find_shortest_path(snakes, ladders):
graph = generate_graph(snakes, ladders)
source = 1
min_queue = []
weights = {k: float('inf') for k in graph.keys()}
previous = {k: None for k in graph.keys()}
visited = {k: False for k in graph.keys()}
weights[source] = 0
heapq.heappush(min_queue, (0, source))
while len(min_queue) > 0:
w_to_node, node = heapq.heappop(min_queue)
visited[node] = True
for adj, w_to_adj in graph[node]:
if not visited[adj]:
new_w = w_to_node + w_to_adj
if new_w < weights[adj]:
weights[adj] = new_w
previous[adj] = node
heapq.heappush(min_queue, (new_w, adj))
path = []
node = max(graph.keys())
while node:
path.insert(0, node)
node = previous[node]
return -1 if weights[100] == float('inf') else weights[100], path if path[0] == 1 and path[-1] == 100 else None
def generate_graph(num_spaces, snakes=None, ladders=None):
if num_spaces <= 0:
raise ValueError()
graph = {}
for i in range(1, num_spaces + 1):
graph[i] = []
j = 1
while j < 7 and i + j <= num_spaces:
graph[i].append((i + j, 1))
j += 1
for (s, e) in ladders:
if s not in graph or e not in graph or s <= 1 or s == e or s >= num_spaces or e <= 1:
raise ValueError()
graph[s].append((e, 0))
for (s, e) in snakes:
if s not in graph or e not in graph or s <= 1 or s == e or s >= num_spaces:
raise ValueError()
graph[s] = [(e, 0)]
return graph
boards = [ # Board 1 - Should be 3 dice rolls.
([(95, 13), (97, 25), (93, 37), (79, 27), (75, 19), (49, 47), (67, 17)], [(32, 62), (42, 68), (12, 98)]),
# Board 2 - Should be 5 dice rolls.
([(51, 19), (39, 11), (37, 29), (81, 3), (59, 5), (79, 23), (53, 7), (43, 33), (77, 21)], [(8, 52), (6, 80), (26, 42), (2, 72)]),
# Board 3 - Should be 3 dice rolls.
([(56, 33)], [(3, 54), (37, 100)]),
# Board 4 - Should be 2 dice rolls.
([(88, 44)], [(3, 57), (8, 100)]),
# Board 5 - Should be 2 dice rolls.
([(99, 1)], [(7, 98)])]
for snakes, ladders in boards:
num_dice_rolls, path = find_shortest_path(snakes, ladders)
print(f"Number of rolls: {num_dice_rolls}, Path: {path}")
|
1501710c29e42ebf545a926fcb67ddf344b27f59 | gabriellaec/desoft-analise-exercicios | /backup/user_190/ch23_2020_03_25_17_31_26_355690.py | 149 | 3.828125 | 4 | v=float(input("velocidade?: "))
if v>80:
multa=5*(v-80)
print('Multado em R${0:.2f}'.format(multa))
else:
print ("Não foi multado")
|
6f81518250e625dd14d6287b779e3d46368892d4 | amogchandrashekar/Leetcode | /Easy/Minimum Value to Get Positive Step by Step Sum.py | 1,512 | 4.1875 | 4 | """
Given an array of integers nums, you start with an initial positive value startValue.
In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right).
Return the minimum positive value of startValue such that the step by step sum is never less than 1.
Example 1:
Input: nums = [-3,2,-3,4,2]
Output: 5
Explanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1.
step by step sum
startValue = 4 | startValue = 5 | nums
(4 -3 ) = 1 | (5 -3 ) = 2 | -3
(1 +2 ) = 3 | (2 +2 ) = 4 | 2
(3 -3 ) = 0 | (4 -3 ) = 1 | -3
(0 +4 ) = 4 | (1 +4 ) = 5 | 4
(4 +2 ) = 6 | (5 +2 ) = 7 | 2
"""
from typing import List
class Solution:
def minStartValue(self, nums: List[int]) -> int:
cum_sum = 0
minimum = 1
"""
Calculate cumulative sum as shown in the problem description, maintain a variable which tracks the
minimum cumulative sum. If minimum cumulative sum is less than zero, we need positive equivalent of
cum_sum + 1 to make the total sum positive. Else, 1 is the least. Hence, return as calculated
"""
for num in nums:
cum_sum += num
minimum = min(minimum, cum_sum)
return max(1, 1 - minimum)
if __name__ == "__main__":
print(Solution().minStartValue([-3, 2, -3, 4, 2])) |
aff1b6b2088848f50a5e87a514a18f133bca9cc4 | thhsu116/LeetCode | /025_ReverseNodesink-Group.py | 1,719 | 3.703125 | 4 | # https://leetcode.com/problems/reverse-nodes-in-k-group/description/
# 95% 56ms, traverse nodes and use stack to reverse nodes every k steps, time complexity O(n), space complexity O(k)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
last = dummy
cur = dummy.next
stack = []
while cur:
stack.append(cur)
cur = cur.next
if len(stack) == k:
while stack:
last.next = stack.pop()
last = last.next
last.next = cur
if stack:
last.next = stack[0]
return dummy.next
# not using stack
class Solution:
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
# Dummy node initialization
dummy = jump = ListNode(-1)
dummy.next = l = r = head
while True:
count = 0
while r and count < k:
count += 1
r = r.next
if count == k:
pre, cur = r, l
for _ in range(k):
temp = cur.next
cur.next = pre
pre = cur
cur = temp
jump.next = pre
jump = l
l = r
else:
return dummy.next
|
a66306f1cf870c025229bee8f8e42fe2a670517b | aflyk/hello | /pystart/lesson4/l4t6_2.py | 661 | 3.953125 | 4 | """
Реализовать два небольших скрипта:
а) бесконечный итератор, генерирующий целые числа, начиная с указанного,
б) бесконечный итератор, повторяющий элементы некоторого списка, определенного заранее.
Подсказка: использовать функцию count() и cycle() модуля itertools.
"""
from itertools import cycle
def cyciter(lst):
for i in cycle(lst):
yield i
if __name__ == "__main__":
for i in cyciter([1, 2, 3, 4, "pes", {'s': "k"}]):
print(i) |
c0a21f04f162653d964754052e554de0c3d02cd2 | Homap/ZtoA_Heterozygosity | /intergenic.py | 385 | 3.578125 | 4 | #!/usr/bin/python
import sys
# Function to read an intergenic coordinate file into a dictionary
def intergenicCoord(intergenic):
intergenicDict= {}
for line in intergenic:
line = line.strip().split("\t")
key, value = line[0], line[1:]
if line[0] in intergenicDict.keys():
intergenicDict[key].append(value)
else:
intergenicDict[key] = [value]
return intergenicDict
|
3b4c4d2212e6e44262daca1af0f6d69676dc36fc | YuchinP/TTA-Python | /simple_script.py | 139 | 3.84375 | 4 | x=10
y=2
#Print x+y
'''prints x+y
to the shell'''
print (x+y)
if x == 10:
print ('x = 10')
#Still in statement
#not in statement
|
b3e9f717a8159880033a01ac1a706bb9c2638d0b | sbz786002/MERC | /sndmail.py | 1,433 | 3.5 | 4 | import smtplib, ssl
import requests
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
port = 587 # For starttls
smtp_server = "smtp.gmail.com"
sender_email = "mis3@virolaindia.com"
receiver_email = "mis@albertotorresi.com"
cc = "sbz786005@gmail.com,eavs@virolaindia.com,customercare@albertotorresi.com,eavs2@virolaindia.com"
password = "mis3@2016"
message = MIMEMultipart("alternative")
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email
message["Cc"] = cc
# Create the plain-text and HTML version of your message
text = """\
Hi,
How are you?
Real Python has many great tutorials:
www.realpython.com"""
html = """\
<html>
<body>
<p>Hi,<br>
How are you?<br>
<a href="http://www.realpython.com">Real Python</a>
has many great tutorials.
</p>
</body>
</html>
"""
# Turn these into plain/html MIMEText objects
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
# Add HTML/plain-text parts to MIMEMultipart message
# The email client will try to render the last part first
message.attach(part1)
message.attach(part2)
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())
print("done") |
2811d995cab97374495b20bb7eb5e0d0b951d934 | andy5874/python | /classQ2.py | 447 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 30 13:55:08 2020
@author: cjdgh
"""
'''
Question 2
Create a circle class that will take the value of a radius and
return the area of the circle
'''
import math
class CircleArea (object):
def __init__ (self, radius):
self.radius = radius
def get_area(self):
area = math.pi * self.radius**2
return area
circle = CircleArea(5) |
25d6f56295ca62866bcdb7f54801dc5a6561b960 | cwpachecol/022021_SIS420 | /busqueda_no_informada/Busqueda_Coste_Uniforme/Freeway.py | 2,933 | 3.640625 | 4 | # Búsqueda con Coste Uniforme - Uniform Cost Search
from Tree import Node
def Compare(node):
return node.get_cost()
def search_solution_UCS(connections, init_state, solution):
solved = False
visited_nodes = []
frontier_nodes = []
init_node = Node(init_state)
init_node.set_cost(0)
frontier_nodes.append(init_node)
while (not solved) and len(frontier_nodes) != 0:
# Ordenar lista de nodos frontera
frontier_nodes = sorted(frontier_nodes, key=Compare)
node = frontier_nodes[0]
# Extraer nodo y añadirlo a visitados
visited_nodes.append(frontier_nodes.pop(0))
if node.get_data() == solution:
# Solucion encontrada
solved = True
return node
else:
# Expandir nodos hijo (ciudades con conexion)
node_data = node.get_data()
child_list = []
for achild in connections[node_data]:
child = Node(achild)
cost = connections[node_data][achild]
child.set_cost(node.get_cost() + cost)
child_list.append(child)
if not child.on_list(visited_nodes):
# Si está en la lista lo sustituimos con el nuevo valor de coste si es menor
if child.on_list(frontier_nodes):
for n in frontier_nodes:
if n.equal(child) and n.get_cost() > child.get_cost():
frontier_nodes.remove(n)
frontier_nodes.append(child)
else:
frontier_nodes.append(child)
node.set_child(child_list)
if __name__ == "__main__":
connections = {
'Malaga': {'Granada': 125, 'Madrid': 513},
'Sevilla': {'Madrid': 514},
'Granada': {'Malaga': 125, 'Madrid': 423, 'Valencia': 491},
'Valencia': {'Granada': 491, 'Madrid': 356, 'Zaragoza': 309, 'Barcelona': 346},
'Madrid': {'Salamanca': 203, 'Sevilla': 514, 'Malaga': 513, 'Granada': 423, 'Barcelona': 603, 'Santander': 437,
'Valencia': 356, 'Zaragoza': 313, 'Santiago': 599},
'Salamanca': {'Santiago': 390, 'Madrid': 203},
'Santiago': {'Salamanca': 390, 'Madrid': 599},
'Santander': {'Madrid': 437, 'Zaragoza': 394},
'Zaragoza': {'Barcelona': 296, 'Valencia': 309, 'Madrid': 313},
'Barcelona': {'Zaragoza': 296, 'Madrid': 603, 'Valencia': 396}
}
init_state = 'Malaga'
solution = 'Santiago'
solution_node = search_solution_UCS(connections, init_state, solution)
# Mostrar resultado
result = []
node = solution_node
while node.get_fathr() is not None:
result.append(node.get_data())
node = node.get_fathr()
result.append(init_state)
result.reverse()
print(result)
print("Coste: %s" % str(solution_node.get_cost()))
|
25fdba874f5d2961701952cd56fd1494399144ff | mrhoanglinh23/tranhoanglinh-fundamentals-c4t4 | /Session02/mrlinhAssignment2/seriousexercise3b2.py | 148 | 3.8125 | 4 | number = int(input("enter a number of 1’s and 0’s: "))
for i in range(19):
for i in range(1):
print("0","1","0","1", end=" ")
|
385dfeb4e5339c31ffcf9f8e1c08444ad06bf0c3 | Suhaiz/first | /test/primee.py | 359 | 3.765625 | 4 | upplim=int(input("enter the upper limit\t"))
lowlim=int(input("enter the lower limit\t"))
sum=0
while lowlim<upplim+1:
i=2
flag=True
while i<upplim:
if upplim%i==0:
flag=False
break
i+=1
if flag:
sum=sum+upplim
print("\n",upplim)
upplim-=1
print("your sum of prime no's is\t",sum)
|
fd12957ace2ea082eb8f7f662bbe9f71ba622a62 | liAmirali/lifeSimulator | /conf/config.py | 1,901 | 3.984375 | 4 | # Developed by liamirali: some day on Dec 2020; version idk
# How long should each day be? (in seconds)
dayLength = 1
# Number of people to start the life
peopleC = 10
# Amount of food and money that people will start the world with.
foodinit = 200
moneyinit = 200
# How much money should each person pay for 1 food?
foodPrice = 2
# How should people pay tax every day?
# Possible inputs:
# 0) torandom => Computer selects a random alive guy (and also not himself)
# 1) toneighbor => Computer finds the alive neighbor of
# person #wid by neighbor.whoIs(wid) function
dailyTaxMethod = 'toneighbor'
# Tax rate has to be a number in (0,1) range
taxRate = 0.4
# How do you want to save the survivors data?
saveMethod = {
"sqlite": True,
"csv": True
}
def sayConfig():
print(f"dayLength = {dayLength}")
print(f"peopleC = {peopleC}")
print(f"foodinit = {foodinit}")
print(f"moneyinit = {moneyinit}")
print(f"foodPrice = {foodPrice}")
print(f"dailyTaxMethod = {dailyTaxMethod}")
print(f"taxRate = {taxRate}")
print(f"saveMethod = {saveMethod}")
## *** DO NOT TOUCH THE FOLLOWING CODE ***
# People will live in this
world = []
# General attitude of people
class person:
alive = True
food = foodinit
money = moneyinit
def __init__(self, wid, generosity, gluttony):
self.wid = wid
self.generosity = generosity
self.gluttony = gluttony
def __str__(self):
return "wid= %s, alive=%s, food=%s, money=%s, generosity=%s, gluttony=%s"\
% (self.wid, self.alive, self.food, self.money, self.generosity, self.gluttony) + "\n"
def __repr__(self):
return "wid= %s, alive=%s, food=%s, money=%s, generosity=%s, gluttony=%s"\
% (self.wid, self.alive, self.food, self.money, self.generosity, self.gluttony) + "\n"
# Days passed
day = 0
# wid of the world's survivor
survivor_wid = None
|
472aa753f6737e8cd6e1f4e745cd25f9ee253887 | Huido1/Hackerrank | /Python/06 - Itertools/05 - Compress the String!.py | 235 | 3.8125 | 4 | #url: https://www.hackerrank.com/challenges/compress-the-string/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
from itertools import groupby
print(*[(len(list(c)), int(k)) for k, c in groupby(input())])
|
d036476016ecc3aa26a04e2a43de1af443c96d8b | nejstastnejsistene/DotBot | /generate_cycle_literals_h.py | 1,614 | 3.5 | 4 | #!/usr/bin/env python
import sys
import itertools
def num_bits(x):
count = 0
while x:
x ^= x & -x
count += 1
return count
# Read the output of ./compute_cycles as pairs of integers.
def read_input():
for line in sys.stdin:
yield map(int, line.split())
# Sort the cycles first by the number of bits/dots in them, and
# secondly by their value (so top and left come first).
key = lambda x: (num_bits(x[0]), x[0])
sorted_pairs = sorted(read_input(), key=key)
# Split the pairs into two separate lists.
cycles, encircled_dots = zip(*sorted_pairs)
# Calculate the offsets where the next size of cycle begins.
offsets = []
offset = 0
for num_dots, group in itertools.groupby(cycles, key=num_bits):
offsets.append((num_dots, offset))
offset += len(list(group))
print '/* This file was automatically generated by', __file__, '*/'
print
print '#ifndef CYCLE_LITERALS_H'
print '#define CYCLE_LITERALS_H'
print
print '#define NUM_CYCLES {}'.format(len(cycles))
print
print '/* Cycles with N dots begin starting at CYCLES_OFFSET_N. */'
for n, offset in offsets:
print '#define CYCLES_OFFSET_{} {}'.format(n, offset)
print
print '/* All cycles, sorted by the number of dots and then their position (top and left first). */'
print 'static const mask_t cycles[NUM_CYCLES] = {'
for x in cycles:
print ' (mask_t){},'.format(x)
print '};'
print
print '/* The dots encircled by the corresponding cycle in cycles[]. */'
print 'static const mask_t encircled_dots[NUM_CYCLES] = {'
for x in encircled_dots:
print ' (mask_t){},'.format(x)
print '};'
print '#endif'
|
cf57274027adec7baaa811db08f86d508623281e | b73201020/codeingInterview | /Convert_Sorted_List_to_Binary_Search_Tree.py | 1,186 | 3.875 | 4 | # Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a list node
# @return a tree node
head = ListNode(-1)
def sortedListToBST(self, head):
self.head = head
return self.buildTree(head, self.count(head))
def count(self, head):
length = 0
if (head != None):
while(head.next != None):
length += 1
head = head.next
if(head != None):
length += 1
return length
def buildTree(self,head, length):
if (length == 0):
return None
tempNode = TreeNode(-1)
tempNode.left = self.buildTree(self.head,length/2)
tempNode.val = self.head.val
self.head = self.head.next
tempNode.right = self.buildTree(self.head,length - length/2 -1)
return tempNode
|
b99702f0903579ed555d88735483e101da922e97 | jlikes/randomApps | /fitnessApp.py | 2,473 | 3.5 | 4 | import math
#setter functions
def setGender():
global gender
while True:
print('\nAre you a (1) male or a (2) female?')
gender = input()
print(gender)
if(gender == '1'):
break
if(gender == '2'):
break
return gender
def setWeight():
print('\nHow much do you weigh? (in lbs)')
weight = input()
return float(weight) * .453592
def setHeight():
print('\nHow tall are you? (in inches)')
height = input()
return float(height) * 2.54
def setAge():
print('\nHow old are you?')
age = input()
return age
def setActivityLevel():
print('\nSelect an activity level: ')
print('1) Sedentary (Little or no Exercise)')
print('2) Lightly Active (Light exercise 1-3 days / week)')
print('3) Moderately Active (Moderate exercise 3-5 days / week)')
print('4) Very Active (Hard exercise 6-7 days / week)')
print('5) Extra Active (Very hard exercise / physical job or 2x training')
activity = input()
return activity
def calToMaintain():
if activity == '1':
calories = bmr*1.2
if activity == '2':
calories = bmr*1.375
if activity == '3':
calories = bmr*1.55
if activity == '4':
calories = bmr*1.725
if activity == '5':
calories = bmr*1.375
return calories
def calcBmr():
if gender == '1':
bmr = 66.47 + (13.7 * float(weight)) + (5 * float(height)) - (6.8 * float(age))
return bmr
elif gender == '2':
bmr = 655.1 + (9.6 * float(weight)) + (1.8 * float(height)) - (4.7 * float(age))
return bmr
#temporarily based on my own needs, will later take user input for requested breakdown
def calcMacro():
print('\nProtiens per meal = ', int((calories-500)*.5/4/6))
print('Carbs per meal = ', int((calories-500)*.4/4/6))
print('Fats per meal = ', int((calories-500)*.1/9/5))
#program begins here
gender = setGender()
weight = setWeight()
height = setHeight()
age = setAge()
activity = setActivityLevel()
bmr = calcBmr()
print()
calories = calToMaintain()
print('Calories required to maintain = ', int(calories))
print('Calories required to lose = ', int(calories) - 500)
print('Calories required to gain = ', int(calories) + 500)
calcMacro()
#debug
##print(gender)
##print(weight)
##print(height)
##print(age)
##print(activity)
##print(int(bmr))
|
b1345c1881f0581633359e0f8f6548e69ec68a41 | 7ossam39/Simple-calculator- | /calculator.py | 330 | 4.21875 | 4 | num1 = int(input(' Enter your num1 :'))
ope = input('Enter your ope :')
num2 = int(input(' Enter your num2 :'))
if ope == '+':
print(num1 + num2 )
elif ope == '-':
print(num1 - num2 )
elif ope == '*':
print(num1 * num2 )
elif ope == '/':
print(num1 / num2 )
input('Press enter to exit...')
|
0b9270332b75b16a3a4e00b3e102f34edc03439f | janvanboesschoten/Python3 | /h10_e1_count_emails.py | 700 | 3.65625 | 4 | fname = input("Enter file name: ")
try:
fhandle = open(fname)
except:
print('Cannot open file')
exit()
# putting the senders in a dictionary together with the number of meials they sent
counts = dict()
for line in (fhandle):
line = line.rstrip()
if not line.startswith('From:') :
continue
else:
words = line.split()
key = words[1]
counts[key] = counts.get(key,0) + 1
#print(counts)
# put the dictionary in a list rverse the order and print the personthat sent the most emails
ml = list()
for key, val in counts.items():
ml.append((val, key))
ml.sort(reverse = True)
for key, val in ml[0:1]:
print(val, key)
|
75454feda00f4aa144244055100820de8cbf635e | bencourtneighhh/AdventOfCode2020 | /day3/main.py | 839 | 3.90625 | 4 | def readFile(): # Reads the input as stores into an array
file = open("input.txt","r")
slope = []
for i in file.readlines():
slope.append(i[0:-1])
return slope
def main(addPos):
slope = readFile()
currentPos = [0,0]
treeCount = 0
while currentPos[0] < len(slope) - 1 :
# Current pos is moved, and index decreased if necessary to count for the looping of the map
currentPos[1] = (currentPos[1] + addPos[1]) % len(slope[0])
currentPos[0] += addPos[0] # Map is not vertically infinite
if slope[currentPos[0]][currentPos[1]] == "#":
treeCount += 1
return treeCount
def partOne():
print(main ([1,3]))
def partTwo():
total = main([1,1]) * main([1,5]) * main([1,3]) * main([1,7]) * main([2,1])
print(total)
#partOne()
partTwo()
|
ddb456019614d8c96f82d05046e04267d4dcb220 | xenonyu/leetcode | /topKFrequent.py | 1,435 | 3.515625 | 4 | import collections
from typing import List
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
stats = list(collections.Counter(nums).items())
heap = [(0, 0)]
def sift_up(heap, i):
val = heap[i]
while i >> 1 > 0 and val[1] < heap[i >> 1][1]:
heap[i] = heap[i >> 1]
i = i >> 1
heap[i] = val
def sift_down(heap, index, length):
val = heap[index]
while index << 1 < length:
l, r = index << 1, index << 1 | 1
small_child = r if r < length and heap[l][1] > heap[r][1] else l
if heap[small_child][1] < val[1]:
heap[index] = heap[small_child]
index = small_child
else:
break
heap[index] = val
for i in range(k):
heap.append(stats[i])
sift_up(heap, i + 1)
# print(heap)
for i in range(k, len(stats)):
# print(heap)
if stats[i][1] > heap[1][1]:
heap[1] = stats[i]
sift_down(heap, 1, k + 1)
# print(heap)
return [i[0] for i in heap[1:]]
if __name__ == '__main__':
test = Solution()
nums = [5, -3, 9, 1, 7, 7, 9, 10, 2, 2, 10, 10, 3, -1, 3, 7, -9, -1, 3, 3]
k = 3
res = test.topKFrequent(nums, k)
print(res)
|
fc8e8365cc918367d5c383a765e9335e8905e633 | lansatiankong/neural_kbqa | /code/movieqa/clean_entities.py | 1,154 | 3.734375 | 4 | #!/usr/bin/python
"""
Cleans up the entities file.
- Removes commas
- Deduplication of entities
- Converts everything to lowercase
- Sorts entities lexicographically
"""
import argparse
from sortedcontainers import SortedSet
from text_util import clean_word
def main(args):
NEWLINE = "\n"
entities_set = SortedSet([])
count_raw = 0
count_processed = 0
with open(args.input, 'r') as entities_file:
with open(args.output, 'w') as clean_entities_file:
for entity in entities_file:
count_raw += 1
entity_clean = clean_word(entity)
if len(entity_clean) > 0:
entities_set.add(entity_clean)
for entity in entities_set:
count_processed += 1
clean_entities_file.write(entity + NEWLINE)
print "COUNT_RAW: ", count_raw
print "COUNT_PROCESSED: ", count_processed
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Specify arguments')
parser.add_argument('--input', help='the raw entities.txt file', required=True)
parser.add_argument('--output', help='the processed clean_entities.txt file', required=True)
args = parser.parse_args()
main(args) |
5fb722562cb1200cdb89c907e8ceec98a1fa848e | alart27/ege_2020 | /python_files/informatics_mccme/problem_arrays_R.py | 1,266 | 3.828125 | 4 | """
Дан список целых чисел, число k и значение C.
Необходимо вставить в список на позицию с индексом k элемент,
равный C, сдвинув все элементы имевшие индекс не менее k вправо.
Посколько при этом количество элементов в списке увеличивается,
после считывания списка в его конец нужно будет добавить новый элемент,
используя метод append.
Вставку необходимо осуществлять уже в считанном списке,
не делая этого при выводе и не создавая дополнительного списка.
"""
def solution(array, k, c):
array.append(c)
for i in range(len(array) - 2, k - 1, -1):
temp = array[i]
array[i+1] = temp
array[k] = c
return array
def main():
a = [int(word) for word in input().split()]
b = [int(w) for w in input().split()]
k = b[0]
c = b[1]
ans = solution(a, k, c)
for n in ans:
print(n, end = ' ')
main()
|
782bde919732f4b13a6615ed4f9a3e55dc893426 | zjf201811/LeetCode__exercises | /小练习/螺旋矩阵.py | 422 | 3.640625 | 4 | # Author:ZJF
class Solution:
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
the_list=[]
while len(matrix)!=0:
n = matrix.pop(0)
the_list+=n
matrix = list(map(list,zip(*matrix)))
matrix.reverse()
return the_list
s = Solution()
print(s.spiralOrder([[1,2,3],[4,5,6],[7,8,9]])) |
9fbfcc1b501aab14aa61c488153585f446d855db | letoshelby/coursera-diving-in-python | /week 3/week 03_01.py | 2,345 | 3.53125 | 4 | # Задание по программированию: Классы и наследование
import csv
import os.path
TYPE_CAR = 'car'
TYPE_TRUCK = 'truck'
TYPE_SPEC_MACHINE = 'spec_machine'
class BaseCar:
def __init__(self, car_type):
self.car_type = car_type
self.photo_file_name = ''
self.brand = ''
self.carrying = 0.0
def set_photo_file_name(self, filename):
self.photo_file_name = filename
def set_brand(self, brand):
self.brand = brand
def set_carrying(self, carrying):
self.carrying = float(carrying)
def get_photo_file_ext(self):
return os.path.splitext(self.photo_file_name)[1]
class Car(BaseCar):
def __init__(self):
super().__init__(TYPE_CAR)
self.passenger_seats_count = 0
def set_passenger_seats_count(self, num_of_seats):
self.passenger_seats_count = int(num_of_seats)
class Truck(BaseCar):
def __init__(self):
super().__init__(TYPE_TRUCK)
self.body_width = 0.0
self.body_height = 0.0
self.body_length = 0.0
def set_body_width(self, width):
self.body_width = float(width)
def set_body_height(self, height):
self.body_height = float(height)
def set_body_length(self, length):
self.body_length = float(length)
def get_body_volume(self):
return self.body_width * self.body_height * self.body_length
class SpecMachine(BaseCar):
def __init__(self):
super().__init__(TYPE_SPEC_MACHINE)
self.extra = ''
def set_extra(self, extra):
self.extra = extra
def parse_row(row):
if len(row) is not 7:
return None
car = None
if row[0] == TYPE_CAR:
car = Car()
car.set_passenger_seats_count(row[2])
elif row[0] == TYPE_TRUCK:
car = Truck()
try:
w, h, l = row[4].split('x')
car.set_body_width(w)
car.set_body_height(h)
car.set_body_length(l)
except ValueError:
pass
elif row[0] == TYPE_SPEC_MACHINE:
car = SpecMachine()
car.set_extra(row[6])
else:
return None
car.set_brand(row[1])
car.set_photo_file_name(row[3])
car.set_carrying(row[5])
return car
def get_car_list(filename):
cars = list()
with open(filename) as csv_fd:
reader = csv.reader(csv_fd, delimiter=';')
next(reader) # skip csv header
for row in reader:
car = parse_row(row)
if car is not None:
cars.append(car)
return cars
|
5e094d437a29f79c36a72ebecdeb897d18dfb386 | hitochan777/kata | /leetcode/python/group-anagrams.py | 472 | 3.578125 | 4 | from collections import defaultdict, Counter
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
groups = defaultdict(list)
for s in strs:
key = tuple(sorted(list(Counter(s).items())))
groups[key].append(s)
return list(groups.values())
if __name__ == "__main__":
solver = Solution()
print(solver.groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
|
86960aaec888c88b37607ce7d652feba0d3324a6 | Unstopab/temp_c_to_f | /temp_c_to_f.py | 155 | 3.5 | 4 | degree_cels = input("請輸入攝氏溫度")
degree_cels = float(degree_cels)
degree_fahr = degree_cels * 9 / 5 + 32
print("華氏溫度為:", degree_fahr) |
a94cec00255f5040df4c55fb1849dca6fed62f52 | rafaelperazzo/programacao-web | /moodledata/vpl_data/423/usersdata/310/90249/submittedfiles/mdc.py | 228 | 3.96875 | 4 | # -*- coding: utf-8 -*-
import math
n1 = int(input('Digite n1: '))
n2 = int(input('Digite n2: '))
i = 1
while true:
i+=1
(n1%i)== (n2%i)==0
if i == n1 or i==n2:
break
print (i)
|
57d3c5b6670ba1b84e8c2c83200a9a4364b1e522 | piyushsingariya/code-practice | /python/learnthehardway/Ex40.py | 435 | 3.609375 | 4 | class Song(object):
def __init__(self, lyrics):
self.lyrics = lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
happ_bday = Song(["Happy birthday to you",
"Happy Birthday to you",
"Happy Birthday to you",
"Happy Birthday, dear ____ _____",
"Happy Birthday to you."])
happ_bday.sing_me_a_song() |
432ca418a17f99eb3c27bdd640cabe9770f4ac54 | subhamaharjan13/IW-pythonassignment | /Datatypes/Question3.py | 249 | 4.15625 | 4 | # Write a python program to get a string from a given string where all occurences of its first char have been changed to '$',
# except the first char itself.
string = 'restart'
print("Result string: ",string[0]+ string[1:].replace(string[0], "$")) |
fbfc54fafd1b04e67e625156e640bc7606707790 | weissab/coursera_genomics | /Reading_frames_and_repeasts/check_dna.py | 448 | 3.921875 | 4 | #!/c/Users/Andrea/Anaconda3/python
"""
add annotation here
have to write into command window: 'chmod a+x FILENAME'
adding this line makes the program executable
to run from command window: python FILENAME
"""
# add annotation here:
dna = input('Enter DNA sequence:')
if 'n' in or 'N' in dna:
nbases=dna.count('n') + dna.count('N')
print ("dna sequence has %d undefined bases " % nbases)
else:
print ("dna sequence has no undefined bases") |
dac9c1b6be52ef0fe30fba708b2783d4436d78aa | learnpython101/PythonFundamentals | /Module 03/Code snippets/Python Dictionary Methods/11 values().py | 1,044 | 4.5 | 4 | """"""
"""
The values() method returns a view object that displays a list of all the values in the dictionary.
The syntax of values() is:
dictionary.values()
values() Parameters
values() method doesn't take any parameters.
Return value from values()
values() method returns a view object that displays a list of all values in a given dictionary.
"""
# Example 1: Get all values from the dictionary
# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
print(sales.values())
# Example 2: How values() works when dictionary is modified?
# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
values = sales.values()
print(f'Original items: {values}')
# delete an item from dictionary
del[sales['apple']]
print(f'Updated items: {values}')
"""
The view object values doesn't itself return a list of sales item values
but it returns a view of all values of the dictionary.
If the list is updated at any time, the changes are reflected on the view object itself,
as shown in the above program.
"""
|
1421699ac02298e6cbbc0526cdfc37d57fd60d81 | vitocuccovillo/DataScienceBook | /Chapter4/SomeMath.py | 637 | 3.578125 | 4 |
def jaccard(u1, u2):
in_common = len(u1 & u2)
union = len(u1 | u2)
return in_common/float(union)
if __name__ == '__main__':
'''
NOTAZIONE:
- liste: lista = ["a","a","b"]
- insieme: set = {"a","b"} senza ripetizioni
- no_duplic = set(lista) trasforma da lista a set
'''
countries = ["ita","ita","eng","eng","usa","fra","fra","lux"]
dist_countries = set(countries)
print(dist_countries)
# crea un dizionario, chiave:valore
dict = {"a":"nicola","b":"vito","c":"paola"}
print(dict["a"])
u1 = {"a","b","c","d"}
u2 = {"a","f","d"}
print(jaccard(u1,u2))
|
112be294f9fa5ed7af3ba49f39d2264c2757c4c2 | bonnemai/MyPortfolio | /iress4.py | 1,766 | 3.734375 | 4 | import math
def delete(S, T):
for letter in S:
new_word=S.replace(letter, '', 1)
if new_word==T:
return letter
return None
def swap(S, T):
''' TODO: Check i>1... '''
for i in range(len(S)):
for j in range(i+1,len(S)):
new_word=list(S)
letter1=new_word[i]
letter2=new_word[j]
new_word[i]=letter2
new_word[j]=letter1
if ''.join(new_word)==T:
return 'SWAP ' +letter1 + ' ' + letter2
return 'IMPOSSIBLE'
print(swap('ab', 'ba'))
print(swap('abc', 'bac'))
print(swap('cab', 'cba'))
print(swap('cccccab', 'cccccba'))
print(swap('cab', 'dba')=='IMPOSSIBLE')
def solution(S, T):
if S==T:
return "NOTHING"
elif math.fabs(len(S)-len(T))>1:
return "IMPOSSIBLE"
elif len(S)>len(T):
# Try to DELETE¸
_del=delete(S, T)
if _del is None:
return "IMPOSSIBLE"
else:
return "DELETE "+_del
elif len(S)<len(T):
# Try to INSERT: equivalent of delete...
_del=delete( T, S)
if _del is None:
return "IMPOSSIBLE"
else:
return "INSERT "+_del
elif len(S)==len(T):
# Try to Swap
return swap(S, T)
return None
print(delete('niece', 'nice')=='e')
print(solution('niece', 'nice')=='DELETE e')
print(delete('abcd', 'efg')is None)
print(solution('abcd', 'efg')=='IMPOSSIBLE')
print(solution('nice', 'niece')=='INSERT e')
print(solution('form', 'from')=='SWAP o r')
print(solution('o', 'odd')=='IMPOSSIBLE')
print(solution('odd', 'odd')=='NOTHING')
print(solution('odd', 'odd1')=='INSERT 1')
print(solution('odd1', 'odd')=='DELETE 1')
print(solution('o', 'abcderfede')=='IMPOSSIBLE') |
e1c0270e392b490074aa8b6e73871c169c0eee61 | rosariovi/curso_python1 | /ciclo_for.py | 85 | 3.65625 | 4 | print("TABLA DEL 5")
for i in range (1,11):
a=i*5
print("5 * ", i, " = ", a)
|
6b7a817d61240ec4913404e9aa790428cb55a5b4 | Helbros72/24-10-21 | /Min_from_3_11_quest.py | 323 | 4.125 | 4 |
def _min_from_3 (x,y,z):
if x < y and x < z :
return (x)
elif y < x and y <z :
return (y)
else :
return (z)
x = int(input(' Enter first number :'))
y = int(input(' Enter second number :'))
z = int(input('Enter third number :'))
print (f' Your minimum number : {_min_from_3(x,y,z)}')
|
15c86dbea3792dcb8b3a33c8c4a8dd1a46fa06c0 | SnehaShree2501/HackerRankPythonPractice | /ListComprehensions.py | 360 | 3.921875 | 4 | x = int(input("Enter 1st co-ordinate"))
y = int(input("Enter 2nd co-ordinate"))
z = int(input("Enter 3rd ordinate"))
n = int(input("Enter the limit"))
ListOfNumbers =[]
ListOfNumbers = [[i,j,k] #list for the loop control variables
for i in range(0,x+1) #multiple loops running here
for j in range(0,y+1)
for k in range(0,z+1)
if i+j+k!=n ]
print(ListOfNumbers) |
d9afd4712eec7939651528303d49d996c4c2deb8 | maximdorko/Python | /Program2.py | 3,066 | 4.03125 | 4 | '''
# Loops
for i in [2,4,8,10]:
print("i = ",i)
# Using range
# range(10) means from 0 to 9
for i in range(10):
print("i = ",i)
# range (2,10) will start from 2 and goes up to 9
for i in range(2,10):
print("i = ", i)
# Print the odd numbers from 0 to 20
for num1 in range(1, 20):
if (num1 % 2) != 0:
print(num1)
# Request a user to input a number and convert it to float and print it rounded to 2 decimals
myfloat = input("Enter a number: ")
myfloat = float(myfloat)
print ("The number in float: {:.2f}".format(myfloat))
# Request user to enter their investment and interest rate
# Each year their investment will be increased by the investment + investment * interest rate
# Print the earnings after 10 years
investment = input ("Your investment?: ")
interestrate = input ("Interest rate?: ")
investment = float(investment)
interestrate = float(interestrate)
for years in range(1,11):
investment = investment + (investment * (interestrate/100))
print ("The earnings are: {:.2f}".format(investment))
# Deek's solution
# Ask for the money and the interest rate
money = float(input("How much to invest? "))
interestrate = float(input("Interest rate?: "))
# Convert the value to float anf round it to 2 decimals
interestrate = interestrate * .01
# Cycle through 10 years usin for loop and range 0 to 9
for years in range(10):
money = money + (money * interestrate)
# Output the results
print("Investment after 10 years: {:.2f}".format(money))
# Floating number are not precise: Only first 10 digits are reliable
num = 0.1 + 0.1 + 0.1 - 0.3
print(num)
# import random module
import random
# Generat a random number between 1 and 51 integer
rand_num = random.randrange(1, 51)
# Iterate until the we're at the random number
i = 1
while i != rand_num:
i += 1
# Print when we found the random number
print("The random number is: ",rand_num)
# Break and continue
# Print all odd numbers until 20, stop id number is 15
i = 1
while i <= 20:
if i%2 == 0:
i+=1
continue # This will jump back to the loop beginning and will ignore everything further
if i == 15:
break # This will jump out from the loop
print("The odd number: ",i) # This will be true if the number is not odd and not 15
i += 1
'''
###############################
# Pine tree printing #
###############################
# Ask for the tree height
tall = int(input("Tree height: "))
stump = tall - 1 # save the position of the stump
spaces = tall - 1 # The spaces are always actual height -1, at starting setting to requested height - 1
branches = 1 # branches are 1, 3, 5, 7, etc. Startin with 1
while tall != 0: # Cycle until tall is 0
tall -= 1 # decrese tall
for i in range(spaces): # printing spaces
print(' ',end="") # print without new line
for i in range(branches): # printing hashes
print('#',end="") # print without new line
spaces -= 1
branches +=2
print() # new line at the end of the level
for i in range(stump): # print the stump
print(" ",end="")
print("#")
|
c2b84076f1ca0b3ac9620c89dcd04f4aaa0156b0 | HandsomeLuoyang/Algorithm-books | /剑指offer/面试题59 - II. 队列的最大值.py | 866 | 3.921875 | 4 | import queue
class MaxQueue:
def __init__(self):
self.queue = queue.Queue()
self.dequeue = queue.deque()
def max_value(self) -> int:
return self.dequeue[0] if self.dequeue else -1
def push_back(self, value: int) -> None:
while self.dequeue and self.dequeue[-1] < value:
self.dequeue.pop()
self.dequeue.append(value)
self.queue.put(value)
def pop_front(self) -> int:
if self.queue.qsize() == 0:
return -1
q = self.queue.get()
if q == self.dequeue[0]:
self.dequeue.popleft()
return q
obj = MaxQueue()
print(obj.pop_front())
print(obj.pop_front())
print(obj.pop_front())
print(obj.pop_front())
print(obj.pop_front())
obj.push_back(15)
print(obj.max_value())
obj.push_back(9)
print(obj.max_value()) |
d5bea976843c81e9d703237054c209d71c23c1e9 | Adityasidher/LookingMass | /drivepath.py | 3,181 | 3.9375 | 4 | """ Return the drive names in the system
This file contains the methods used to grab the different drives using kivy's file explorer. Most of this code is original, however it was created using Kivy's documentation listed on their website, as well as reading into python's drive exploring capabilities. The code handles whether an operating system is windows, mac, or linux and adapts adequetly to allow file exploring to occur.
Typical usage example:
values: drivepath.get_drive_names()
on_text: fc.path = drivepath.get_path(self.text)
"""
from string import ascii_uppercase
from kivy.utils import platform
from os import listdir
if platform == 'win':
from ctypes import windll, create_unicode_buffer, c_wchar_p, sizeof
def get_win_drive_names():
"""Grabs windows drive names
This function will grab the different drive names for windows.
Windows handles drive assignment annoyingly compared to unix,
and requires custom parsing in order to grab all drives.
Args:
none, this is an assignment fnc that returns drive names
"""
volumeNameBuffer = create_unicode_buffer(1024)
fileSystemNameBuffer = create_unicode_buffer(1024)
serial_number = None
max_component_length = None
file_system_flags = None
drive_names = []
bitmask = (bin(windll.kernel32.GetLogicalDrives())[2:])[
::-1]
drive_letters = [ascii_uppercase[i] + ':/' for i,
v in enumerate(bitmask) if v == '1']
for d in drive_letters:
rc = windll.kernel32.GetVolumeInformationW(c_wchar_p(d), volumeNameBuffer, sizeof(volumeNameBuffer),
serial_number, max_component_length, file_system_flags,
fileSystemNameBuffer, sizeof(fileSystemNameBuffer))
if rc:
drive_names.append(
f'{volumeNameBuffer.value}({d[:2]})')
return drive_names
def get_drive_names():
"""Used by the application to assign a variable drive names
This function handles which operating system is being used,
linux/mac or windows and uses the applicable native functions
to list directory
Args:
none, this is an assignment fnc that assigns drives
"""
if platform == 'win':
names = get_win_drive_names()
elif platform == 'macosx':
names = listdir('/Volumes')
elif platform == 'linux':
names = ['/']
return names
def get_path(spinner_text):
"""Used by the application to grab paths of files
This function will grab the path of the selected file.
The path is generated different for each operating system
through a series of appended strings.
Args:
The input is the grabbed file name from the application
which is then used to generate the full path based on the OS
"""
if platform == 'win':
new_path = spinner_text[-3:-1] + '/'
elif platform == 'macosx':
new_path = '/Volumes/' + spinner_text
elif platform == 'linux':
new_path = spinner_text
return new_path
|
304b405eb84e694feecb69a0b678ad655fd5f147 | thepaul/noodle | /Noodle/dispatcher.py | 7,516 | 3.828125 | 4 | # dispatcher
#
# paul cannon <pcannon@novell.com>
# mar 2005
"""A way to make generic functions -- functions with different versions
depending on the types of the incoming arguments. Used with decorators.
The best way to explain is probably by example, so:
#!/usr/bin/env python2.4
from dispatcher import *
# This is made the default.
@generic
def foo(*args):
print "foo%s" % str(args)
# This is called when foo gets two arguments of type string.
@foo.with_types(str, str)
def bar(one, two):
print "bar(%s, %s)" % (one, two)
# This is called when foo gets four arguments, and the first, second,
# and fourth are 29, 13, and 14, respectively. The third can be anything.
@foo.with_values(29, 13, Any, 14)
def baz(one, two, three, four):
print "baz(%s, %s, %s, %s)" % (one, two, three, four)
# This is called when foo gets 2 or more arguments, and the first and
# last are of type int. ("Others" means any number of arguments of
# any type and value).
@foo.with_types(int, Others, int)
def bonk(*args):
print "bonk%s" % str(args)
# This is called when the arguments to foo match these conditions: the
# first is of type str, and the second is between 55 and 75.
@foo.with_conditions(TypeMatch(str), lambda arg: 55 < arg < 75)
def boo(*args):
print "boo%s" % str(args)
print "---------------------"
print "this should call foo:"
foo('hello', 12)
print "---------------------"
print "this should call bar:"
foo('hello', 'world')
print "---------------------"
print "this should call baz:"
foo(29, 13, {'big': 'extra', 'arg': 'in here'}, 14)
print "---------------------"
print "this should call bonk:"
foo(29, 13, 14, 'what a world', 12)
print "---------------------"
print "this should call bonk:"
foo(29, 12)
print "---------------------"
print "this should call foo:"
foo('blob', 55)
print "---------------------"
print "this should call boo:"
foo('blob', 56)
So the process is: decorate the default version of the function with
@dispatcher.generic. After that, you can use several attributes of
that function in order to add other possibilities to the generic
function: with_types, with_values, and with_conditions.
Each function can still be called normally after becoming a candidate
for the generic function.
Note that this causes some confusion when used with methods of a class:
when normally bound, the 'self' argument is automatically inserted, so
your with_* decorators need to allow for that argument. If you don't
want to need to deal with that, use the @dispatcher.genericmethod
decorator instead. This will cause the first parameter for each call
to be treated specially- it won't be compared against any of the items
in the specified argument values, types, etc.
"""
class Any:
"""Pass this as an argument to a generic function's with_* decorators
to indicate that "Any" one argument can match in that position.
"""
class Others:
"""Pass this as an argument to a generic function's with_* decorators
to indicate that any number of arguments of any sort (or zero arguments)
can match in that position.
"""
class _Candidate:
"""A candidate for a default generic function."""
def __call__(self, func):
"""This is called when the candidate is finally applied as a
decorator; it just stores the function in itself. The master
generic function already has a reference to this object, so
this is sufficient.
"""
self.func = func
return func
def _get_index_of(seq, item):
for num, member in enumerate(seq):
if member == item:
return num
return -1
class _ArgumentBasedCandidate(_Candidate):
def __init__(self, specd_args):
othersloc = _get_index_of(specd_args, Others)
if othersloc < 0:
self.begin_args = specd_args
self.end_args = []
self.extra_args_ok = False
else:
self.begin_args = specd_args[:othersloc]
self.end_args = specd_args[othersloc+1:]
self.extra_args_ok = True
def lenmatches(self, given_args):
combined_len = len(self.begin_args) + len(self.end_args)
return ((len(given_args) == combined_len) or
(self.extra_args_ok and len(given_args) > combined_len))
def matches(self, arglist):
if not self.lenmatches(arglist):
return False
for inarg, reqtype in zip(arglist, self.begin_args):
if not self.arg_ok(inarg, reqtype):
return False
for inarg, reqtype in zip(arglist[-len(self.end_args):], self.end_args):
if not self.arg_ok(inarg, reqtype):
return False
return True
class _TypeMatcher(_ArgumentBasedCandidate):
def __init__(self, argtypes):
_ArgumentBasedCandidate.__init__(self, argtypes)
def arg_ok(self, given, required):
return (isinstance(given, required) or required == Any)
class _ValueMatcher(_ArgumentBasedCandidate):
def __init__(self, argvals):
_ArgumentBasedCandidate.__init__(self, argvals)
def arg_ok(self, given, required):
return (given == required or required == Any)
class _FuncMatcher(_ArgumentBasedCandidate):
def __init__(self, args):
_ArgumentBasedCandidate.__init__(self, args)
def arg_ok(self, given, required):
return required(given)
def ValueMatch(required_val):
"""Call this function within the spec arguments to the
with_conditions decorator to create a value checker.
"""
def do_value_match(given):
return given == required_val
return do_value_match
def TypeMatch(required_type):
"""Call this function within the spec arguments to the
with_conditions decorator to create a type checker; it checks
for any objects of the given type or a subtype.
"""
def do_type_match(val):
return isinstance(val, required_type)
return do_type_match
# Note: this was done with closures instead of a class because, (a), I like
# it that way, and (b), the returned function is actually a function, which
# means it can be normally bound as a method when found in a class. Class
# instances--even callable ones--aren't made bound methods in a class
# definition.
def generic(func, _skip=0):
candidates = []
candidatetypes = {
'with_types': _TypeMatcher,
'with_values': _ValueMatcher,
'with_conditions': _FuncMatcher
}
def _candidate_creator_factory(candidatetype):
def _candidate_creator_decorator(*args):
def _new_candidate(c):
candidates.append(c)
return c
return _new_candidate(candidatetype(args))
return _candidate_creator_decorator
def choose(*args):
for candidate in candidates:
if candidate.matches(args[_skip:]):
return candidate.func(*args)
return func(*args)
for name, klass in candidatetypes.items():
setattr(choose, name, _candidate_creator_factory(klass))
choose.func_name = 'generic_%s' % func.func_name
return choose
def genericmethod(func):
"""Generic function which is usable as a normally bound method: it skips
checking of the first argument, since that will be the self argument.
"""
return generic(func, _skip=1)
# vim: set et sw=4 ts=4 :
|
bc6f2014e01eda6010242b3dd1e5cd2aa239e778 | kim-seoyoon/study-python | /sample_canvas_simplegui.py | 339 | 3.5 | 4 | # example of drawing on the canvas
import simplegui
#define draw handler
def draw(canvas):
canvas.draw_text("Hello!",[100,100],24,"White")
canvas.draw_circle([100,100],2,2,"Blue")
# create frame
frame=simplegui.create_frame("test",300,200)
# register draw handler
frame.set_draw_handler(draw)
#start frame
frame.start()
|
42c8e4a90399f13740fb735dfb6eb82de4f7b7ce | JasonLinden/FlaskAPI_DataStructures | /linked_list.py | 2,006 | 3.96875 | 4 | class Node:
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
class LinkedList:
def __init__(self):
self.head = None
self.last_node = None
def print_self(self):
ll_string = ""
node = self.head
if node is None:
print(None)
while node:
ll_string += f" {str(node.data)} ->"
node = node.next_node
ll_string += " None"
print(ll_string)
def insert_beginning(self, data):
if self.head is None:
self.head = Node(data, None)
self.last_node = self.head
else:
new_node = Node(data, self.head)
self.head = new_node
def insert_at_end(self, data):
if self.head is None:
self.insert_beginning(data)
if self.last_node is None:
node = self.head
while node.next_node:
node = node.next_node
node.next_node = Node(data, None)
self.last_node = node.next_node
else:
self.last_node.next_node = Node(data, None)
self.last_node = self.last_node.next_node
def to_list(self):
l = []
if self.head is None:
return l
node = self.head
while node:
l.append(node.data)
node = node.next_node
return l
def get_user_by_id(self, user_id):
node = self.head
while node:
if node.data["id"] is int(user_id):
return node.data
node = node.next_node
return None
# ll = LinkedList()
# ll.insert_beginning("1")
# ll.insert_beginning("2")
# ll.insert_beginning("3")
# ll.insert_beginning("4")
# ll.insert_beginning("5")
# ll.insert_beginning("6")
# ll.insert_beginning("7")
# ll.insert_beginning("8")
# ll.insert_at_end("end")
# ll.insert_at_end("end1")
# ll.print_self()
# print(ll.head.data)
# print(ll.last_node.data)
|
709fceb003c5c214fe96df2cba1fa348c30cb4b7 | Borleonid/Conversor | /conversor.py | 2,105 | 4 | 4 | def convierte():
print()
numero=input("Introduce un número:\n")
sistema=input("Introduce un sistema:\n1-Binario a decimal.\n2-Octal a decimal\n3-Hexadecimal a decimal.\n4-Base 32 a decimal.\n5-Salir.\n\n")
if sistema == "1":
sistema=2
final = int(numero,sistema)
print ("El número binario ", numero, " es el número ", final, " en decimales.")
elif sistema == "2":
sistema = 8
final = int(numero,sistema)
print ("El número octal ", numero, " es el número ", final, " en decimales.")
elif sistema == "3":
sistema = 16
final = int(numero,sistema)
print ("El número hexadecimal ", numero, " es el número ", final, " en decimales.")
elif sistema == "4":
sistema = 32
final = int(numero,sistema)
print ("El número con base 32 ", numero, " es el número ", final, " en decimales.")
elif sistema == "5":
pass
else:
print("No has introducido una opción válida.")
def binario_decimal():
numero=int(input("Introduce un número:\n"))
convertido=bin(numero)[2:]
print(convertido)
def octal_decimal():
numero=int(input("Introduce un número:\n"))
convertido=oct(numero)[2:]
print(convertido)
def hexadecimal_decimal():
numero=int(input("Introduce un número:\n"))
convertido=hex(numero)[2:]
print(convertido)
def menu():
print("Elige una opción:\n",
"1-Conversiones a decimal.\n",
"2-Conversión de decimal a binario.\n",
"3-Conversión de decimal a octal.\n",
"4-Conversión de decimal a hexadecimal.\n",
"5-Salir.\n")
opcion=input("Escribe un número y pulsa enter: ")
if opcion == "1":
convierte()
elif opcion == "2":
binario_decimal()
elif opcion == "3":
octal_decimal()
elif opcion == "4":
hexadecimal_decimal()
elif opcion == "5":
pass
else:
print("No has introducido una opción válida.")
menu()
|
1a34b83bf081ea56b61cb3896349d8f80a36be97 | SiaN07/Algorithms | /countvowels.py | 288 | 4.25 | 4 | '''
Count number of vowels in a string
'''
def countvowels(string):
vowels = set('aeiouAEIOU')
count = 0
for char in string:
if char in vowels:
count = count + 1
print("The number of vowels is", count)
string = "The red pie"
countvowels(string)
|
410d343198a94692272297c5a9b257fe79395e60 | cs1531/learn-python | /v02/repeated_digit_addition_adv.py | 1,362 | 4.1875 | 4 | '''
Write a program that accepts a single digit `a` from the user and
computes the value of a + aa + aaa
E.g. if a = 7, then the output should be 861, which is equal to 7 + 77 + 777
You may assume that user input is always a single digit
HINT: There are many different ways to solve this problem. Try...
1. String concatenation, i.e. string addition in Python
2. String formatting, e.g. f'{variable}'
3. Without using any string manipulations, i.e. solve mathematically
'''
# Solution 1: using string concatenation
a = input('Enter a digit: ')
n1 = int(a)
n2 = int(a + a)
n3 = int(a + a + a)
print(n1 + n2 + n3)
# Solution 2: using string formatting
a = input('Enter a digit: ')
n1 = int(f'{a}')
n2 = int(f'{a}{a}')
n3 = int(f'{a}{a}{a}')
print(n1 + n2 + n3)
# Solution 3: using C-style string formatting
a = input('Enter a digit: ')
n1 = int( '%s' % a )
n2 = int( '%s%s' % (a, a) )
n3 = int( '%s%s%s' % (a, a, a) )
print(n1 + n2 + n3)
# Solution 4: using string multiplication
a = input('Enter a digit: ')
n1 = int(a)
n2 = int(a * 2)
n3 = int(a * 3)
print(n1 + n2 + n3)
# Solution 5: for mathematicians
a = int(input('Enter a digit: '))
print(1 * a + 11 * a + 111 * a)
# Solution 6: one-liner (NOT recommended since not readable)
print(123 * int(input('Enter a digit: '))) |
1063438ebb7bf1b41bf7beb53b7a2622f2a13eef | JoaozinhoProgramation/Exercios_LP_1B | /Exerc11.py | 148 | 3.640625 | 4 | produto = float(input("Preço do produto:"))
produto = (((produto * 5)/100) - produto)
print("Seu produto com 5% de desconto é {}".format(produto)) |
a2c5e65259e50b0daa084c568bedefbe10b6c224 | yojimbo88/ICTPRG-Python | /w4q1.py | 171 | 3.625 | 4 | x = 0
while x < 26: # while loop that will only stop once variable x reaches 25
print(x)
x = x + 1
# Tomas Franco 101399521
# for x in range(26):
# print(x)
|
5193f2334468101c9c954fe3fea131dfa15908a8 | pingrunhuang/fluent-python | /07-closure-deco/running_average_closure.py | 1,310 | 3.5 | 4 | """
>>> avg = make_averager()
>>> avg(10)
10.0
>>> avg(11)
10.5
>>> avg(12)
11.0
>>> avg.__code__.co_varnames
('new_value', 'total')
>>> avg.__code__.co_freevars
('series',)
>>> avg.__closure__ # doctest: +ELLIPSIS
(<cell at 0x...: list object at 0x...>,)
>>> avg.__closure__[0].cell_contents
[10, 11, 12]
"""
DEMO = """
>>> avg.__closure__
(<cell at 0x107a44f78: list object at 0x107a91a48>,)
"""
def make_averager():
series = []
def averager(new_value:'float > 0'=0)->float:
series.append(new_value)
total = sum(series)
return total/len(series)
return averager
def make_averager_v2():
"""
UnboundLocalError: local variable 'total' referenced before assignment
modifying number or immutable object in closure is not allowed (list is mutable)
"""
total = 0
num = 0
def averager(new_value):
total += new_value
num += 1
return total / num
return averager
def make_averager_v3():
"""
this is why we need the nonlocal keyword
"""
total = 0
num = 0
def averager(new_value):
nonlocal total, num
total += new_value
num += 1
return total / num
return averager
if __name__ == "__main__":
avg = make_averager_v3()
print(avg(10))
print(avg(11)) |
36cfd696405eb7db04fac6f62915a6efbbc4375c | tabinda-s/assignments | /superheropowers.py | 415 | 3.53125 | 4 | import json
# read file
with open('superheroes.json', 'r') as f:
superheroes = json.load(f)
data = []
# define members
members = superheroes['members']
# loop through members and list powers
for member in members:
powers = member['powers']
# loop through powers and print
for power in powers:
data.append(power)
unique_powers = set(data)
unique_powers_list = list(unique_powers)
print(unique_powers_list) |
ef83e5d1e8df9faba407c6b8febeadde0bea9de6 | jhyang12345/algorithm-problems | /problems/queue_two_stacks.py | 565 | 3.90625 | 4 | class Queue:
def __init__(self):
self.stack_in = []
self.stack_out = []
def enqueue(self, val):
self.stack_in.append(val)
def dequeue(self):
if self.stack_out:
return self.stack_out.pop()
while self.stack_in:
self.stack_out.append(self.stack_in.pop())
return self.stack_out.pop()
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
print(q.dequeue())
q.enqueue(4)
print(q.dequeue())
print(q.dequeue())
q.enqueue(5)
q.enqueue(6)
print(q.dequeue())
print(q.dequeue())
q.enqueue(7)
print(q.dequeue())
print(q.dequeue())
|
bda5042b4e1e3548c810fd9498eaf840354e0510 | AlejoGomezV/Principios-SOLID | /0001A.py | 403 | 3.84375 | 4 | class Duck:
def __init__(self, name):
self.name = name
def fly(self):
print(f"{self.name} is flying not very high")
def swim(self):
print(f"{self.name} swims in the lake and quacks")
def do_sound(self) -> str:
return "Quack"
def greet(self, duck2: Duck):
print(f"{self.name}: {self.do_sound()}, hello {duck2.name}")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.